将授权服务器与资源服务器分开非常简单:如果您使用 IIS 并且在两个应用程序/服务器上配置了相同的机器密钥,它甚至可以在没有任何额外代码的情况下工作。
如果您需要选择访问令牌可以访问哪些端点,则使用 OWIN OAuth2 服务器实现支持多个资源服务器会有点困难。如果您不关心这一点,只需使用相同的机器密钥配置所有资源服务器,您就可以使用相同的令牌访问所有 API。
要更好地控制可与访问令牌一起使用的端点,您应该查看AspNet.Security.OpenIdConnect.Server - OWIN/Katana 附带的 OAuth2 服务器的一个分支 - 它本机支持这种情况:@987654321 @。
设置起来相对容易:
在您的授权服务器应用程序中添加一个新的中间件颁发令牌(在Startup.cs 中):
app.UseOpenIdConnectServer(new OpenIdConnectServerOptions
{
Provider = new AuthorizationProvider()
});
在不同的 API 服务器(Startup.cs)中添加新的中间件验证访问令牌:
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
// AllowedAudiences MUST contain the absolute URL of your API.
AllowedAudiences = new[] { "http://localhost:11111/" },
// X509CertificateSecurityTokenProvider MUST be initialized with an issuer corresponding to the absolute URL of the authorization server.
IssuerSecurityTokenProviders = new[] { new X509CertificateSecurityTokenProvider("http://localhost:50000/", certificate) }
});
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
// AllowedAudiences MUST contain the absolute URL of your API.
AllowedAudiences = new[] { "http://localhost:22222/" },
// X509CertificateSecurityTokenProvider MUST be initialized with an issuer corresponding to the absolute URL of the authorization server.
IssuerSecurityTokenProviders = new[] { new X509CertificateSecurityTokenProvider("http://localhost:50000/", certificate) }
});
最后,在您的客户端应用中添加一个新的 OpenID Connect 客户端中间件(Startup.cs):
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
// Some essential parameters have been omitted for brevity.
// See https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/blob/dev/samples/Mvc/Mvc.Client/Startup.cs for more information
// Authority MUST correspond to the absolute URL of the authorization server.
Authority = "http://localhost:50000/",
// Resource represents the different endpoints the
// access token should be issued for (values must be space-delimited).
// In this case, the access token will be requested for both APIs.
Resource = "http://localhost:11111/ http://localhost:22222/",
});
您可以查看此示例以获取更多信息:https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/blob/dev/samples/Mvc/
它不使用多个资源服务器,但使用我提到的不同步骤来调整它应该不难。如果您需要帮助,请随时联系我。