netcore 下的policy授权自定义返回结果
程序员文章站
2022-05-18 18:33:58
目前一直在用policy做权限校验,但是好像组里需要将返回结果统一,之前用的都是直接继承AuthorizationHandler然后调用context.Fail(),但是这样会导致没办法自定义返回结果比如{code:403,msg:'未授权',data:null}, 也百度了下https://q.c ......
目前一直在用policy做权限校验,但是好像组里需要将返回结果统一,之前用的都是直接继承authorizationhandler然后调用context.fail(),但是这样会导致没办法自定义返回结果比如{code:403,msg:'未授权',data:null},
也百度了下 这里也说了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();
}
}
}
有不对或者更好的方法希望园友提供指出谢谢