-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathConfigureJwtBearerOptions.cs
More file actions
85 lines (75 loc) · 2.91 KB
/
ConfigureJwtBearerOptions.cs
File metadata and controls
85 lines (75 loc) · 2.91 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using FSH.Framework.Core.Exceptions;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
using System.Text;
namespace FSH.Modules.Identity.Authorization.Jwt;
public class ConfigureJwtBearerOptions : IConfigureNamedOptions<JwtBearerOptions>
{
private readonly JwtOptions _options;
public ConfigureJwtBearerOptions(IOptions<JwtOptions> options, IConfiguration configuration)
{
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(configuration);
_options = options.Value;
}
public void Configure(JwtBearerOptions options)
{
ArgumentNullException.ThrowIfNull(options);
Configure(string.Empty, options);
}
public void Configure(string? name, JwtBearerOptions options)
{
ArgumentNullException.ThrowIfNull(options);
if (name != JwtBearerDefaults.AuthenticationScheme)
{
return;
}
byte[] key = Encoding.ASCII.GetBytes(_options.SigningKey);
options.RequireHttpsMetadata = true;
options.SaveToken = false;
options.MapInboundClaims = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidIssuer = _options.Issuer,
ValidateIssuer = true,
ValidateLifetime = true,
ValidAudience = _options.Audience,
ValidateAudience = true,
RoleClaimType = ClaimTypes.Role,
ClockSkew = TimeSpan.FromMinutes(2)
};
options.Events = new JwtBearerEvents
{
OnChallenge = context =>
{
context.HandleResponse();
if (!context.Response.HasStarted)
{
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
var result = System.Text.Json.JsonSerializer.Serialize(new { error = "Unauthorized" });
return context.Response.WriteAsync(result);
}
return Task.CompletedTask;
},
OnForbidden = _ => throw new ForbiddenException(),
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
if (!string.IsNullOrEmpty(accessToken) &&
context.HttpContext.Request.Path.StartsWithSegments("/notifications", StringComparison.OrdinalIgnoreCase))
{
// Read the token out of the query string
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
}
}