64 lines
1.7 KiB
C#
64 lines
1.7 KiB
C#
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>();
|
|
}
|
|
}
|