不必在每个微服务中对外部请求进行身份验证(您可能希望对内部微服务通信进行身份验证),而应安装一个网关(例如Ocelot),使用您正在使用的任何系统,例如Jwt bearer,可以为您处理外部“上游”身份验证:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication()
.AddJwtBearer("TestScheme", x => ...
}
然后在Ocelot中,您可以按以下方式决定哪些路由需要此方案
"Routes": [{
"DownstreamHostAndPorts": [...],
"DownstreamPathTemplate": "/",
"UpstreamPathTemplate": "/",
"AuthenticationOptions": {
"AuthenticationProviderKey": "TestScheme",
"AllowedScopes": []
}
}]
如果身份验证成功,您可以使用Ocelot的"声明到声明转换"方法,从上游到下游此方法 - 我个人想要自定义这个方法,并构建一个新的Jwt令牌用于内部身份验证,所以我使用了自己的下游处理程序,像这样:
services
.AddHttpClient<IMyService, MyService>(client => ...)
.AddHttpMessageHandler<MyJwtDownstreamHandler>();
request.Headers.Authorization = new AuthenticationHeaderValue(
"bearer",
TokenGenerator.Generate(
identity: myIdentity,
)
);