ASP.NET Core 2 supports handling multiple JWT token providers. This functionality is critical when your API needs to integrate with external services that use different JWT token issuance mechanisms.
To achieve this function, please use the following code:
<code class="language-csharp">services .AddAuthentication() .AddJwtBearer("Firebase", options => { options.Authority = "https://securetoken.google.com/my-firebase-project"; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = "my-firebase-project", ValidateAudience = true, ValidAudience = "my-firebase-project", ValidateLifetime = true }; }) .AddJwtBearer("Custom", options => { // 在此处配置自定义 JWT 令牌选项 }); services .AddAuthorization(options => { options.DefaultPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .AddAuthenticationSchemes("Firebase", "Custom") .Build(); });</code>
This code differs from the original code snippet in several key ways:
AddJwtBearer
method has multiple overloads, one of which allows specifying the authentication scheme name. Since we have multiple scenarios, this overload must be used. AddAuthentication
method is used without parameters to avoid setting a default authentication scheme. This is because handling multiple authentication schemes requires each request to go through all schemes. DefaultPolicy
has been modified to allow "Firebase" and "Custom" authentication schemes. This ensures that the authorization system attempts to authenticate the request using both schemes. AuthenticationFailed
event, please note that for non-first AddJwtBearer
policies, the error "IDX10501: Signature validation failed" may occur. This is because the system attempts to match the signature of each policy in turn. Additional Notes for .NET Core 6 and above
In .NET Core 6 and above, a default authorization scheme must be specified. So use the following code instead:
<code class="language-csharp">builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { // Firebase 配置 }) .AddJwtBearer("AzureAD", options => { // Azure AD 配置 }); builder.Services.AddAuthorization(options => { var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder( JwtBearerDefaults.AuthenticationScheme, "AzureAD"); defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser(); options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); });</code>
By implementing the provided solution, you can seamlessly manage multiple JWT token issuers in your ASP.NET Core 2 application.
The above is the detailed content of How to Handle Multiple JWT Issuers in ASP.NET Core?. For more information, please follow other related articles on the PHP Chinese website!