将属性与用户的电子邮件一起使用

我已经看到[Authorize]属性采用了这样的AuthorizeAttribute.User属性[Authorize("User=Alice, Bob")] (其中Alice / Bob是用户名,我猜?)。 但是,在我的应用程序中,我注册的是用户的电子邮件地址。

[Authorize("User=...")]采取其他属性? 是否可以接收电子邮件(并且[Authorize("User=alice@example.org, bob@example.org")] ?毫不奇怪, MSDN页面不是很有帮助。

这是内置的这个function,还是我必须实现自己的自定义Authorize属性? 在上面链接的非常简短的MSDN页面上,Authorize属性上是否有完整参数列表的文档?

我认为这里没有区别……“james.doe@example.com”是一个字符串,同样“James Doe”是一个字符串,两者都在User属性上使用。

这就是说,如果你想拥有自己的属性,例如UserName那么只需从Authorize属性派生一个新的Attribute类,并用你自己的授权逻辑添加你自己的属性。

资源:

  • MVC 4:授权属性(PluralSightvideo)
  • MVC 5:授权属性(PluralSightvideo)
  • ASP.NET MVC安全性

示例:自定义授权属性


HomeController.cs

 public class HomeController : Controller { [CustomAuthorize(FirstNames = "Aydin")] public ActionResult Index() { return View(); } } 

ApplicationUser.cs || User.cs

 public class User : IdentityUser { public string FirstName { get; set; } public async Task GenerateUserIdentityAsync(UserManager manager) { ClaimsIdentity userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); userIdentity.AddClaim(new Claim("FirstName", this.FirstName)); return userIdentity; } } 

CustomAuthorizeAttribute.cs

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public class CustomAuthorizeAttribute : FilterAttribute, IAuthorizationFilter { private static readonly char[] SplitParameter = new char[1] {','}; private string firstNames; private string[] firstNamesSplit = new string[0]; public string FirstNames { get { return this.firstNames ?? string.Empty; } set { this.firstNames = value; this.firstNamesSplit = SplitString(value); } } ///  Called when a process requests authorization.  public virtual void OnAuthorization(AuthorizationContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } if (OutputCacheAttribute.IsChildActionCacheActive(filterContext)) { throw new InvalidOperationException("Cannot use with a ChildAction cache"); } if (filterContext.ActionDescriptor.IsDefined(typeof (AllowAnonymousAttribute), true) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof (AllowAnonymousAttribute), true)) { return; } if (this.AuthorizeCore(filterContext.HttpContext)) { HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache; cache.SetProxyMaxAge(new TimeSpan(0L)); cache.AddValidationCallback(this.CacheValidateHandler, null); } else this.HandleUnauthorizedRequest(filterContext); } ///  When overridden, provides an entry point for custom authorization checks.  protected virtual bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) throw new ArgumentNullException("httpContext"); IPrincipal user = httpContext.User; if (!user.Identity.IsAuthenticated) return false; string claimValue = ClaimsPrincipal.Current.FindFirst("FirstName").Value; return this.firstNamesSplit.Length <= 0 || this.firstNamesSplit.Contains(claimValue, StringComparer.OrdinalIgnoreCase); } private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus) { validationStatus = this.OnCacheAuthorization(new HttpContextWrapper(context)); } ///  Processes HTTP requests that fail authorization.  protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext) { filterContext.Result = new HttpUnauthorizedResult(); } ///  Called when the caching module requests authorization.  ///  A reference to the validation status.  protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext) { if (httpContext == null) throw new ArgumentNullException("httpContext"); return !this.AuthorizeCore(httpContext) ? HttpValidationStatus.IgnoreThisRequest : HttpValidationStatus.Valid; } private string[] SplitString(string original) { if (string.IsNullOrEmpty(original)) return new string[0]; return original.Split(SplitParameter) .Select(splitItem => new { splitItem, splitItemTrimmed = splitItem.Trim() }) .Where (value => !string.IsNullOrEmpty(value.splitItemTrimmed)) .Select(value => value.splitItemTrimmed).ToArray(); } }