将[授权]属性与用户的电子邮件一起使用

时间:2016-02-07 14:41:38

标签: c# asp.net .net asp.net-mvc asp.net-web-api

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

[Authorize("User=...")]是否会使用其他属性?是否可以接收电子邮件(并[Authorize("User=alice@example.org, bob@example.org")]?不出所料,MSDN page并没有太大帮助。

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

1 个答案:

答案 0 :(得分:3)

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

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

资源:

示例:自定义授权属性

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