首页 文章

使用承载令牌访问IdentityServer4上的受保护API

提问于
浏览
3

我试图搜索此问题的解决方案,但没有找到正确的搜索文本 .

我的问题是,我如何配置我的IdentityServer,以便它也接受/授权Api请求与BearerTokens?

我已经配置并运行了IdentityServer4 . 我还在IdentityServer上配置了一个Test API,如下所示:

[Authorize]
[HttpGet]
public IActionResult Get()
{
    return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}

在我的startup.cs中,ConfigureServices()如下:

public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        ...
        // configure identity server with stores, keys, clients and scopes
        services.AddIdentityServer()
            .AddCertificateFromStore(Configuration.GetSection("AuthorizationSettings"), loggerFactory.CreateLogger("Startup.ConfigureServices.AddCertificateFromStore"))

            // this adds the config data from DB (clients, resources)
            .AddConfigurationStore(options =>
            {
                options.DefaultSchema = "auth";
                options.ConfigureDbContext = builder =>
                {
                    builder.UseSqlServer(databaseSettings.MsSqlConnString,
                        sql => sql.MigrationsAssembly(migrationsAssembly));
                };
            })

            // this adds the operational data from DB (codes, tokens, consents)
            .AddOperationalStore(options =>
            {
                options.DefaultSchema = "auth";
                options.ConfigureDbContext = builder =>
                    builder.UseSqlServer(databaseSettings.MsSqlConnString,
                        sql => sql.MigrationsAssembly(migrationsAssembly));

                // this enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup = true;
                options.TokenCleanupInterval = 30;
            })

            // this uses Asp Net Identity for user stores
            .AddAspNetIdentity<ApplicationUser>()
            .AddProfileService<AppProfileService>()
            ;

        services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
                {
                    options.Authority = authSettings.AuthorityUrl;
                    options.RequireHttpsMetadata = authSettings.RequireHttpsMetadata;
                    options.ApiName = authSettings.ResourceName;
                })

和Configure()如下:

// NOTE: 'UseAuthentication' is not needed, since 'UseIdentityServer' adds the authentication middleware
        // app.UseAuthentication();
        app.UseIdentityServer();

我有一个客户端配置为允许隐式授权类型,并已配置 ApiName 作为AllowedScopes之一:

new Client
            {
                ClientId = "47DBAA4D-FADD-4FAD-AC76-B2267ECB7850",
                ClientName = "MyTest.Web",
                AllowedGrantTypes = GrantTypes.Implicit,

                RequireConsent = false,

                RedirectUris           = { "http://localhost:6200/assets/oidc-login-redirect.html", "http://localhost:6200/assets/silent-redirect.html" },
                PostLogoutRedirectUris = { "http://localhost:6200/?postLogout=true" },
                AllowedCorsOrigins     = { "http://localhost:6200" },

                AllowedScopes =
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Email,
                    "dev.api",
                    "dev.auth" // <- ApiName for IdentityServer authorization
                },
                AllowAccessTokensViaBrowser = true,
                AllowOfflineAccess = true,
                AccessTokenLifetime = 18000,
            },

当我使用Postman访问受保护的API但它总是重定向到登录页面,即使已将有效的承载令牌添加到请求标头 .

注释掉[Authorize]属性将正确返回响应,但User.Claims当然是空的 .

登录IdentityServer(通过浏览器)然后访问API(通过浏览器)时,它也会返回响应 . 这次,User.Claims可用 .

1 回答

  • 3

    在IdentityServer中有一个共同托管受保护API的示例:IdentityServerAndApi

    我在他们的创业公司和你的公司之间进行快速比较是他们正在调用 AddJwtBearer 而不是 AddIdentityServerAuthentication

    services.AddAuthentication()
     .AddJwtBearer(jwt => {
        jwt.Authority = "http://localhost:5000";
        jwt.RequireHttpsMetadata = false;
        jwt.Audience = "api1";
    });
    

    Authorize 属性还设置身份验证方案:

    [Authorize(AuthenticationSchemes = "Bearer")]
    

相关问题