Last active
February 9, 2020 05:51
-
-
Save PatrickDinh/ee60add219cab45c4b74086fec9a7930 to your computer and use it in GitHub Desktop.
Configure JWT auth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class AuthenticationBuilderExtensions | |
{ | |
public static AuthenticationBuilder ConfigureAuth(this AuthenticationBuilder builder, Action<AuthOptions> authOptions) | |
{ | |
builder.Services.Configure(authOptions); | |
builder.Services.AddSingleton<IConfigureOptions<JwtBearerOptions>, ConfigureJwtBearerOptions>(); | |
builder.AddJwtBearer(); | |
return builder; | |
} | |
private class ConfigureJwtBearerOptions : IConfigureNamedOptions<JwtBearerOptions> | |
{ | |
private readonly AuthOptions _azureOptions; | |
public ConfigureJwtBearerOptions(IOptions<AuthOptions> azureOptions) | |
{ | |
_azureOptions = azureOptions.Value; | |
} | |
public void Configure(string name, JwtBearerOptions options) | |
{ | |
var azureAdRootUrl = "https://login.microsoftonline.com/"; | |
options.Authority = $"{azureAdRootUrl}{_azureOptions.TenantId}"; | |
options.TokenValidationParameters = new TokenValidationParameters | |
{ | |
ValidAudiences = new[] | |
{ | |
_azureOptions.ClientId | |
}, | |
ValidIssuers = new[] | |
{ | |
$"{azureAdRootUrl}{_azureOptions.TenantId}/v2.0" | |
} | |
}; | |
} | |
public void Configure(JwtBearerOptions options) | |
{ | |
Configure(Options.DefaultName, options); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment