本文介绍了使用[授权]与用户的电子邮件属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过的 [授权] 属性采取AuthorizeAttribute.User财产这样的 [授权(用户=爱丽丝,鲍勃) ] (其中爱丽丝 / 鲍勃的用户名,我猜?)。然而,在我的应用我注册的是用户的电子邮件地址。

I've seen the [Authorize] attribute take an AuthorizeAttribute.User property like this [Authorize("User=Alice, Bob")] (where Alice/Bob are usernames, I guess?). However, in my app all I register is the user's email address.

确实 [授权(用户= ...)] 采取其他属性?它可以采取电子邮件(做 [授权([email protected][email protected])] ?毫不奇怪,的是不是非常有帮助。

Does [Authorize("User=...")] take other properties? Can it take email (and do [Authorize("[email protected], [email protected]")]? Not surprisingly, the MSDN page was not very helpful.

这是此功能的内置,要不然我就必须实现自己的自定义属性的授权?是否有对授权属性在过去紧缺MSDN页面我上面链接的完整参数列表中的任何文档?

It's this functionality built-in, or will I have to implement my own custom Authorize attribute? Is there any documentation for a full parameter list on the Authorize attribute past the very scanty MSDN page I linked above?

推荐答案

我在这里[email protected]是一个字符串,就像很多詹姆斯母鹿是一个字符串,既看不出差别对用户财产被使用。

I see no difference here... "[email protected]" is a string, just as much "James Doe" is a string, both being used on the User property.

如果你想拥有自己的财产,如用户名然后简单地推导出从授权一个新的属性类属性并用自己的授权逻辑添加自己的属性。

That said if you want to have your own property, e.g.UserName then simply derive a new Attribute class from the Authorize attribute and add your own properties with your own authorization logic.

资源:





  • MVC 4: Authorization Attribute (PluralSight Video)
  • MVC 5: Authorization Attribute (PluralSight Video)
  • ASP.NET MVC Security
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();
    }
}

这篇关于使用[授权]与用户的电子邮件属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 10:16