authentication - 验证由 .net 核心微服务创建的 JWT
问题描述
我有一些在 docker 中运行的 .net 核心 Web API 微服务。
例如:目录 API、邮政编码 API、结帐 API。
我创建了另一个验证电子邮件和密码以生成 JWT 令牌的微服务。
有没有办法在其他服务中检查此令牌的凭据,例如在目录 API 中?
解决方案
为了实现这一点,我做了两件事。首先,在 Startup.cs 我添加了这段代码:
public static IServiceCollection AddCustomAuthentication(this IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.TokenValidationParameters = new TokenValidationParameters
{
// -> next three lines: avoid to check de signature key (just the auth app, the issuer, has the key)
ValidateIssuerSigningKey = false,
RequireSignedTokens = false,
SignatureValidator = (string token, TokenValidationParameters parameters) => new JwtSecurityToken(token),
ValidateIssuer = false,
ValidateAudience = false,
ValidateActor = false,
ValidateLifetime = true // -> even avoiding the signature check, the token expiration has to be checked
};
});
return services;
}
使用此代码,在控制器中,我可以在没有签名检查的情况下验证令牌,只需使用 [Authorize]
第二步是,当我需要检查签名时,我创建了 [AuthorizeOnJwtSource] 属性:
public class AuthorizeOnJwtSourceAttribute : AuthorizeAttribute, IAsyncAuthorizationFilter
{
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
if (context.HttpContext.User.Identity.IsAuthenticated) // -> first, we need to check if we have some toeken
{
var authorizationService = context.HttpContext.RequestServices.GetRequiredService<AuthorizationService>();
string token = context.HttpContext.Request.Headers["Authorization"];
bool isTokenValid = await authorizationService.IsTokenValid(token);
if(!isTokenValid)
context.Result = new UnauthorizedResult();
}
}
}
AuthorizationService 使用 HttpClient 来验证 isser Web 应用程序中的令牌。
推荐阅读
- python - 如何从上到下访问给定矩阵中的元素
- bash - 导出的函数不扩展 awk 变量
- java - 是否有一个等效的 doCallRealMethod 用于间谍(又名 doCallMockMethod)?
- snakemake - 没有明显原因的 Snakemake 中的通配符语法错误
- angular - 向下钻取图表动态功能
- android-studio-3.4 - 如何修复“找不到 com.android.tools.build:aapt2:3.4.0-5326820。” android studio 3.4 中的错误
- sql - 在Oracle数据库上选择大数时如何摆脱科学计数法?
- c# - 为什么我的 MenuFlyoutItem 文本绑定不起作用?
- python - 如何为 Ansible 模块打包共享代码
- python - 我怎样才能使它不那么可怕?Python