C# 无法执行Cookie身份验证:SignInAsync和AuthenticateTasync未成功

C# 无法执行Cookie身份验证:SignInAsync和AuthenticateTasync未成功,c#,asp.net-core,cookies,.net-5,C#,Asp.net Core,Cookies,.net 5,我正在尝试构建一个非常简单的游乐场服务器,以便学习一些ASP.NET核心身份验证/授权概念。基本上是一个web应用程序,带有一个非常简单的控制器,将由Postman进行测试 我提出了我的代码的简化版本,由单个登录端点组成,该端点将使用Cookie身份验证对用户进行身份验证(无需凭据),如下所示: [ApiController] public class MyController : ControllerBase { [HttpGet("/login")] pu

我正在尝试构建一个非常简单的游乐场服务器,以便学习一些ASP.NET核心身份验证/授权概念。基本上是一个web应用程序,带有一个非常简单的控制器,将由Postman进行测试

我提出了我的代码的简化版本,由单个登录端点组成,该端点将使用Cookie身份验证对用户进行身份验证(无需凭据),如下所示:

[ApiController]
public class MyController : ControllerBase
{
    [HttpGet("/login")]
    public async Task<IActionResult> Login()
    {
        var claims = new[] { new Claim("name", "bob") };
        var identity = new ClaimsIdentity(claims);
        var principal = new ClaimsPrincipal(identity);

        await HttpContext.SignInAsync(principal);
        return Ok();
    }
}
然后我尝试通过调用
HttpContext.authenticateSync()
来替换
HttpContext.SignInAsync()
,以便在再次尝试调用
SignInAsync()
之前对用户进行身份验证:

[HttpGet("/login")]
public async Task<IActionResult> Login()
{
    var authResult = await HttpContext.AuthenticateAsync();
    if (authResult.Succeeded == false)
        return StatusCode(500, "Failed to autenticate!");
    return Ok();
}
我的项目以
net5.0
框架为目标,没有外部/显式依赖关系,下面是我使用的Startup类:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie();
    }


    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IConfiguration configs)
    {
        app.UseRouting();
        app.UseAuthentication();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}
我知道我一定错过了一些基本的东西。我也不确定自己是否基于.NET5.0的最新版本


为什么cookie身份验证(
HttpContext.SignInAsync()
/
HttpContext.authenticatesync()
)失败?

这是自Asp.Net Core 3.0预览版6以来的一次突破性更改。文档在这里,但它不包含破坏性更改的动机

真正的动机在于:

简而言之,您需要显式指定auth方案:

new ClaimsIdentity(claims, /*Explicit*/CookieAuthenticationDefaults.AuthenticationScheme)

我也遇到了同样的问题,这一变化对我的情况也有帮助。

仅以Dmitry的回答为基础,这里是一个工作登录的片段(.NET 5.0,可能适用于3.0及以上版本):

var索赔=新列表
{
//来自外部API的示例声明
新索赔(“sub”,用户ID),
新索赔(ClaimTypes.Name、用户名)
};
var claimsIdentity=新的claimsIdentity(
声明,CookieAuthenticationDefaults.AuthenticationScheme);
var signIn=HttpContext.SignInAsync(新的ClaimsPrincipal(claimsIdentity)),
_AuthenticationOptions(model.RememberMe));

这解决了我从2.2升级到5.0时的问题。
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie();
    }


    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IConfiguration configs)
    {
        app.UseRouting();
        app.UseAuthentication();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}
new ClaimsIdentity(claims, /*Explicit*/CookieAuthenticationDefaults.AuthenticationScheme)
var claims = new List<Claim>
{
    // example claims from external API
    new Claim("sub", userId), 
    new Claim(ClaimTypes.Name, username)
};

var claimsIdentity = new ClaimsIdentity(
                claims, CookieAuthenticationDefaults.AuthenticationScheme);
var signIn = HttpContext.SignInAsync(new ClaimsPrincipal(claimsIdentity),
                _userService.AuthenticationOptions(model.RememberMe));