多个JWT令牌和多个身份验证处理程序



我目前已经为我的API应用程序设置了Auth,使用带有Identity User的JWT令牌,这很好,我现在正试图在另一个JWT令牌上链上,该令牌是用户密钥斗篷,我想为该令牌类型设置一个自定义的Auth处理程序,这可能吗?我的代码如下:

services.AddAuthentication()
.AddJwtBearer("KeyCloak", opt =>
{
opt.Authority = "site.co.za/auth/realms/Development";
opt.Audience = "dev";
opt.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidAudiences = new string[] { "dev" },
NameClaimType = "preferred_username",
RoleClaimType = "role"
};
opt.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{
c.NoResult();
c.Response.StatusCode = 500;
c.Response.ContentType = "text/plain";
return c.Response.WriteAsync(c.Exception.ToString());
}
};
opt.RequireHttpsMetadata = false;
opt.SaveToken = true;
opt.Validate();

})
.AddJwtBearer("Internal", opt =>
{
opt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Constants.AuthTokenKey))
};
});
services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddAuthenticationSchemes("KeyCloak", "Internal").Build();
});

我需要添加一个仅用于密钥斗篷的自定义Auth HandleAuthenticateAsync,并使用普通的开箱即用的HandleAuthenticateAync进行内部验证。这样做可能吗?

您可以这样做:

这将选择基于API路径的jwt令牌验证。

builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = "Custom";
})
.AddPolicyScheme("Custom", "Custom", options =>
{
options.ForwardDefaultSelector = context =>
{
bool isKeyCloakAuthRequired = context.Request.Path.StartsWithSegments("/apithatneedskeycloakauth");
if (isKeyCloakAuthRequired)
{
return "Keycloak";
}
else
{
return "Internal";
}
};
})
.AddJwtBearer("Keycloak", options =>
{
// your code for keycloak validation parameters.
})
.AddJwtBearer("Internal", options =>
{
// your code for token validation parameters.
})

希望能有所帮助。

最新更新