我一直在关注本文中的步骤,但我的IdentityServer是使用IdentityServer4构建的 . https://identityserver.github.io/Documentation/docsv2/overview/simplestOAuth.html
在IdentityServer上,我创建了2个ApiResource,1个用于CoreWebApi,1个用于Framework 4.6.2 WebApi .
new ApiResource {
Name = "WebApi",
DisplayName = "WebApi Api",
Description = "WebApi API Access",
UserClaims = new List<string> {"role"},
ApiSecrets = new List<Secret> {new Secret("scopeSecret".Sha256())},
Scopes = new List<Scope> {
new Scope("WebApi.read"),
new Scope("WebApi.write")
}
},
new ApiResource {
Name = "CoreApi",
DisplayName = "CoreApi API",
Description = "CoreApi API Access",
UserClaims = new List<string> {"role"},
ApiSecrets = new List<Secret> {new Secret("scopeSecret".Sha256())},
Scopes = new List<Scope> {
new Scope("CoreApi.read"),
new Scope("CoreApi.write")
}
}
并且我的测试控制台的客户端生成访问令牌 .
new Client()
{
ClientId = "consoleApp",
ClientName = "Example Client Credentials Client Application",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets = new List<Secret>()
{
new Secret("superSecretPassword".Sha256())
},
AllowedScopes = new List<string>(){ "CoreApi.read", "WebApi.read" }
}
我可以为CoreApi请求令牌
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("CoreApi.read");
然后调用我的CoreApi没有问题 .
我也可以获得WebApi的令牌
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("WebApi.read");
但是使用令牌调用WebApi会返回“Unauthorized”?
CoreWebApi配置如下:
services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters();
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ApiName = "CoreApi";
});
WebApi配置是:
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "http://localhost:5000",
ValidationMode = ValidationMode.ValidationEndpoint,
RequiredScopes = new[] { "WebApi.read" }
});
// configure web api
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
// require authentication for all controllers
config.Filters.Add(new AuthorizeAttribute());
app.UseWebApi(config);
我有什么明显的遗失吗?是否可以在IdentityServer4中生成访问令牌并使用IdentityServer3.AccessTokenValidation进行验证?任何帮助赞赏 .
1 回答
仅供参考,我设法通过将配置更新为以下内容来使ValidationEndpoint正常工作:
在查看Git上的一些代码之后,我发现如果指定了ClientId,它将使用 Introspection (/ connect / introspect) endpoints 而不是不存在的验证 endpoints (connect / accesstokenvalidation) .
****注意使用的 ClientId 和 ClientSecret 实际上是 API resource Name 和 ApiSecrets 令人困惑!