asp.net - Web API 授权属性不适用于操作

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

我在 WebAPI Controller 操作上使用 [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;
    }
}

Application_Start 中的 Global.asax.cs 中注册

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

它一直显示一条消息

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

最佳答案

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

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

关于asp.net - Web API 授权属性不适用于操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27804506/

相关文章:

c# - 从 .ashx 压缩 Javascript 在浏览器中返回解码错误

asp.net - 在混合Webforms MVC应用程序中使用IExceptionFilter

c# - 不会保存编辑

asp.net-mvc - 如何使用 Ninject 拦截来拦截所有 ASP.NET WebApi Controller 操作方法调用以进行日志记录?

javascript - 将 cookie 写入 ashx 文件

c# - 是否可以使用 itextSharp 将 PDF 页面转换为图像?

asp.net - JavaScript 和 ASP.NET 控件前缀中的 "this"

MVC 布局中的 CSS 命名最佳实践

c# - 在 WebApi 方法中调用异步方法

c# - 使用 Autofac 将 WebAPI UrlHelper 注入(inject)服务