[英]IdentityServer4 Introspection Endpoint API uses invalid hashing algorithm
尝试使用IdentityServer4上的Introspection Endpoint验证令牌。 我一直得到401:未经授权。 我的日志看起来像这样:
dbug: IdentityServer4.EntityFramework.Stores.ResourceStore[0]
Found MyAPI API resource in database
info: IdentityServer4.Validation.HashedSharedSecretValidator[0]
Secret: MyAPI API uses invalid hashing algorithm.
dbug: IdentityServer4.Validation.SecretValidator[0]
Secret validators could not validate secret
fail: IdentityServer4.Validation.ApiSecretValidator[0]
API validation failed.
fail: IdentityServer4.Endpoints.IntrospectionEndpoint[0]
API unauthorized to call introspection endpoint. aborting.
我的API配置如下:
new ApiResource
{
Name = "MyAPI",
DisplayName = "My API",
ApiSecrets =
{
new Secret("TopSecret".Sha256())
},
}
我将内容类型的标题传递为application / x-www-form-urlencoded,授权为Basic xxxxxxxxxxxxxxxxx,其中x是我的base64编码的auth字符串(myapi:TopSecret)。 我的令牌在帖子的正文中
我错过了什么? 为什么我得到“MyAPI API使用无效散列算法”? 如果它无效,什么是有效的哈希算法?
附加信息:我的资源包含在通过Entity Framework访问的SQL数据库中。 具体来说,设置与此处的快速入门文档中的设置相同。 为了达到我的目的,我必须手动将我的API添加到ApiSecrets表并给它一个Type(SharedSecret)和一个值,这是一个Sha256密码。
在Startup.cs中,我的COnfigureServices包括
services.AddIdentityServer()
.AddTemporarySigningCredential()
.AddInMemoryApiResources(Configurations.Scopes.GetApiResources())
.AddInMemoryClients(Configurations.Clients.GetClients())
.AddConfigurationStore(builder =>
builder.UseSqlServer(connectionString, options =>
options.MigrationsAssembly(migrationsAssembly)))
.AddOperationalStore(builder =>
builder.UseSqlServer(connectionString, options =>
options.MigrationsAssembly(migrationsAssembly)));
// include the password validation routine
services.AddTransient<IResourceOwnerPasswordValidator, Configurations.ResourceOwnerPasswordValidator>();
services.AddTransient<IProfileService, Configurations.ProfileService>();
services.AddMvc();
在配置下:
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = "http://localhost:5000",
RequireHttpsMetadata = false,
ApiSecret = "TopSecret",
AutomaticAuthenticate = true,
AutomaticChallenge = false,
ApiName = "MyAPI"
});
InitializeDatabase(app);
app.UseIdentityServer();
app.UseMvc();
请注意,只有在我开始解决问题以使其工作之后,我才将ApiSecret,AutomaticAuthenticate和AutomaticChallenge添加到此部分。
在我的Scopes.cs中,我概述了以下API:
public static IEnumerable<ApiResource> GetApiResources()
{
return new[]
{
new ApiResource
{
Name = "MyAPI",
DisplayName = "My API",
ApiSecrets =
{
new Secret("TopSecret".Sha256()),
},
}
};
}
对于Clients.cs:
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientName = "My Client",
AlwaysSendClientClaims=true,
ClientId = "MyClient",
ClientSecrets = { new Secret("TopSecret".Sha256()) },
RequireClientSecret=false,
AllowAccessTokensViaBrowser =true,
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
AllowedScopes = { "MyAPI" },
RequireConsent = false,
AllowOfflineAccess = true,
},
这或多或少都与代码部分有关。 容纳配置的数据库似乎覆盖了我所做的任何代码更改,所以我不确定这一切是多么有用。 在DB中,我在ApiSecrets表中创建了ApiResourceId为1的记录,添加了描述和到期日期,将Type设置为“SharedSecret”,并使用各种格式(包括纯文本,sha256和base64)添加了Secret。
这是通话期间的完整日志。 也许它会有所帮助。 我看到有一些关于Bearer没有被发现的东西或类似的东西,但我不确定为什么会这样,如果它影响程序的结果。
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 29.4277ms 401
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 POST http://localhost:5000/connect/introspect application/x-www-form-urlencoded 762
info: IdentityServer4.AccessTokenValidation.Infrastructure.NopAuthenticationMiddleware[7]
Bearer was not authenticated. Failure message: No token found.
dbug: IdentityServer4.CorsPolicyProvider[0]
CORS request made for path: /connect/introspect from origin: chrome-extension://aicmkgpgakddgnaphhhpliifpcfhicfo but rejected because invalid CORS path
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[7]
idsrv was not authenticated. Failure message: Unprotect ticket failed
dbug: IdentityServer4.Hosting.EndpointRouter[0]
Request path /connect/introspect matched to endpoint type Introspection
dbug: IdentityServer4.Hosting.EndpointRouter[0]
Mapping found for endpoint: Introspection, creating handler: IdentityServer4.Endpoints.IntrospectionEndpoint
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
Invoking IdentityServer endpoint: IdentityServer4.Endpoints.IntrospectionEndpoint for /connect/introspect
dbug: IdentityServer4.Endpoints.IntrospectionEndpoint[0]
Starting introspection request.
dbug: IdentityServer4.Validation.BasicAuthenticationSecretParser[0]
Start parsing Basic Authentication secret
dbug: IdentityServer4.Validation.SecretParser[0]
Parser found secret: BasicAuthenticationSecretParser
dbug: IdentityServer4.Validation.SecretParser[0]
Secret id found: MyAPI
info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1]
Executed DbCommand (0ms) [Parameters=[@__name_0='?' (Size = 200)], CommandType='Text', CommandTimeout='30']
SELECT TOP(1) [apiResource].[Id], [apiResource].[Description], [apiResource].[DisplayName], [apiResource].[Enabled], [apiResource].[Name]
FROM [ApiResources] AS [apiResource]
WHERE [apiResource].[Name] = @__name_0
ORDER BY [apiResource].[Id]
info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1]
Executed DbCommand (0ms) [Parameters=[@__name_0='?' (Size = 200)], CommandType='Text', CommandTimeout='30']
SELECT [a3].[Id], [a3].[ApiResourceId], [a3].[Type]
FROM [ApiClaims] AS [a3]
INNER JOIN (
SELECT DISTINCT TOP(1) [apiResource].[Id]
FROM [ApiResources] AS [apiResource]
WHERE [apiResource].[Name] = @__name_0
ORDER BY [apiResource].[Id]
) AS [apiResource2] ON [a3].[ApiResourceId] = [apiResource2].[Id]
ORDER BY [apiResource2].[Id]
info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1]
Executed DbCommand (0ms) [Parameters=[@__name_0='?' (Size = 200)], CommandType='Text', CommandTimeout='30']
SELECT [a2].[Id], [a2].[ApiResourceId], [a2].[Description], [a2].[Expiration], [a2].[Type], [a2].[Value]
FROM [ApiSecrets] AS [a2]
INNER JOIN (
SELECT DISTINCT TOP(1) [apiResource].[Id]
FROM [ApiResources] AS [apiResource]
WHERE [apiResource].[Name] = @__name_0
ORDER BY [apiResource].[Id]
) AS [apiResource1] ON [a2].[ApiResourceId] = [apiResource1].[Id]
ORDER BY [apiResource1].[Id]
info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1]
Executed DbCommand (0ms) [Parameters=[@__name_0='?' (Size = 200)], CommandType='Text', CommandTimeout='30']
SELECT [a].[Id], [a].[ApiResourceId], [a].[Description], [a].[DisplayName], [a].[Emphasize], [a].[Name], [a].[Required], [a].[ShowInDiscoveryDocument]
FROM [ApiScopes] AS [a]
INNER JOIN (
SELECT DISTINCT TOP(1) [apiResource].[Id]
FROM [ApiResources] AS [apiResource]
WHERE [apiResource].[Name] = @__name_0
ORDER BY [apiResource].[Id]
) AS [apiResource0] ON [a].[ApiResourceId] = [apiResource0].[Id]
ORDER BY [apiResource0].[Id], [a].[Id]
info: Microsoft.EntityFrameworkCore.Storage.IRelationalCommandBuilderFactory[1]
Executed DbCommand (0ms) [Parameters=[@__name_0='?' (Size = 200)], CommandType='Text', CommandTimeout='30']
SELECT [a0].[Id], [a0].[ApiScopeId], [a0].[Type]
FROM [ApiScopeClaims] AS [a0]
INNER JOIN (
SELECT DISTINCT [apiResource0].[Id], [a].[Id] AS [Id0]
FROM [ApiScopes] AS [a]
INNER JOIN (
SELECT DISTINCT TOP(1) [apiResource].[Id]
FROM [ApiResources] AS [apiResource]
WHERE [apiResource].[Name] = @__name_0
ORDER BY [apiResource].[Id]
) AS [apiResource0] ON [a].[ApiResourceId] = [apiResource0].[Id]
) AS [a1] ON [a0].[ApiScopeId] = [a1].[Id0]
ORDER BY [a1].[Id], [a1].[Id0]
dbug: IdentityServer4.EntityFramework.Stores.ResourceStore[0]
Found MyAPI API resource in database
info: IdentityServer4.Validation.HashedSharedSecretValidator[0]
Secret: MyAPI Secret uses invalid hashing algorithm.
info: IdentityServer4.Validation.HashedSharedSecretValidator[0]
Secret: MyAPI Secret uses invalid hashing algorithm.
dbug: IdentityServer4.Validation.SecretValidator[0]
Secret validators could not validate secret
fail: IdentityServer4.Validation.ApiSecretValidator[0]
API validation failed.
fail: IdentityServer4.Endpoints.IntrospectionEndpoint[0]
API unauthorized to call introspection endpoint. aborting.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 30.673ms 401
没有看到代码和数据库配置的每一个细节,都有点难。 另外,我没有看到实际调用Introspection端点的代码。 你是用C#或Javascript还是Postman做的?
无论如何,这是我的评论......
Startup.cs
ConfigureServices
方法看起来不错。 对于所述问题,不需要添加ResourceOwner密码验证器服务; 要访问Introspection端点,需要ApiSecret ,而不是ResourceOwner密码。 我假设你有一些不相干的原因,如果没有,那就把它拿出来。
在Configure方法下,您有app.UseIdentityServerAuthentication
,这意味着您使用Web应用程序不仅充当身份验证服务器(使用IdentityServer4),而且它也是您的Web Api应用程序,它回调到身份验证服务器(在这种情况下) )验证传入的令牌。
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = "https://localhost:44388",
RequireHttpsMetadata = false,
ApiName = "MyAPI"
//ApiSecret = "TopSecret" not necessary to know the api secret for normal validation
//AutomaticAuthenticate = true, not necessary
//AutomaticChallenge = false not necessary
});
您也可能想要app.UseMvcWithDefaultRoute()
。
Api InMemory配置
使用new ApiResource("name", "display")
构造函数将正确设置数据库; 但是如上所述使用对象初始化器语法则不会。 这是向GitHub报告的问题: https : //github.com/IdentityServer/IdentityServer4/issues/836
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
// this will incorrectly leave out the ApiScope record in the database, but will create the ApiResoure and ApiSecret records
new ApiResource
{
Name = "MyAPI",
DisplayName = "My API",
ApiSecrets =
{
new Secret("TopSecret".Sha256()),
}
},
// this will correctly create the ApiResource, ApiScope, and ApiSecret records in the database.
new ApiResource("MyAPI2", "My API2")
{
ApiSecrets =
{
new Secret("TopSecret2".Sha256())
}
}
};
}
Fyi,由于上面的new ApiResources
中没有指定new ApiResources
,IdentityServer工具将为每个ApiResource自动生成一个ApiScope。 在这种情况下,ApiScore与ApiResource的名称相同。 ApiResource必须至少有一个ApiScope; 但可能有很多。 然后是ApiScopes与ClientScopes表中的Client相关联。
客户端InMemory配置
看评论...
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientName = "My Client",
AlwaysSendClientClaims = true,
ClientId = "MyClient",
// changed the secret to make clear this is unrelated to the Api secret
ClientSecrets = { new Secret("TopSecretClientSecret".Sha256()) },
// RequireClientSecret might as well be true if you are giving this client a secret
RequireClientSecret = true,
AllowAccessTokensViaBrowser = true,
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
// Added MyAPI2 from my example above
AllowedScopes = { "MyAPI", "MyAPI2" },
RequireConsent = false,
AllowOfflineAccess = true
}
};
}
调用自省端点
以下代码来自WebApi控制器。 (请记住,IdentityServer权限和ApiResource在此讨论中托管在同一Web应用程序中)。 客户可以请求此方法。
在此方法中,您可以看到它调用其权限的内省端点来验证/解密access_token。 这个示例中没有必app.UseIdentityServerAuthentication
,因为我们将web应用程序设置为app.UseIdentityServerAuthentication
,它已经执行此操作。 内省端点将用于引用令牌,或者当Web应用程序本身无法验证access_token时。
[Route("api/[controller]/[action]")]
[Produces("application/json")]
public class DataController : Controller
{
[HttpGet]
[Authorize]
public async Task<IEnumerable<String>> Secure()
{
var accessToken = await HttpContext.Authentication.GetTokenAsync("access_token");
var introspectionClient = new IntrospectionClient("https://localhost:44388/connect/introspect", "MyAPI", "TopSecret");
var response = await introspectionClient.SendAsync(new IntrospectionRequest { Token = accessToken });
var isActive = response.IsActive;
var claims = response.Claims;
return new[] { "secure1", "secure2", $"isActive: {isActive}", JsonConvert.SerializeObject(claims) };
}
}
在这里,使用IntrospectionClient
作为ApiScope“MyAPI”将得到401,因为由于前面提到的对象初始化器问题,数据库缺少ApiScope。
最后一件事
另一个可能的问题是在数据库编辑器中手动添加散列ApiSecret可能会导致奇怪的复制/粘贴问题,使文本无法正确解密。
查看完整解决方案
https://github.com/travisjs/AspNetCore-IdentityServer-Instrospection
我希望这可以帮助解决问题的根源或至少激发一个新的想法。
(myapi:绝密)。 我的令牌在帖子的正文中
内省端点需要使用scope:apisecret
的基本身份验证scope:apisecret
,而不是name:apisecret
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.