使用 ASP.NET Core Identity 在 Cookie 中保存令牌

Era*_*cht 3 c# asp.net cookies asp.net-identity asp.net-core

我想在我的“身份”生成的 cookie 中保存一些东西。我目前正在使用文档中的默认身份设置。

启动文件

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";
});
Run Code Online (Sandbox Code Playgroud)

账户控制器.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);
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用。因为 cookie 还没有创建。“信息”变量为空。

我可以通过使用“CookieMiddleware”来解决它

启动文件

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

但比我需要使用

await HttpContext.Authentication.SignInAsync("Cookies", <userPrincipal>);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我需要为自己建立一个“用户主体”。我更喜欢在这件事上利用“身份”。

那么有没有可能把它结合起来呢?如果不是这种情况,我如何以一种好的方式生成索赔委托人。

无需“映射”每个声明。

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);
Run Code Online (Sandbox Code Playgroud)

所以像:

ClaimsPrincipal pricipal = new ClaimsPrincipal(user.Claims); 
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为 user.Claims 是 IdentityUserClaim 类型而不是 Security.Claims.Claim 类型。

谢谢阅读。祝你有美好的一天,

真诚的,布莱希特

Era*_*cht 5

我设法解决了我的问题。

我编写了与“signInManager”相同的功能。但是添加我自己的身份验证属性。

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
}
Run Code Online (Sandbox Code Playgroud)

实际在 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);
}
Run Code Online (Sandbox Code Playgroud)

最后 4 行代码是最重要的。