Почему identityserver4 не даёт токены после входа

Я пишу сервер авторизации с клиентом, засекреченными API и самим identity server в одном приложении. А не с клиент серверной архитектурой, примеров которых полно. После того как я вхожу в аккаунт и пытаюсь по запросу на метод контроллера получить токены. У меня это не выходить ибо значение их null, как я понимаю я либо что-то напутал в настройке сервера либо надо использовать httpClientFactory для создания клиента. Вот моя настройка identityServer4:

public static IEnumerable<IdentityResource> IdentityResources =>
    new List<IdentityResource>
    {
        new IdentityResources.OpenId(),
        new("user-profile", "Your profile data", 
            new List<string>{ "name", "role", "email" })
    };

public static IEnumerable<ApiScope> ApiScopes =>
    new List<ApiScope>
    {
        new("UserInfoScope",new List<string>
        {
            JwtClaimTypes.Subject, JwtClaimTypes.Name, JwtClaimTypes.Role, JwtClaimTypes.ClientId
        })
    };

public static IEnumerable<ApiResource> ApiResources =>
    new List<ApiResource>
    {
        new("Client")
        {
            Scopes =
            {
                "UserInfoScope"
            }
        }
    };

public static IEnumerable<Client> Clients =>
    new List<Client>
    {
        new()
        {
            ClientId = "client",
            ClientSecrets =
            {
                new Secret("client-secret".Sha256())
            },
            AllowedGrantTypes = GrantTypes.Code,
            RedirectUris = new List<string>{ "https://localhost:5005/signin-oidc" },
            PostLogoutRedirectUris = {"https://localhost:5005/signout-callback-oidc"},
            AllowedScopes =
            {
                IdentityServerConstants.StandardScopes.OpenId,
                "UserInfoScope",
                "user-profile",
                "Client",
                IdentityServerConstants.StandardScopes.OfflineAccess
            },
            RequireConsent = false,
            AccessTokenLifetime = 180,
            AllowOfflineAccess = true,
            UpdateAccessTokenClaimsOnRefresh = true,
            RequirePkce = true,
        }
    };
var builder = services.AddIdentityServer(opt =>
        {
            opt.EmitStaticAudienceClaim = true;
        })
        .AddAspNetIdentity<Account>()
        .AddInMemoryApiResources(IdentityServerConfiguration.ApiResources)
        .AddInMemoryIdentityResources(IdentityServerConfiguration.IdentityResources)
        .AddInMemoryApiScopes(IdentityServerConfiguration.ApiScopes)
        .AddInMemoryClients(IdentityServerConfiguration.Clients);
        
    builder.AddDeveloperSigningCredential();

    services.ConfigureApplicationCookie(opt =>
    {
        opt.LoginPath = "/auth/signin";
        opt.LogoutPath = "/auth/logout";
    });
    
    services.AddAuthentication(opt =>
        {
            opt.DefaultChallengeScheme = "oidc"; 
        })
        .AddCookie("Cookie", opt =>
        {
            opt.Events.OnSigningOut = async e =>
            {
                await e.HttpContext.RevokeUserRefreshTokenAsync();
            };
        })
        .AddOpenIdConnect("oidc", opt =>
        {
            opt.Authority = "https://localhost:5005";
            opt.RequireHttpsMetadata = false;
            opt.ClientId = "client";
            opt.ClientSecret = "client-secret";
            opt.ResponseType = "code";
            opt.SaveTokens = true;
            
            opt.GetClaimsFromUserInfoEndpoint = true;
            
            opt.Scope.Clear();
            opt.Scope.Add("openid");
            opt.Scope.Add("offline_access");
            opt.Scope.Add("UserInfoScope");
            opt.Scope.Add("user-profile");
        });
    
    services.AddAccessTokenManagement(options =>
        {
            options.Client.DefaultClient.Scope = "user-profile";
        })
        .ConfigureBackchannelHttpClient();

Далее я демонстрирую код метода контроллера для входа (который принимает returnUrl для получения пути, к примеру /authorize?параметры и последующего перехода на путь signin-oidc для получения user claims)

[HttpGet]
public async Task<IActionResult> SignIn(string? returnUrl)
{
    var signInModel = new SignInModel
    {
        ReturnUrl = returnUrl.IsNullOrEmpty() ? "https://localhost:5005" : returnUrl
    };
    return View(signInModel);
}

[HttpPost]
public async Task<IActionResult> SignIn(SignInModel signInModel)
{
    if (!ModelState.IsValid)
    {
        return View(signInModel);
    }

    var result = await _authService.SignInAsync(signInModel.Email, signInModel.Password);
    
    if (!string.IsNullOrEmpty(result))
    {
        ModelState.AddModelError(String.Empty, result);
        return View(signInModel);
    }
    

    return Redirect(signInModel.ReturnUrl);
}

Но вот в чём проблема: после входа я захожу на метод контроллера чтоб получить свои токены, знать что они есть и с возможностью потом сохранить refresh token.

[Authorize(Roles = "Doctor")]
public async Task<IActionResult> Privacy()
{
    var f = HttpContext;
    var accessToken = await HttpContext.GetTokenAsync("access_token");
    var idToken = await HttpContext.GetTokenAsync("id_token");
    var refreshToken = await HttpContext.GetTokenAsync("refresh_token");

    var _accessToken = new JwtSecurityTokenHandler().ReadJwtToken(accessToken);
    var _idToken = new JwtSecurityTokenHandler().ReadJwtToken(idToken);
    return View();
}

Смотрел так же через HttpContext в итоге их там нет. Единственные мысли по этому поводу что я где-то ошибся в конфигурации.


Ответы (0 шт):