-
Notifications
You must be signed in to change notification settings - Fork 0
/
JwtBearerExtensions.cs
52 lines (45 loc) · 1.98 KB
/
JwtBearerExtensions.cs
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
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
namespace AWSAugment.Cognito.JwtBearer
{
public static class JwtBearerExtensions
{
public static AuthenticationBuilder AddCognitoJwtBearer
(
this AuthenticationBuilder builder,
Action<CognitoJwtBearerOptions> configureCognitoOptions
)
{
Action<JwtBearerOptions> action = options =>
{
var cognitoJwtBearerOptions = new CognitoJwtBearerOptions(options);
configureCognitoOptions(cognitoJwtBearerOptions);
// AWS cognito jwt token does not have aud included so that we cannot validate audience.
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false
};
var existingJwtSecurityTokenHandler = options.SecurityTokenValidators
.FirstOrDefault(_ => _.GetType() == typeof(JwtSecurityTokenHandler));
if (existingJwtSecurityTokenHandler != null)
{
options.SecurityTokenValidators.Remove(existingJwtSecurityTokenHandler);
}
var awsTokenValidator = new AwsCognitoTokenValidator
{
RequiredClientId = cognitoJwtBearerOptions.ClientId,
Authority = cognitoJwtBearerOptions.IdpUrl
};
options.SecurityTokenValidators.Add(awsTokenValidator);
options.Authority = cognitoJwtBearerOptions.IdpUrl;
};
builder.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, action);
return builder;
}
}
}