如何验证用户的 cookie 并在身份框架中提取他们的声明?
How do I validate a user's cookie and extract their claims in identity framework?
我目前正在使用身份框架为用户创建和存储 cookie。当用户尝试使用 cookie 登录时,我无法从 cookie 中获取用户声明。有没有办法在传入cookie时解密或在httpcontext中找到它?
我已经尝试搜索 httpcontext,目前我正在尝试找到一种方法来解密传入的 cookie。
来自startup.cs
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.Cookie.Name = "MyCookie.Identity";
options.Cookie.Expiration = TimeSpan.FromDays(1);
});
我在哪里创建 cookie:
private async void AddUserCookie(AuthRequest authRequest)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, authRequest.UserName),
new Claim(ClaimTypes.Name, authRequest.UserName),
new Claim(ClaimTypes.Email, "TestClaim@Test.com")
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
AllowRefresh = true,
ExpiresUtc = DateTimeOffset.UtcNow.AddDays(1),
IsPersistent = true,
IssuedUtc = DateTimeOffset.UtcNow
};
await this._httpContextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties).ConfigureAwait(false);
当我尝试从 http 上下文中检索 cookie 时,它说用户身份中没有声明。
这里提供了答案:
https://forums.asp.net/t/2157350.aspx?How+does+cookie+authentication+in+identity+framework+work+
简而言之,我忘记在 startup.cs
中添加 app.UseAuthentication()
我目前正在使用身份框架为用户创建和存储 cookie。当用户尝试使用 cookie 登录时,我无法从 cookie 中获取用户声明。有没有办法在传入cookie时解密或在httpcontext中找到它?
我已经尝试搜索 httpcontext,目前我正在尝试找到一种方法来解密传入的 cookie。
来自startup.cs
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.Cookie.Name = "MyCookie.Identity";
options.Cookie.Expiration = TimeSpan.FromDays(1);
});
我在哪里创建 cookie:
private async void AddUserCookie(AuthRequest authRequest)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, authRequest.UserName),
new Claim(ClaimTypes.Name, authRequest.UserName),
new Claim(ClaimTypes.Email, "TestClaim@Test.com")
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
AllowRefresh = true,
ExpiresUtc = DateTimeOffset.UtcNow.AddDays(1),
IsPersistent = true,
IssuedUtc = DateTimeOffset.UtcNow
};
await this._httpContextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties).ConfigureAwait(false);
当我尝试从 http 上下文中检索 cookie 时,它说用户身份中没有声明。
这里提供了答案: https://forums.asp.net/t/2157350.aspx?How+does+cookie+authentication+in+identity+framework+work+
简而言之,我忘记在 startup.cs
中添加 app.UseAuthentication()