Files
NTBug/backend/src/Helpdesk.Api/Infrastructure/AuthenticationSetup.cs
T

47 lines
1.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Helpdesk.Application.Abstractions;
using Helpdesk.Domain.Auth;
using Helpdesk.Infrastructure.Security;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.JsonWebTokens;
namespace Helpdesk.Api.Infrastructure;
public static class AuthenticationSetup
{
/// <summary>
/// Ověření access tokenu podle RFC 7519, kap. 7.2 (kap. 10.1 návrhu):
/// body 1–4 (podpis HS256, <c>typ</c> = <c>at+jwt</c>, <c>iss</c>/<c>aud</c>, <c>exp</c>) zajistí JwtBearer,
/// bod 5 (zneplatněné <c>jti</c>) kontroluje <see cref="JwtBearerEvents.OnTokenValidated"/>.
/// </summary>
public static IServiceCollection AddHelpdeskAuthentication(this IServiceCollection services, IConfiguration configuration)
{
var jwt = configuration.GetSection(JwtOptions.Section).Get<JwtOptions>() ?? new JwtOptions();
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.MapInboundClaims = false; // claimy zůstanou jako "sub", "role", "jti"
options.TokenValidationParameters = JwtTokenService.CreateValidationParameters(jwt, TokenType.Access);
options.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
var store = context.HttpContext.RequestServices.GetRequiredService<IRevokedTokenStore>();
if (context.SecurityToken is not JsonWebToken token || string.IsNullOrEmpty(token.Id) || store.IsRevoked(token.Id))
context.Fail("Token byl zneplatněn.");
return Task.CompletedTask;
},
};
});
return services;
}
}
public static class RateLimitPolicies
{
public const string Auth = "auth";
public const string IssueWrites = "issue-writes";
}