none
ASP.NET Core Claims-Based Authorization 怎么针对Claims返回特定的错误信息 RRS feed

  • 问题

  • 大家好,我在使用ASP.NET Core,UseJwtBearerAuthentication做权限验证时,遇到个问题:

    首先,我在Startup.cs中的Configure方法,配置了三个Policy,如下:

             services.AddAuthorization(options =>
                {
                    options.AddPolicy("License", policy => policy.RequireClaim("IsLicense", true.ToString()));
                    options.AddPolicy("Administrator", policy => policy.RequireClaim("IsAdministrator", true.ToString()));
                    options.AddPolicy("Caller", policy => policy.RequireClaim("IsCaller", true.ToString()));
                });

    在WebApi接口中,使用了其中两个Claim,License与Administrator,如下:

            [HttpPost]
            [Authorize(Policy = "License")]
            [Authorize(Policy = "Administrator")]
    现在我希望在某个Claims验证失败的时候,除了返回401,还能带有自定义的错误信息,请问有参考解决方案么?



    • 已编辑 yhnbgfd 2017年5月5日 3:45
    2017年5月5日 3:44

全部回复

  • 你好,

    这种情况下您需要写自定义授权策略来实现,然后更改Response,您可以参考以下代码

    services.AddAuthorization(options => { options.AddPolicy("License", policy => policy.Requirements.Add(new LiceneseRequirement())); options.AddPolicy("Administrator", policy => policy.Requirements.Add(new AdministratorRequirement())); });

    public class LiceneseRequirement : AuthorizationHandler<LiceneseRequirement>, IAuthorizationRequirement { public LiceneseRequirement() { } protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, LiceneseRequirement requirement) { await Task.Run(() => { if (!context.User.HasClaim("IsLicense", "True")) { //输出自定义信息 var bytes = System.Text.ASCIIEncoding.UTF8.GetBytes("License Validate Faild!"); var response = ((Microsoft.AspNetCore.Mvc.ActionContext)context.Resource).HttpContext.Response; response.StatusCode = 401; response.Body.Write(bytes, 0, bytes.Length); context.Fail(); return; } context.Succeed(requirement); }); } } public class AdministratorRequirement : AuthorizationHandler<AdministratorRequirement>, IAuthorizationRequirement { public AdministratorRequirement() { } protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, AdministratorRequirement requirement) { await Task.Run(() => { if (!context.User.HasClaim("IsAdministrator", "True")) { var bytes = System.Text.ASCIIEncoding.UTF8.GetBytes("You are not administrator!"); var response = ((Microsoft.AspNetCore.Mvc.ActionContext)context.Resource).HttpContext.Response; response.StatusCode = 401; response.Body.Write(bytes, 0, bytes.Length); context.Fail(); return; } context.Succeed(requirement); }); } }

    您也可以参考下面这个链接:

    https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies


    2017年5月12日 3:13
    版主