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

时间:2018-10-11 17:10:41

标签: c# asp.net-core jwt identityserver4 bearer-token

我试图寻找解决此问题的方法,但没有找到正确的搜索文字。

我的问题是,如何配置我的IdentityServer,使其也可以接受/授权带有BearerToken的Api请求?

我已配置并正在运行IdentityServer4。 我还在我的IdentityServer上配置了一个测试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时,即使将有效的Bearer Token添加到了Request标头中,它总是重定向到Login页面。

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

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

4 个答案:

答案 0 :(得分: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")]

答案 1 :(得分:2)

如果要将默认身份验证方案设置为策略之上的一级(当您有多个策略或根本没有策略时,这最为相关):

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;                
}).AddJwtBearer(o =>
{
    o.Authority = "http://localhost:5000";
    o.RequireHttpsMetadata = false;
    o.Audience = "api1";             
});

然后,您可以简单地使用控制器方法上方的[Authorize]标签属性,而不会用sceme污染每个授权属性:

[Authorize]
public IActionResult GetFoo()
{
}

答案 2 :(得分:0)

找到了更好的解决方案,请在Startup.cs中进行配置:

services.AddAuthentication()
    .AddLocalApi();

services.AddAuthorization(options =>
{
    options.AddPolicy(IdentityServerConstants.LocalApi.PolicyName, policy =>
    {
        policy.AddAuthenticationSchemes(IdentityServerConstants.LocalApi.AuthenticationScheme);
        policy.RequireAuthenticatedUser();
    });
});

并在控制器中使用:

[Authorize(IdentityServerConstants.LocalApi.PolicyName)]
public class UserInfoController : Controller
{
    ...
}

答案 3 :(得分:0)

或者更简单:

services.AddLocalApiAuthentication();

同样,你仍然需要

[Authorize(IdentityServerConstants.LocalApi.PolicyName)]

在您的控制器/方法上。并且不要忘记添加

IdentityServerConstants.LocalApi.ScopeName

到令牌中允许的范围/请求的范围。 有关详情,请参阅 docs