oauth 状态丢失或无效。处理远程登录时遇到错误

yad*_*avr 5 c# asp.net-identity asp.net-core-mvc .net-core asp.net-core

我在不使用身份的情况下在 asp.net core 2.2 (mvc) 中实现外部登录时遇到问题。登录 Google 后,它会重定向回抛出异常的回调 URL,如下图所示。

异常:oauth 状态丢失或无效。

地点未知

异常:处理远程登录时遇到错误。

Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler.HandleRequestAsync()

有关我所做的更详细步骤,请查看此处

在此输入图像描述

以下是Startup.cs设置

 public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services
            .AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                options.Cookie.IsEssential = true;
            })
            .AddGoogle(options =>
            {
                options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.ClientId = Configuration["Authentication:Google:ClientId"];
                options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
                options.CallbackPath = "/externallogincallback";

            });

              services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }
Run Code Online (Sandbox Code Playgroud)

下面是我的 HomeController.cs 设置

 //Action to issue a challange to google login
    public IActionResult Google(string provider)
    {
        provider = "Google";
        //Issue a challenge to external login middleware to trigger sign in process
        //return new ChallengeResult(provider);

        var authenticationProperties = new AuthenticationProperties
        {
            RedirectUri = Url.Action("externallogincallback")
        };          

        return Challenge(authenticationProperties, "Google");
    }

    //Callback action to retrive signin user details
    [HttpGet("externallogincallback", Name = "externallogincallback")]
    [AllowAnonymous]
    public Task<IActionResult> externallogincallback(string returnUrl = null, string remoteError = null)
    {
        //Here we can retrieve the claims
        var result =  HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);

        return null;
    }
Run Code Online (Sandbox Code Playgroud)

在 Google 控制台设置授权重定向 URI

用于来自 Web 服务器的请求。这是用户在通过 Google 进行身份验证后被重定向到的应用程序中的路径。该路径将附加访问授权代码。必须有一个协议。不能包含 URL 片段或相对路径。不能是公共 IP 地址。

https://localhost:44379/externallogincallback 
Run Code Online (Sandbox Code Playgroud)

小智 1

从设置中删除回调路径

options.CallbackPath = "/externallogincallback";
Run Code Online (Sandbox Code Playgroud)