'How to use custom filter in Minimal Api .net 6.0?
After decoding the token generated in another application, I need to check for an expire. I used OnActionExecuting in web app but not working this method in minimal api.
Now I'm catching it by checking the response, but I need a better solution than this.
program.cs
builder.Services.AddSingleton(autoMapper);
builder.Services.AddAuthorization();
builder.Services.AddAuthentication("BearerAuthentication").AddScheme<Microsoft.AspNetCore.Authentication.AuthenticationSchemeOptions, BearerAuthendicationHandler>("BearerAuthentication", null);
var app = builder.Build();
app.UseAuthorization();
app.UseAuthentication();
app.MapGet("/countries", async (HttpContext http, CountryService service) =>
{
if (http.Response.StatusCode == 401) return Results.Unauthorized();
var result = service.GetAll(http.Request.Headers["lang"]);
return Results.Ok(result);
});
BearerAuthendicationHandler.cs
public class BearerAuthendicationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
public BearerAuthendicationHandler(
Microsoft.Extensions.Options.IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
System.Text.Encodings.Web.UrlEncoder encoder,
ISystemClock clock
) : base(options, logger, encoder, clock)
{
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var authHeader = Request.Headers["Authorization"].ToString();
try
{
if (authHeader != null && authHeader.StartsWith("bearer", StringComparison.OrdinalIgnoreCase))
{
var token = authHeader.Substring("Bearer ".Length).Trim();
string secret = "secret_key";
var key = Encoding.ASCII.GetBytes(secret);
var handler = new JwtSecurityTokenHandler();
var validations = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
var claims = handler.ValidateToken(token, validations, out var tokenSecure);
var exp = claims.Claims.FirstOrDefault(s => s.Type == "exp").Value;
var timeStamp = long.Parse(exp);
var timeStampNow = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
if (timeStamp < timeStampNow)
{
Response.StatusCode = 401;
return Task.FromResult(AuthenticateResult.Fail("Invalid Authorization Header"));
}
Response.StatusCode = 200;
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(), null, "")));
}
else
{
Response.StatusCode = 401;
return Task.FromResult(AuthenticateResult.Fail("Invalid Authorization Header"));
}
}
catch (Exception ex)
{
Response.StatusCode = 401;
return Task.FromResult(AuthenticateResult.Fail("Invalid Authorization Header"));
}
}
}
Thanks for your help.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|