2020-04-30

netcore 下的policy授权自定义返回结果

netcore 下的policy授权自定义返回结果


目前一直在用policy做权限校验,但是好像组里需要将返回结果统一,之前用的都是直接继承AuthorizationHandler然后调用context.Fail(),但是这样会导致没办法自定义返回结果比如{code:403,msg:'未授权',data:null},

也百度了下https://q.cnblogs.com/q/120091/ 这里也说了3.0后就改掉了之前可以通过result来返回,但是现在不行了,之后又查了下资料无果,今天心血来潮直接用httpcontext来返回结果可以了。。。。。

直接上代码吧

 public class ApiUrlPermissionHandler : AuthorizationHandler<ApiUrlPermissionRequirement> {  private readonly IHttpContextAccessor _accessor;  private readonly ILogger<ApiUrlPermissionHandler> _logger;  private readonly IPermissionWatchDog _permissionWatchDog;  public ApiUrlPermissionHandler(IHttpContextAccessor accessor,ILogger<ApiUrlPermissionHandler> logger, IPermissionWatchDog permissionWatchDog)  {   this._accessor = accessor;   this._logger = logger;   this._permissionWatchDog = permissionWatchDog;  }  protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, ApiUrlPermissionRequirement requirement)  {   var httpContext = _accessor.HttpContext;   var isAuthenticated = context.User.Identity.IsAuthenticated;   if (isAuthenticated)   {    var uid = httpContext.User.Claims.FirstOrDefault(s => s.Type == "uid")?.Value;    if (uid.IsNullOrWhiteSpace())    {     context.Fail();     return;    }    //判断是否有权限    var questUrl = httpContext.Request.Path.Value.ToLower();    if (!await _permissionWatchDog.PassApiPermAsync(uid, questUrl))    {     context.Fail();     return;    }    context.Succeed(requirement);   }   else   {    httpContext.Response.ContentType = "application/json; charset=UTF-8";    await httpContext.Response.WriteAsync(JsonConvert.SerializeObject(new { a="123",b="435"}));    await httpContext.Response.Body.FlushAsync();    //context.Fail();   }  } }

  有不对或者更好的方法希望园友提供指出谢谢


No comments:

Post a Comment