身份验证
This commit is contained in:
63
Hotfix/Api/Middlewares/ApiJwtGuardMiddleware.cs
Normal file
63
Hotfix/Api/Middlewares/ApiJwtGuardMiddleware.cs
Normal 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>();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user