目前一直在用policy做許可權校驗,但是好像組裡需要將返回結果統一,之前用的都是直接繼承AuthorizationHandler然後調用context.Fail(),但是這樣會導致沒辦法自定義返回結果比如{code:403,msg:'未授權',data:null}, 也百度了下https://q.c ...
目前一直在用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(); } } }
有不對或者更好的方法希望園友提供指出謝謝