1
This commit is contained in:
44
Gatedge.ScanCode/Middleware/AuthorizationMiddleware.cs
Normal file
44
Gatedge.ScanCode/Middleware/AuthorizationMiddleware.cs
Normal file
@@ -0,0 +1,44 @@
|
||||
using Gatedge.ScanCode.Common;
|
||||
using Gatedge.ScanCode.Extension;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Authorization.Policy;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace Gatedge.ScanCode.Middleware;
|
||||
|
||||
/// <summary>
|
||||
/// JWT鉴权中间件
|
||||
/// </summary>
|
||||
public class AuthorizationMiddleware : IAuthorizationMiddlewareResultHandler
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="next"></param>
|
||||
/// <param name="context"></param>
|
||||
/// <param name="policy"></param>
|
||||
/// <param name="authorizeResult"></param>
|
||||
/// <returns></returns>
|
||||
public async Task HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
|
||||
{
|
||||
//因为管道还没有走到Action 所以没有ActionResult使用 我们必须自己定义Response中的内容
|
||||
//这里授权是否成功
|
||||
if (!authorizeResult.Succeeded)
|
||||
{
|
||||
//将状态码定义为200
|
||||
context.Response.StatusCode = 200;
|
||||
//使用 WriteAsJsonAsync 写入一个自定义的返回对象 自动完成Json的序列化操作
|
||||
//我这里用匿名类演示 实际项目中请替换成对应的返回对象 自定义状态码和提示信息
|
||||
//身份验证是否通过
|
||||
if (context?.User?.Identity?.IsAuthenticated == false)
|
||||
await context.Response.WriteAsJsonAsync(AjaxResult.Error(401, "找不到会话信息,请先登录."));
|
||||
else
|
||||
await context.Response.WriteAsJsonAsync(AjaxResult.Error(403, "改用户没有权限"));
|
||||
//注意一定要return 在这里短路管道 不要走到next 否则线程会进入后续管道 到达action中
|
||||
return;
|
||||
}
|
||||
//如果授权成功 继续执行后续的中间件 记住一定记得next 否则会管道会短路
|
||||
await next(context);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user