66 lines
2.2 KiB
C#
66 lines
2.2 KiB
C#
using LMS.service.Service.PermissionService;
|
|
using Microsoft.AspNetCore.Routing;
|
|
using System.Security.Claims;
|
|
|
|
namespace LMS.service.Extensions.Middleware
|
|
{
|
|
public class DynamicPermissionMiddleware
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
|
|
public DynamicPermissionMiddleware(RequestDelegate next)
|
|
{
|
|
_next = next;
|
|
}
|
|
|
|
public async Task InvokeAsync(HttpContext context, PremissionValidationService _premissionValidationServices)
|
|
{
|
|
var endpoint = context.GetEndpoint();
|
|
var userId = GetUserIdFromContext(context); // 从JWT token或session中获取用户ID
|
|
if (userId == -1) // 判断用户ID是否有效
|
|
{
|
|
context.Response.StatusCode = StatusCodes.Status400BadRequest;
|
|
await context.Response.WriteAsync("用户参数校验错误");
|
|
return;
|
|
}
|
|
|
|
if (endpoint != null)
|
|
{
|
|
var httpMethod = context.Request.Method;
|
|
var path = (endpoint as RouteEndpoint)?.RoutePattern.RawText;
|
|
|
|
if (await _premissionValidationServices.HasPermissionForEndpoint(userId, httpMethod, path))
|
|
{
|
|
await _next(context);
|
|
}
|
|
else
|
|
{
|
|
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
|
await context.Response.WriteAsync("Access denied");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
await _next(context);
|
|
}
|
|
}
|
|
|
|
private long GetUserIdFromContext(HttpContext context)
|
|
{
|
|
var userIdClaim = context.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
|
|
var userId = userIdClaim?.Value;
|
|
if (!string.IsNullOrWhiteSpace(userId))
|
|
{
|
|
// 判断userId是否为数字
|
|
if (!long.TryParse(userId, out var result))
|
|
{
|
|
return -1;
|
|
}
|
|
context.Items["UserId"] = userId;
|
|
return Convert.ToInt64(userIdClaim?.Value);
|
|
}
|
|
return 0;
|
|
}
|
|
}
|
|
}
|