无法执行 Cookie 身份验证:SignInAsync 和 AuthenticateAsync 不成功 [英] Failing to perform Cookie Authentication: SignInAsync and AuthenticateAsync not successful

查看:22
本文介绍了无法执行 Cookie 身份验证:SignInAsync 和 AuthenticateAsync 不成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个非常简单的 Playground 服务器,以便我研究一些 ASP.NET Core 身份验证/授权概念.基本上是一个带有一个非常简单的控制器的网络应用程序,可以用 Postman 进行测试.

I am trying to build a very simple playground server for me to study some ASP.NET Core authentication/authorization concepts. Basically a web app with a single, very simple controller, to be tested with Postman.

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

I came up with a minified version of my code, consisting of a single login endpoint which would authenticate the user (no credentials required) using Cookie Authentication, like that:

[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() 的调用引发了以下异常:

The thing is that the call to HttpContext.SignInAsync() is firing the following exception:

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.AuthenticateAsync() 来替换 HttpContext.SignInAsync(),这样我就可以在尝试调用 之前对用户进行身份验证>SignInAsync() 再次:

Then I tried to replace HttpContext.SignInAsync() by a call to HttpContext.AuthenticateAsync(), so that I could authenticate the user before trying to call SignInAsync() again:

[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() 的调用只会记录以下(不是很有帮助的)信息:

But in that case the AuthenticateAsync() result always returns a failure (authResult.Succeeded = false), and later calls to HttpContext.SignInAsync() would fail with the same InvalidOperationException as before. By enabling "Trace"-level logging, the call to AuthenticateAsync() only logs the following (not very helpful) piece of information:

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 类:

My project targets the net5.0 framework, has no external/explicit dependencies, and here's the Startup class I'm using:

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 的最新版本.

I know I must be missing something really basic here. I'm also not sure if the documentation I am basing myself on is actually up-to-date for .NET 5.0.

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

Why is the cookie authentication (HttpContext.SignInAsync() / HttpContext.AuthenticateAsync()) failing?

推荐答案

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

This was a breaking change since Asp.Net Core 3.0 Preview 6. The documentation is here https://docs.microsoft.com/en-us/dotnet/core/compatibility/aspnetcore#identity-signinasync-throws-exception-for-unauthenticated-identity, but it does not contain the motivation of the breaking change.

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

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

In short, you need to specify auth scheme explicitly:

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

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

I had the same issue, and this change helped in my case.

这篇关于无法执行 Cookie 身份验证:SignInAsync 和 AuthenticateAsync 不成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆