Skip to content

Commit 3f51888

Browse files
feat: implement authentication event handling for JWT bearer tokens
1 parent 1fbfecb commit 3f51888

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

  • Applications/Backend/Source/HttpsRichardy.Federation.WebApi/Constants
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
namespace HttpsRichardy.Federation.WebApi.Constants;
2+
3+
public static class Authentication
4+
{
5+
private static readonly JsonSerializerOptions _serializer = new()
6+
{
7+
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
8+
WriteIndented = true
9+
};
10+
11+
public static readonly JwtBearerEvents Events = new()
12+
{
13+
OnAuthenticationFailed = context =>
14+
{
15+
context.NoResult();
16+
17+
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
18+
context.Response.ContentType = MediaTypeNames.Application.Json;
19+
20+
if (context.Exception is SecurityTokenExpiredException expiredException)
21+
return context.Response.WriteAsync(JsonSerializer.Serialize(AuthenticationErrors.TokenExpired, _serializer));
22+
23+
if (context.Exception is SecurityTokenInvalidSignatureException)
24+
return context.Response.WriteAsync(JsonSerializer.Serialize(AuthenticationErrors.InvalidSignature, _serializer));
25+
26+
return context.Response.WriteAsync(JsonSerializer.Serialize(AuthenticationErrors.InvalidTokenFormat, _serializer));
27+
},
28+
29+
OnChallenge = context =>
30+
{
31+
context.HandleResponse();
32+
33+
if (context.Response.HasStarted)
34+
return Task.CompletedTask;
35+
36+
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
37+
context.Response.ContentType = MediaTypeNames.Application.Json;
38+
39+
return context.Response.WriteAsync(JsonSerializer.Serialize(AuthenticationErrors.Unauthenticated, _serializer));
40+
}
41+
};
42+
}

0 commit comments

Comments
 (0)