我已经看到该[Authorize]
属性采用这样的AuthorizeAttribute.User属性[Authorize("User=Alice, Bob")]
(其中Alice
/Bob
是用户名,我猜是吗?)。但是,在我的应用程序中,我注册的只是用户的电子邮件地址。
是否[Authorize("User=...")]
具有其他属性?它可以接收电子邮件[Authorize("[email protected], [email protected]")]
吗(并且这样做?毫不奇怪,MSDN页面不是很有帮助。
这是内置的功能,还是我必须实现自己的自定义Authorize属性?我上面链接的MSDN页面很少,是否有关于Authorize属性上完整参数列表的文档?
我在这里看不到任何区别...“ [email protected]”是一个字符串,就像“ James Doe”是一个字符串一样,两者都用于User属性。
就是说,如果您想拥有自己的属性,例如,UserName
只需从Authorize
属性派生新的Attribute类,然后使用自己的授权逻辑添加自己的属性。
资源:
public class HomeController : Controller
{
[CustomAuthorize(FirstNames = "Aydin")]
public ActionResult Index()
{
return View();
}
}
public class User : IdentityUser
{
public string FirstName { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
{
ClaimsIdentity userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
userIdentity.AddClaim(new Claim("FirstName", this.FirstName));
return userIdentity;
}
}
[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);
}
}
/// <summary> Called when a process requests authorization. </summary>
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);
}
/// <summary> When overridden, provides an entry point for custom authorization checks. </summary>
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));
}
/// <summary> Processes HTTP requests that fail authorization. </summary>
protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new HttpUnauthorizedResult();
}
/// <summary> Called when the caching module requests authorization. </summary>
/// <returns> A reference to the validation status. </returns>
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();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句