Skip to main content
 首页 » 编程设计

c#之将 [Authorize] 属性与用户的电子邮件一起使用

2024年05月10日41三少

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

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

这是内置功能,还是我必须实现自己的自定义授权属性?除了我在上面链接的非常少的 MSDN 页面之外,是否有关于 Authorize 属性的完整参数列表的任何文档?

请您参考如下方法:

我看不出这里有什么区别...“james.doe@example.com”是一个字符串,就像“James Doe”是一个字符串一样,两者都用于 User 属性。

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

资源:


示例:自定义授权属性


家庭 Controller .cs

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

应用程序用户.cs ||用户.cs

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; 
    } 
} 

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); 
        } 
    } 
 
    /// <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(); 
    } 
}