【问题标题】:Web API Authorize Attribute not working on ActionWeb API 授权属性不适用于操作
【发布时间】:2015-01-06 18:06:51
【问题描述】:

我在我的 WebAPI 控制器操作中使用 [Authorize] 属性,但它总是在未经授权的情况下返回。

这是我的行动

    [Authorize(Roles = "Admin")]
    public IQueryable<Country> GetCountries()
    {
      return db.Countries;
    }

这是我在全局消息处理程序中设置授权的地方。这是为了测试我正在放入一个测试用户。

public class AuthenticationHandler1 : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {

        if (!HttpContext.Current.User.Identity.IsAuthenticated)
        {
            HttpContext.Current.User = TestClaimsPrincipal();
        }


        return base.SendAsync(request, cancellationToken);
    }

    private ClaimsPrincipal TestClaimsPrincipal()
    {

        var identity = new ClaimsIdentity(HttpContext.Current.User.Identity.AuthenticationType);
        identity.AddClaim(new Claim(ClaimTypes.Name, "some.user"));
        identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
        identity.AddClaim(new Claim(ClaimTypes.Role, "Supervisor"));
        var testIdentity = new ClaimsIdentity(identity);

        var myPrincipal = new ClaimsPrincipal(testIdentity);

        return myPrincipal;
    }
}

Global.asax.csApplication_Start注册

GlobalConfiguration.Configuration.MessageHandlers.Add(new MyProject.AuthenticationHandler1());

它一直显示这个消息

{"Message":"Authorization has been denied for this request."}

【问题讨论】:

  • 我的内置 Authorize 属性也有同样的问题,我不应该创建自定义属性

标签: asp.net asp.net-mvc asp.net-web-api authorize-attribute


【解决方案1】:

我创建了一个自定义授权属性,它可以工作。

public class AuthorizationAttribute : System.Web.Http.AuthorizeAttribute
{
    public string Roles { get; set; }
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        ClaimsPrincipal currentPrincipal = HttpContext.Current.User as ClaimsPrincipal;
        if (currentPrincipal != null && CheckRoles(currentPrincipal))
        {
            return true;
        }
        else
        {
            actionContext.Response =
                new HttpResponseMessage(
                System.Net.HttpStatusCode.Unauthorized)
                {
                    ReasonPhrase = "Some message"
                };
            return false;
        }
    }

    private bool CheckRoles(ClaimsPrincipal principal)
    {
        string[] roles = RolesSplit;
        if (roles.Length == 0) return true;
        return roles.Any(principal.IsInRole);
    }

    protected string[] RolesSplit
    {
        get { return SplitStrings(Roles); }
    }

    protected static string[] SplitStrings(string input)
    {
        if(string.IsNullOrWhiteSpace(input)) return new string[0];
        var result = input.Split(',').Where(s=>!String.IsNullOrWhiteSpace(s.Trim()));
        return result.Select(s => s.Trim()).ToArray();
    }
}

这样使用

[AuthorizationAttribute(Roles = "SomeRole,Admin")]    
public IQueryable<Country> GetCountries()
    {
     }

【讨论】:

    猜你喜欢
    • 2014-10-28
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 2019-08-12
    • 2021-02-01
    相关资源
    最近更新 更多