简体   繁体   中英

Save tokens in Cookie with ASP.NET Core Identity

I want to save something inside my 'Identity' generated cookie. I'm currently using the default Identity setup from the Docs.

Startup.cs

services.Configure<IdentityOptions>(options =>
{
    // User settings
    options.User.RequireUniqueEmail = true;

    // Cookie settings
    options.Cookies.ApplicationCookie.AuthenticationScheme = "Cookies";
    options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromHours(1);
    options.Cookies.ApplicationCookie.SlidingExpiration = true;
    options.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
    options.Cookies.ApplicationCookie.LoginPath = "/Account";
    options.Cookies.ApplicationCookie.LogoutPath = "/Account/Logout";
});

AccountController.cs

var result = await _signInManager.PasswordSignInAsync(user.UserName, model.Password, true, true);

if (result.Succeeded)
{
    _logger.LogInformation(1, "User logged in.");

    var tokens = new List<AuthenticationToken>
    {
        new AuthenticationToken {Name = "Test", Value = "Test"},
    };


    var info = await HttpContext.Authentication.GetAuthenticateInfoAsync("Cookies");
    info.Properties.StoreTokens(tokens);

It seems this doesn't work. Because the cookie isn't created yet. The 'Info' variable is empty.

I could solve it by using the 'CookieMiddleware'

Startup.cs

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationScheme = "Cookies",
    ExpireTimeSpan = TimeSpan.FromHours(1),
    SlidingExpiration = true,
    AutomaticAuthenticate = true,
    LoginPath = "/Account",
    LogoutPath = "/Account/Logout",
});

But than I need to use

await HttpContext.Authentication.SignInAsync("Cookies", <userPrincipal>);

In this case I need to build myself a 'user principal'. And I prefer to leverage 'Identity' for this matter.

So is it possible to combine this? If this is not the case how do I generate the claimsprincipal on a good way.

Without the need to 'map' every claim.

List<Claim> userClaims = new List<Claim>
{
    new Claim("UserId", Convert.ToString(user.Id)),
    new Claim(ClaimTypes.Name, user.UserName),
    // TODO: Foreach over roles
};

ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims));
await HttpContext.Authentication.SignInAsync("Cookies", principal);

So something like:

ClaimsPrincipal pricipal = new ClaimsPrincipal(user.Claims); 

This doesn't work because user.Claims is of type IdentityUserClaim and not of type Security.Claims.Claim.

Thanks for reading. Have a good day,

Sincerely, Brecht

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM