Доступ к защищенному API на IdentityServer4 с токеном на предъявителя - PullRequest
0 голосов
/ 11 октября 2018

Я пытался найти решение этой проблемы, но не нашел правильный текст для поиска.

Мой вопрос: как мне настроить мой IdentityServer, чтобы он также принимал / авторизировал запросы Api?с BearerTokens?

У меня настроен и работает IdentityServer4.Я также настроил тестовый API на своем IdentityServer, как показано ниже:

[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,
            },

Когда я используюПочтальон для доступа к защищенному API, но он всегда перенаправляет на страницу входа, даже если в заголовок запроса был добавлен действительный токен на предъявителя.

Закомментирование атрибута [Authorize] вернет ответ, но, конечно,User.Claims пустые.

При входе в IdentityServer (через браузер) и последующем доступе к API (через браузер) он также возвращает ответ.На этот раз User.Claims доступны.

1 Ответ

0 голосов
/ 11 октября 2018

Существует пример совместного размещения защищенного API внутри IdentityServer: IdentityServerAndApi

Я быстрое сравнение между их запуском и вашим, что они вызывают AddJwtBearer вместо AddIdentityServerAuthentication:

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

Атрибут Authorize также устанавливает схему аутентификации:

[Authorize(AuthenticationSchemes = "Bearer")]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...