Ссылочный токен - для клиента не настроен общий секрет - PullRequest
0 голосов
/ 08 января 2020

Я пытаюсь настроить опорный токен в IdentityServer4, следуя этому руководству и используя EntityFramework Core для конфигурации и рабочих данных.

Это то, что я получил после выполнения этих инструкций: IdentityServer4: Startup.cs

IdentityServer4: Startup.cs

services.AddIdentityServer(
    options =>
    {
        options.Events.RaiseErrorEvents = true;
        options.Events.RaiseFailureEvents = true;
        options.Events.RaiseInformationEvents = true;
        options.Events.RaiseSuccessEvents = true;
    })
 .AddDeveloperSigningCredential()
 .AddInMemoryApiResources(ProjectName.Configuration.Scopes.GetScopes())
 .AddInMemoryClients(ProjectName.Configuration.Clients.GetClient())
 .AddInMemoryIdentityResources(ProjectName.Configuration.IdentityResources.GetIdentityResources())
 .AddAspNetIdentity<ApplicatonUser>()
 .AddConfigurationStore(builder =>
 {
     builder.ConfigureDbContext = builder => builder.UseNpgsql(connectionString, options => options.MigrationsAssembly(migrationsAssembly));
 })
.AddOperationalStore(builder =>
{
    builder.ConfigureDbContext = builder => builder.UseNpgsql(connectionString, options => options.MigrationsAssembly(migrationsAssembly));
});

Файл запуска клиента

// Add validation.

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddIdentityServerAuthentication(options =>
{
    options.Authority = "http://localhost:53679";
    options.ClaimsIssuer = "http://localhost:53679";
    options.RequireHttpsMetadata = false;
    options.ApiName = "myApi";
    options.ApiSecret = "secret";
    options.SupportedTokens = SupportedTokens.Both;
});

Config.cs

public static List<Client> GetClient()
{
    return new List<Client>()
    {

        new Client()
        {
            ClientId="projectname",
            ClientSecrets=new List<Secret>()
            {
                new Secret("secret".Sha256()),
            },
           AllowedScopes = { "myApi" },
           AccessTokenType = AccessTokenType.Reference,
           AllowedGrantTypes = GrantTypes.ResourceOwnerPassword

        }
    };
}

Файл ApiResource

public static IEnumerable<ApiResource> GetScopes()
{
    return new List<ApiResource>
    {
        new ApiResource("myApi", "API Application")
    {
    ApiSecrets = new List<Secret>
    {
        new Secret("secret".Sha256())
    }
}

Когда я сделал запрос к / connect / token с указанием c информации о клиенте. Я получил access_token, отправленный сервером:

Но когда я использовал ранее полученный токен доступа, чтобы сделать запрос к защищенному API. 401 было отправлено обратно:

Вот что я получил в выводе Visual Studio:

IdentityServer4.EntityFramework.Stores.ResourceStore: Debug: Found myApi API resource in database
IdentityServer4.Validation.HashedSharedSecretValidator: Debug: No shared secret configured for client.IdentityServer4.Validation.SecretValidator: Debug: Secret validators could not validate secret IdentityServer4.Events.DefaultEventService: Information: {`enter code here`
  "Name": "API Authentication Failure",
  "Category": "Authentication",
  "EventType": "Failure",
  "Id": 1021,
  "ApiName": "myApi",
  "Message": "Invalid API secret",
  "ActivityId": "80000048-0004-fc00-b63f-84710c7967bb",
  "TimeStamp": "2020-01-08T07:14:06Z",
  "ProcessId": 32868,
  "LocalIpAddress": "::1:53679",
  "RemoteIpAddress": "::1"
}
IdentityServer4.Validation.ApiSecretValidator: Error: API validation failed.
IdentityServer4.Endpoints.IntrospectionEndpoint: Error: API unauthorized to call introspection endpoint. aborting.
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request finished in 2236.9377ms 401 
System.Net.Http.HttpClient.IdentityModel.AspNetCore.OAuth2Introspection.BackChannelHttpClientName.ClientHandler: Information: Received HTTP response after 2243.0106ms - Unauthorized
System.Net.Http.HttpClient.IdentityModel.AspNetCore.OAuth2Introspection.BackChannelHttpClientName.LogicalHandler: Information: End processing HTTP request after 2256.764ms - Unauthorized
IdentityModel.AspNetCore.OAuth2Introspection.OAuth2IntrospectionHandler: Error: Error returned from introspection endpoint: Unauthorized
IdentityModel.AspNetCore.OAuth2Introspection.OAuth2IntrospectionHandler: Information: BearerIdentityServerAuthenticationIntrospection was not authenticated. Failure message: Error returned from introspection endpoint: Unauthorized
IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler: Information: Bearer was not authenticated. Failure message: Error returned from introspection endpoint: Unauthorized
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService: Information: Authorization failed.
IdentityModel.AspNetCore.OAuth2Introspection.OAuth2IntrospectionHandler: Information: AuthenticationScheme: BearerIdentityServerAuthenticationIntrospection was challenged.
IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler: Information: AuthenticationScheme: Bearer was challenged.
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request finished in 2294.4558ms 401 

Но когда я использовал ранее полученный токен доступа, чтобы сделать запрос к защищенному API. 401 было отправлено обратно:

Я потратил часы на поиск ** Identity Server 4 со справочными руководствами по токенам **, но не повезло.

Это очень расстраивает.

Любая помощь?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...