Неавторизованный клиент при запросе токена с помощью IdentityServer4. NET Core 3.1 - PullRequest
0 голосов
/ 26 мая 2020

Я пытаюсь заставить IdentityServer4 работать, но, к сожалению, безуспешно. Объясню проблему более подробно. Я использую IdentityServer4, а также. NET core Identity. У меня есть приложение. net core mvc со страницей входа. Вы в основном входите в систему с именем пользователя и паролем. Когда вы входите в систему, мне нужно сгенерировать токен jwt. Я делаю это, используя следующий код:

[HttpGet]
        public async Task<IActionResult> GetClientToken(string clientId, string clientSecret, string grantType, string scope, string username, string password)
        {
            var serverClient = HttpClientFactory.CreateClient();
            var discoveryDocument = await serverClient.GetDiscoveryDocumentAsync($"{Request.Scheme}://{Request.Host.Value}");

            var tokenClient = HttpClientFactory.CreateClient();

            var tokenResponse = await tokenClient.RequestPasswordTokenAsync(
                new PasswordTokenRequest
                {
                    ClientId = clientId,
                    ClientSecret = clientSecret,
                    GrantType = grantType,
                    Address = discoveryDocument.TokenEndpoint,
                    UserName = username,
                    Password = password,
                    Scope = scope,
                });

            if (!tokenResponse.IsError)
            {
                return Ok(new TokenResponseModel()
                {
                    access_token = tokenResponse.AccessToken,
                    refresh_token = tokenResponse.RefreshToken,
                    expires_in = tokenResponse.ExpiresIn,
                    scope = tokenResponse.Scope,
                    token_type = tokenResponse.TokenType,
                });
            }

            return BadRequest(tokenResponse.Error);
        }

Каждый раз, когда я запрашиваю токен, я получаю неавторизованный клиент.

Мои данные для заполнения следующим образом:

 public static IEnumerable<ApiResource> GetApis() =>
            new List<ApiResource>
            {
                new ApiResource("AppointmentBookingApi"),
                new ApiResource("PaymentApi", new string[] { "patient.portal.api.payment" }),
            };

        public static IEnumerable<IdentityResource> GetIdentityResources() =>
            new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResource
                {
                    Name = "patient.portal.api",
                    UserClaims =
                    {
                        "patient.portal",
                    },
                }
            };

        public static IEnumerable<Client> GetClients() =>
            new List<Client>
            {
                new Client
                {
                    ClientId = "patient.portal.client.refresh",
                    ClientSecrets = { new Secret("secret".Sha256()) },

                    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                    RequirePkce = true,

                    RedirectUris = { "https://localhost:44307/signin-oidc" },
                    PostLogoutRedirectUris = { "https://localhost:44307/Home/Index" },

                    AllowedScopes =
                    {
                        "AppointmentBookingApi",
                        "PaymentApi",
                        IdentityServerConstants.StandardScopes.OpenId,
                        "patient.portal.api",
                    },

                    AllowOfflineAccess = true,
                    RequireConsent = false,
                },
                new Client
                {
                    ClientId = "patient.portal.client.code",
                    ClientSecrets = { new Secret("secret".Sha256()) },

                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    AllowedScopes =
                    {
                        "AppointmentBookingApi",
                    },
                },
            };

кто-нибудь знает, где я здесь ошибаюсь ????

...