Save tokens in Cookie with ASP.NET Core Identity

こ雲淡風輕ζ 提交于 2019-12-06 08:38:15

I managed to solve my problem.

I wrote the same functionality that is inside the 'signInManager'. But adding my own authentication property.

var result = await _signInManager.PasswordSignInAsync(user, model.Password, true, true);
if (result.Succeeded)
{
    await AddTokensToCookie(user, model.Password);
    return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
    // Ommitted
}
if (result.IsLockedOut)
{
    // Ommitted
}

Code that actually saves something (tokens) inside the cookie:

private async Task AddTokensToCookie(ApplicationUser user, string password)
{
    // Retrieve access_token & refresh_token
    var disco = await DiscoveryClient.GetAsync(Environment.GetEnvironmentVariable("AUTHORITY_SERVER") ?? "http://localhost:5000");

    if (disco.IsError)
    {
        _logger.LogError(disco.Error);
        throw disco.Exception;
    }

    var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
    var tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync(user.Email, password, "offline_access api1");

    var tokens = new List<AuthenticationToken>
    {
        new AuthenticationToken {Name = OpenIdConnectParameterNames.AccessToken, Value = tokenResponse.AccessToken},
        new AuthenticationToken {Name = OpenIdConnectParameterNames.RefreshToken, Value = tokenResponse.RefreshToken}
    };

    var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResponse.ExpiresIn);
    tokens.Add(new AuthenticationToken
    {
        Name = "expires_at",
        Value = expiresAt.ToString("o", CultureInfo.InvariantCulture)
    });

    // Store tokens in cookie
    var prop = new AuthenticationProperties();
    prop.StoreTokens(tokens);
    prop.IsPersistent = true; // Remember me

    await _signInManager.SignInAsync(user, prop);
}

The last 4 lines of code are the most important ones.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!