身份验证

This commit is contained in:
Bob.Song
2026-04-01 16:40:34 +08:00
parent d5dafd2bcf
commit b628f0d04a
17 changed files with 590 additions and 101 deletions

View File

@@ -0,0 +1,63 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
namespace NBF;
public sealed class ApiJwtGuardMiddleware
{
private readonly RequestDelegate _next;
public ApiJwtGuardMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (HttpMethods.IsOptions(context.Request.Method))
{
await _next(context);
return;
}
var path = context.Request.Path.Value ?? string.Empty;
var normalizedPath = path.Length > 1 ? path.TrimEnd('/') : path;
if (!normalizedPath.StartsWith("/api/", StringComparison.OrdinalIgnoreCase))
{
await _next(context);
return;
}
// Endpoint carries AllowAnonymous metadata when action/controller has [AllowAnonymous].
var endpoint = context.GetEndpoint();
if (endpoint?.Metadata.GetMetadata<IAllowAnonymous>() != null)
{
await _next(context);
return;
}
if (context.User?.Identity?.IsAuthenticated != true)
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
await context.Response.WriteAsJsonAsync(new ResponseData<string>
{
Code = StatusCodes.Status401Unauthorized,
Data = "unauthorized"
});
return;
}
await _next(context);
}
}
public static class ApiJwtGuardMiddlewareExtensions
{
public static IApplicationBuilder UseApiJwtGuard(this IApplicationBuilder app)
{
return app.UseMiddleware<ApiJwtGuardMiddleware>();
}
}