Web API授权属性不适用于Action

Hei*_*ich 5 asp.net asp.net-mvc authorize-attribute asp.net-web-api

[Authorize]在我的WebAPI控制器操作上使用该属性,它总是未经授权返回.

这是我的行动

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

这是我在全局MessageHandler中设置授权的地方.这是为了测试我正在测试用户.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

注册Global.asax.csApplication_Start

GlobalConfiguration.Configuration.MessageHandlers.Add(new MyProject.AuthenticationHandler1());
Run Code Online (Sandbox Code Playgroud)

它一直显示这个消息

{"Message":"Authorization has been denied for this request."}
Run Code Online (Sandbox Code Playgroud)

Hei*_*ich 3

我创建了一个自定义授权属性并且它有效。

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样使用它

[AuthorizationAttribute(Roles = "SomeRole,Admin")]    
public IQueryable<Country> GetCountries()
    {
     }
Run Code Online (Sandbox Code Playgroud)