oauth 状态丢失或无效.处理远程登录时遇到错误 [英] The oauth state was missing or invalid. An error was encountered while handling the remote login

查看:56
本文介绍了oauth 状态丢失或无效.处理远程登录时遇到错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<块引用>

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

未知位置

<块引用>

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

Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler.HandleRequestAsync()

有关我所做的更详细的步骤,

下面是 Startup.cs 设置

 public void ConfigureServices(IServiceCollection services){services.Configure(options =>{//此 lambda 确定给定请求是否需要用户同意非必要 cookie.options.CheckConsentNeeded = 上下文 =>真的;options.MinimumSameSitePolicy = SameSiteMode.None;});服务.AddAuthentication(options =>{options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;}).AddCookie(options =>{options.Cookie.IsEssential = true;}).AddGoogle(选项=>{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);}

下面是我的 HomeController.cs 设置

//发起挑战谷歌登录的动作公共 IActionResult 谷歌(字符串提供者){提供者 = "谷歌";//向外部登录中间件发出质询以触发登录过程//返回新的ChallengeResult(provider);var authenticationProperties = 新的 AuthenticationProperties{RedirectUri = Url.Action("externallogincallback")};返回挑战(身份验证属性,谷歌");}//回调操作以检索登录用户详细信息[HttpGet("externallogincallback", Name = "externallogincallback")][允许匿名]公共任务externallogincallback(string returnUrl = null, string remoteError = null){//在这里我们可以检索声明var 结果 = HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);返回空;}

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

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

https://localhost:44379/externallogincallback

解决方案

有点混乱...options.CallbackPath 不是控制器/操作的路径.它必须与在您的第 3 方提供商(Google 或其他...)中注册的相同.默认情况下它是 signin-google,并且此回调处理程序由 IdentityServer 获取.回调externallogincallback 实际上是在ChallengeResult 中设置的.因此,如果您将 options.CallbackPathChallenge(RediretUrl) 设置为相同,这意味着它有两个具有相同名称/路由的处理程序,ASP.NET 将在错误.

I am facing issues while implementing external login in asp.net core 2.2 (mvc) without using identity. After signing in to google it redirect back to callback url that is throwing exception as attached in the image below.

Exception: The oauth state was missing or invalid.

Unknown location

Exception: An error was encountered while handling the remote login.

Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler.HandleRequestAsync()

For more detailed steps that I did, please check here

Below is Startup.cs settings

 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);
    }

Below is my HomeController.cs settings

 //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;
    }

In Google console setting Authorized redirect URIs

For use with requests from a web server. This is the path in your application that users are redirected to after they have authenticated with Google. The path will be appended with the authorization code for access. Must have a protocol. Cannot contain URL fragments or relative paths. Cannot be a public IP address.

https://localhost:44379/externallogincallback 

解决方案

It is a bit confusing... The options.CallbackPath is not the path to your Controller/Action. It just must be the same as registered in your 3rd party provider (Google, or so...). By default it is signin-google, and this callback handler is taken by IdentityServer. The callback externallogincallback is actually set in the ChallengeResult. So, if you set the options.CallbackPath and Challenge(RediretUrl) as the same, which means it has two hanlders with same name/route, ASP.NET will run in error.

这篇关于oauth 状态丢失或无效.处理远程登录时遇到错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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