Как правильно использовать претензии с IdentityServer4? - PullRequest
0 голосов
/ 17 октября 2018

Я пытаюсь понять, как это работает, поэтому, пожалуйста, потерпите меня.Вот мой конфиг для сервера идентификации:

    public static IEnumerable<ApiResource> GetApiResources(IConfiguration configuration)
    {
        return new []
        {
            new ApiResource
            {
                Name = "invoices.api",

                ApiSecrets =
                {
                    new Secret("invoices.api.secret".Sha256()),
                },

                Scopes =
                {
                    new Scope("invoices.api.scope"),
                },

                UserClaims =
                {
                    "custom_role",
                }
            }
        };
    }

    public static IEnumerable<Client> GetClients(IConfiguration configuration)
    {
        return new []
        {
            new Client
            {
                ClientId = "invoices.ui",
                RequireConsent = false,
                AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                AccessTokenType = AccessTokenType.Reference,

                AllowedCorsOrigins = configuration.GetSection("Redirect").Get<RedirectOptions>().AllowedCorsOrigins.ToList(),
                RedirectUris = configuration.GetSection("Redirect").Get<RedirectOptions>().RedirectUris.ToList(),
                PostLogoutRedirectUris = configuration.GetSection("Redirect").Get<RedirectOptions>().PostLogoutRedirectUris.ToList(),

                ClientSecrets =
                {
                    new Secret("invoices.ui.secret".Sha256())
                },

                AllowedScopes =
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    "invoices.api.scope",
                },
            }
        };
    }

    public static IEnumerable<TestUser> GetUsers(IConfiguration configuration)
    {
        return new []
        {
            new TestUser
            {
                SubjectId = "1",
                Username = "alice",
                Password = "123",
                Claims =
                {
                    new Claim("custom_role", "user"),
                },
            },
            new TestUser
            {
                SubjectId = "2",
                Username = "bob",
                Password = "123",
                Claims =
                {
                    new Claim("custom_role", "admin"),
                },
            }
        };
    }

    public static IEnumerable<IdentityResource> GetIdentityResources(IConfiguration configuration)
    {
        return new []
        {
            new IdentityResources.OpenId(),
        };
    }

И вот как настраивается мой MVC-клиент:

    services.AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = "oidc";
    })
    .AddCookie(opts =>
    {
        //opts.ExpireTimeSpan = TimeSpan.FromSeconds(60);
    })
    .AddOpenIdConnect("oidc", opts =>
    {
        opts.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

        opts.DisableTelemetry = true;

        opts.Authority = Configuration.GetValue<string>("IdentityServer");
        opts.RequireHttpsMetadata = false;

        opts.ClientId = "invoices.ui";
        opts.ClientSecret = "invoices.ui.secret";
        opts.ResponseType = "code id_token";

        opts.SaveTokens = true;
        opts.GetClaimsFromUserInfoEndpoint = true;

        opts.Scope.Clear();
        opts.Scope.Add("openid");
        opts.Scope.Add("invoices.api.scope");
    });

После аутентификации пользователя я пытаюсь увидеть его утвержденияв таком виде:

    @foreach (var claim in User.Claims)
    {
        <dt>@claim.Type</dt>
        <dd>@claim.Value</dd>
    }

Но в списке нет претензий "custom_role".Журналы сервера идентификации показывают, что информация о пользователе была запрошена клиентом из конечной точки информации пользователя, но мой «custom_role» не был перенесен туда, однако в журналах сервера идентификации он показывает, что у пользователя она есть.

Как получить доступ к моим пользовательским заявкам в приложении MVC?Мне нужно получить их от конечной точки пользователя и использовать для авторизации.

Ответы [ 2 ]

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

Кажется, что добавление ресурса идентификации с указанными утверждениями решает проблему даже со встроенной реализацией ProfileService:

    public static IEnumerable<IdentityResource> GetIdentityResources(IConfiguration configuration)
    {
        return new []
        {
            new IdentityResources.OpenId(),
            new IdentityResource
            {
                Name = "roles.scope",
                UserClaims =
                {
                    "custom_role",
                }
            }
        };
    }

Также добавлено в качестве области действия для клиента:

    AllowedScopes =
    {
        IdentityServerConstants.StandardScopes.OpenId,
        "invoices.api.scope",
        "roles.scope",
    },
0 голосов
/ 17 октября 2018

Если вы запрашиваете токен доступа и Identity Token ("code id_token") Identity Server не будет включать заявки пользователей по умолчанию.

Решениеустановить AlwaysIncludeUserClaimsInIdToken в true.См. http://docs.identityserver.io/en/release/reference/client.html

Объяснение, почему существуют эти настройки, здесь: https://leastprivilege.com/2016/12/14/optimizing-identity-tokens-for-size/

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