using Microsoft.AspNetCore.Authorization.Policy; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Volo.Abp.DependencyInjection; using Microsoft.Extensions.DependencyInjection; namespace Syc.Authorize.JwtBearer { /// /// 用于针对授权结果,进行不同的响应处理 /// public class AppAuthorizationMiddlewareResultHandler : IAuthorizationMiddlewareResultHandler,ITransientDependency { public async Task HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult) { JwtBearerErrorMsgResponse response = null; if (authorizeResult.Challenged) { await context.Response.UnauthorizedAsync(); return; } if (authorizeResult.Forbidden || authorizeResult.AuthorizationFailure is not null) { IEnumerable reasons = null; if (authorizeResult.AuthorizationFailure is not null) { var message = authorizeResult.AuthorizationFailure.FailureReasons.Select(x => x.Message).ToList(); if (message.Any(x => !string.IsNullOrWhiteSpace(x))) reasons = message; } response = new JwtBearerErrorMsgResponse() { Code = 403, Message = "Forbidden", Data = reasons }; } //token 已过期 if (context.Request.Headers.ContainsKey("Token-Expired")) { response = new JwtBearerErrorMsgResponse() { Code = 401, Message = "Token has expired" }; } if (response is not null) { await context.Response.WriteAsJsonAsync(response); } else await next(context); } } }