asp.net-core - IdentityServer AccessTokenValidation 结果中的 Token 未激活

标签 asp.net-core identityserver4

我将 IdentityServer 与 AccessTokenType.Reference 一起使用和一个 API。 API 无法通过以下错误日志对请求的用户进行身份验证:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.0 POST http://dev.applicationname.com/api/query text/plain 36
info: IdentityModel.AspNetCore.OAuth2Introspection.OAuth2IntrospectionHandler[7]
      BearerIdentityServerAuthenticationIntrospection was not authenticated. Failure message: Token is not active.
info: IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler[7]
      Bearer was not authenticated. Failure message: Token is not active.
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed for user: (null).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
      Executing ChallengeResult with authentication schemes ().
info: IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler[12]
      AuthenticationScheme: Bearer was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action ApplicationName.Services.QueryHandler.Controllers.QueryController.PostAsync (ApplicationName.Services.QueryHandler) in 1.0248ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 49.0536ms 401

服务
public void ConfigureServices(IServiceCollection services)
{
    services
        .AddMvcCore()
        .AddAuthorization()
        .AddJsonFormatters();

    services
        .AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
        .AddIdentityServerAuthentication(options =>
        {
            options.Authority = "http://localhost:5000";
            options.ApiName = "my_api_name";
            options.ApiSecret = "my_api_secret";
        });
}

身份服务器

启动文件
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, IdentityRole>(options =>
        {
            // ...
        })
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    // ...

    services.AddIdentityServer(options =>
        {
            options.IssuerUri = "http://localhost:5000";
            options.PublicOrigin = "http://localhost:5000";
        })
        .AddDeveloperSigningCredential()
        .AddInMemoryPersistedGrants()
        .AddInMemoryIdentityResources(Config.GetIdentityResources())
        .AddInMemoryApiResources(Config.GetApiResources())
        .AddInMemoryClients(Config.GetClients())
        .AddAspNetIdentity<ApplicationUser>();
}

配置文件
public static IEnumerable<ApiResource> GetApiResources()
{
    yield return new ApiResource
    {
        Name = "my_api_name",
        ApiSecrets = {new Secret("my_api_secret".Sha256())},
        Scopes = {new Scope {Name = $"my_api_name.full_access"}},
        UserClaims =
        {
            JwtClaimTypes.Name,
            JwtClaimTypes.Email,
            "tenant_id"
        }
    };
}

public static IEnumerable<Client> GetClients(string baseUrl)
{
    yield return new List<Client>
    {
        new Client
        {
            ClientId = "frontend",
            ClientName = "AngularClient",
            AccessTokenType = AccessTokenType.Reference,
            AllowAccessTokensViaBrowser = true,
            AllowedGrantTypes = GrantTypes.Implicit,
            AllowOfflineAccess = true,
            AlwaysIncludeUserClaimsInIdToken = true,
            RequireConsent = false,
            RequireClientSecret = false,

            RedirectUris =
            {
                "http://localhost:4200/signin-oidc"
            },
            PostLogoutRedirectUris =
            {
                "http://localhost:4200/signout-callback-oidc"
            },
            AllowedCorsOrigins =
            {
                "http://localhost:4200"
            },
            AllowedScopes = new List<string>
            {
                IdentityServerConstants.StandardScopes.OpenId,
                IdentityServerConstants.StandardScopes.Profile,
                IdentityServerConstants.StandardScopes.Email,
                "tenant_id",
                "my_api_name.full_access"
            }
        }
    };
}

在 IdentityServer 中,我收到以下错误日志:
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
      Invoking IdentityServer endpoint: IdentityServer4.Endpoints.IntrospectionEndpoint for /connect/introspect
[15:17:44 Information] IdentityServer4.Hosting.IdentityServerMiddleware
Invoking IdentityServer endpoint: IdentityServer4.Endpoints.IntrospectionEndpoint for /connect/introspect

fail: IdentityServer4.Validation.TokenValidator[0]
      Invalid reference token.
      {
        "ValidateLifetime": true,
        "AccessTokenType": "Reference",
        "TokenHandle": "2a29182593d7eb69e9845e3d94b16f3056bc27da6cb6d6ae760733b3141dacdb"
      }
[15:17:44 Error] IdentityServer4.Validation.TokenValidator
Invalid reference token.
{
  "ValidateLifetime": true,
  "AccessTokenType": "Reference",
  "TokenHandle": "2a29182593d7eb69e9845e3d94b16f3056bc27da6cb6d6ae760733b3141dacdb"
}

info: IdentityServer4.Endpoints.IntrospectionEndpoint[0]
      Success token introspection. Token active: False, for API name: my_api_name
[15:17:44 Information] IdentityServer4.Endpoints.IntrospectionEndpoint
Success token introspection. Token active: False, for API name: my_api_name

我假设存在错误配置但看不到它。

最佳答案

我认为您必须添加对资源的客户端访问权限,否则 IdentityServer 将继续拒绝引用 token 验证。 apiResource 必须在客户端允许的范围内,恕我直言,这有点令人困惑。

public static IEnumerable<Client> GetClients(string baseUrl)
{
    yield return new List<Client>
    {
        new Client
        {
            AllowedScopes = new List<string>
            {
                IdentityServerConstants.StandardScopes.OpenId,
                IdentityServerConstants.StandardScopes.Profile,
                IdentityServerConstants.StandardScopes.Email,
                "tenant_id",
                "my_api_name", // add this
                "my_api_name.full_access"
            }
        }
    };
}

关于asp.net-core - IdentityServer AccessTokenValidation 结果中的 Token 未激活,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48544376/

相关文章:

javascript - XMLHttpRequest 无法加载 No 'Access-Control-Allow-Origin' > 请求的资源上存在 header

c# - 如何在 ASP.NET Core 应用程序中将记录器传递到服务器端的 SignalR hub

Angular - 在 Azure 上托管时,在运行时从服务器变量读取配置

.net - DiscoveryClient.GetAsync ("http://localhost:5000"中的崩溃)

asp.net-mvc - IdentityServer4 用户管理与单独的 MVC 客户端 (AspNetIdentity)

identityserver4 - 身份服务器 : API resources and scopes

Azure 网络核心 : The specified CGI application encountered an error and the server terminated the process

c# - Entity Framework 数据库更新但数据库上下文未显示更新

c# - Entity Framework Core OnModelCreating 与 Migration,正确的开发工作流程

asp.net-core - 使用 IdentyServer4 和 Asp.net Core 2.0 的反向 channel 注销示例?