无法执行Cookie身份验证:SignInAsync和AuthenticateAsync不成功

c#

我正在尝试构建一个非常简单的游乐场服务器来研究一些 ASP.NET Core 身份验证/授权概念。基本上是一个带有一个非常简单的控制器的网络应用程序,可以用 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.SignInAsync()正在触发以下异常:

System.InvalidOperationException: SignInAsync when principal.Identity.IsAuthenticated is false is not allowed when AuthenticationOptions.RequireAuthenticatedSignIn is true.
   at Microsoft.AspNetCore.Authentication.AuthenticationService.SignInAsync(HttpContext context, String scheme, ClaimsPrincipal principal, AuthenticationProperties properties)
   at MyController.Login() in C:UsersvinicDesktopTEMPTestesAuthorizationControllersMyController.cs:line 18

然后我尝试HttpContext.SignInAsync()通过调用来替换HttpContext.AuthenticateAsync(),以便在尝试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();
}

但在这种情况下,AuthenticateAsync()结果总是返回失败 ( authResult.Succeeded= false),以后调用HttpContext.SignInAsync()将失败,并返回与之前相同的 InvalidOperationException。通过启用“跟踪”级别的日志记录,对 AuthenticateAsync() 的调用仅记录以下(不是很有帮助的)信息:

dbug: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[9]
      AuthenticationScheme: Cookies was not authenticated.
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler: Debug: AuthenticationScheme: Cookies was not authenticated.

我的项目以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();
        });
    }
}

我知道我一定在这里遗漏了一些非常基本的东西。我也不确定我所依赖的文档是否实际上是 .NET 5.0 的最新版本。

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

回答

这是自 Asp.Net Core 3.0 Preview 6 以来的重大变化。文档在这里https://docs.microsoft.com/en-us/dotnet/core/compatibility/aspnetcore#identity-signinasync-throws-exception-for- unauthenticated-identity,但它不包含破坏性变化的动机。

真正的动机在这里:https :
//github.com/dotnet/aspnetcore/issues/9255

简而言之,您需要明确指定身份验证方案:

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

我遇到了同样的问题,这种变化对我有帮助。


以上是无法执行Cookie身份验证:SignInAsync和AuthenticateAsync不成功的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>