使用 ASOS 绝对可以将资源服务器角色(即 API)与授权服务器角色分开。
When opting for JWT tokens (instead of the default encrypted tokens), you need to ensure the audience is correctly added to the authentication ticket by calling ticket.SetResources
, so the JWT access token gets the appropriate aud
claim, containing the identifier associated with your resource server (ie API):
public override Task GrantResourceOwnerCredentials(GrantResourceOwnerCredentialsContext context) {
var identity = new ClaimsIdentity(context.Options.AuthenticationScheme);
identity.AddClaim(ClaimTypes.NameIdentifier, "[unique identifier]");
var ticket = new AuthenticationTicket(
new ClaimsPrincipal(identity),
new AuthenticationProperties(),
context.Options.AuthenticationScheme);
// Call SetResources with the list of resource servers
// the access token should be issued for.
ticket.SetResources("resource_server_1");
// Call SetScopes with the list of scopes you want to grant.
ticket.SetScopes("profile", "offline_access");
context.Validate(ticket);
return Task.FromResult(0);
}
在您的 API 应用程序中,您只需options.Audience
使用授权服务器中使用的标识符设置属性,它应该可以工作:
app.UseJwtBearerAuthentication(new JwtBearerOptions {
AutomaticAuthenticate = true,
AutomaticChallenge = true,
Audience = "resource_server_1",
Authority = "http://localhost:61854"
});
我会在调用 app.UseJwtBearerAuthentication 时使用一小段代码,只是将 JWT 中间件指向 OIDC 端点?如果是这种情况,app.UseJwtBearerAuthentication 使用 OIDC 来允许 IdentityModel 使用 HTTP 仍然会发生一些神奇的事情,所以我不清楚在从属服务器上是否也需要这个。
JWT 不记名中间件通过对配置元数据端点进行 HTTP 调用,options.Authority
自动从属性中提到的授权服务器检索用于签署访问令牌的加密密钥:您无需配置任何内容,即使 API 项目是与授权服务器应用程序分开。