Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用ASP.NET核心标识在Cookie中保存令牌_C#_Asp.net_Cookies_Asp.net Core_Asp.net Identity - Fatal编程技术网

C# 使用ASP.NET核心标识在Cookie中保存令牌

C# 使用ASP.NET核心标识在Cookie中保存令牌,c#,asp.net,cookies,asp.net-core,asp.net-identity,C#,Asp.net,Cookies,Asp.net Core,Asp.net Identity,我想在“身份”生成的cookie中保存一些内容。我目前正在使用文档中的默认身份设置 Startup.cs services.Configure<IdentityOptions>(options => { // User settings options.User.RequireUniqueEmail = true; // Cookie settings options.Cookies.ApplicationCookie.Authenticati

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

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";
});
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationScheme = "Cookies",
    ExpireTimeSpan = TimeSpan.FromHours(1),
    SlidingExpiration = true,
    AutomaticAuthenticate = true,
    LoginPath = "/Account",
    LogoutPath = "/Account/Logout",
});
但比我需要用的还要多

await HttpContext.Authentication.SignInAsync("Cookies", <userPrincipal>);
这不起作用,因为user.Claims是IdentityUserClaim类型,而不是Security.Claims.Claim类型

谢谢你的阅读。 祝你过得愉快


老实说,布莱希特我设法解决了我的问题

我编写了与“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
}
在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);
}
private async Task AddTokensToCookie(应用程序用户,字符串密码)
{
//检索访问令牌和刷新令牌
var disco=await DiscoveryClient.GetAsync(Environment.GetEnvironmentVariable(“AUTHORITY\u SERVER”)??“http://localhost:5000");
如果(迪斯科舞厅)
{
_logger.LogError(disco.Error);
抛出disco.Exception;
}
var tokenClient=新的tokenClient(disco.TokenEndpoint,“客户机”、“机密”);
var tokenResponse=wait tokenClient.RequestResourceOwnerPasswordAsync(user.Email,密码,“脱机访问api1”);
var tokens=新列表
{
新的AuthenticationToken{Name=OpenIdConnectParameterNames.AccessToken,Value=tokenResponse.AccessToken},
新的AuthenticationToken{Name=OpenIdConnectParameterNames.RefreshToken,Value=tokenResponse.RefreshToken}
};
var expiresAt=DateTime.UtcNow+TimeSpan.FromSeconds(tokenResponse.ExpiresIn);
令牌。添加(新的AuthenticationToken
{
Name=“到期日”,
Value=expireSet.ToString(“o”,CultureInfo.InvariantCulture)
});
//将代币存储在cookie中
var prop=新的AuthenticationProperties();
道具存储代币(代币);
prop.IsPersistent=true;//记得我吗
wait _signInManager.SignInAsync(用户,道具);
}
最后4行代码是最重要的

ClaimsPrincipal pricipal = new ClaimsPrincipal(user.Claims); 
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
}
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);
}