-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthentication.cs
More file actions
71 lines (53 loc) · 2.66 KB
/
Authentication.cs
File metadata and controls
71 lines (53 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
namespace HttpsRichardy.Federation.WebApi.Constants;
public static class Authentication
{
private static readonly JsonSerializerOptions _serializer = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
public static readonly JwtBearerEvents Events = new()
{
OnAuthenticationFailed = context =>
{
context.NoResult();
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
context.Response.ContentType = MediaTypeNames.Application.Json;
if (context.Exception is SecurityTokenExpiredException expiredException)
return context.Response.WriteAsync(JsonSerializer.Serialize(AuthenticationErrors.TokenExpired, _serializer));
if (context.Exception is SecurityTokenInvalidSignatureException)
return context.Response.WriteAsync(JsonSerializer.Serialize(AuthenticationErrors.InvalidSignature, _serializer));
return context.Response.WriteAsync(JsonSerializer.Serialize(AuthenticationErrors.InvalidTokenFormat, _serializer));
},
OnTokenValidated = context =>
{
var request = context.HttpContext.Request;
if (context.SecurityToken is not Microsoft.IdentityModel.JsonWebTokens.JsonWebToken token)
{
context.HttpContext.Items["authentication.error"] = AuthenticationErrors.InvalidTokenFormat;
context.Fail("The token format is invalid or the token is malformed.");
return Task.CompletedTask;
}
var expectedIssuer = $"{request.Scheme}://{request.Host}".TrimEnd('/');
var actualIssuer = token.Issuer?.TrimEnd('/');
if (!string.Equals(actualIssuer, expectedIssuer, StringComparison.OrdinalIgnoreCase))
{
context.HttpContext.Items["authentication.error"] = AuthenticationErrors.InvalidIssuer;
context.Fail("The token issuer is invalid.");
return Task.CompletedTask;
}
return Task.CompletedTask;
},
OnChallenge = context =>
{
context.HandleResponse();
if (context.Response.HasStarted)
return Task.CompletedTask;
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
context.Response.ContentType = MediaTypeNames.Application.Json;
var error = context.HttpContext.Items["authentication.error"] as Error
?? AuthenticationErrors.Unauthenticated;
return context.Response.WriteAsync(JsonSerializer.Serialize(error, _serializer));
}
};
}