例外:oauth 状态丢失或无效。 (ASP.NET Core 外部标识符 OAuth)

Posted

技术标签:

【中文标题】例外:oauth 状态丢失或无效。 (ASP.NET Core 外部标识符 OAuth)【英文标题】:Exception: The oauth state was missing or invalid. (ASP.NET Core external identifier OAuth) 【发布时间】:2021-04-26 11:59:26 【问题描述】:

我正在尝试在 Asp.Net Core (https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers) 中实现外部 OAuth。我的应用程序(GitLab)有回调 URL https://myhost.com/signin-gitlab(中间件默认使用)。

如果我运行下面的代码,我会收到“异常:oauth 状态丢失或无效”。但是,如果我从 Startup.cs 中删除“options.UserInformationEndpoint”,那么我会使用代码和状态参数重定向到 myhost.com/signin-gitlab,中间件应该用它们交换访问令牌。我的问题是,为什么我的状态参数会损坏(使用 UserInformationEndpoint)?为什么我没有获得访问令牌?我在这里错过了什么?

我的创业班:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using AspNet.Security.OAuth.GitLab;
using System.Net.Http;
using System.Net.Http.Headers;

namespace MyApp

    public class Startup
    
        private readonly IConfiguration _cfg;

        public Startup(IConfiguration configuration) => _cfg = configuration;

        public void ConfigureServices(IServiceCollection services)
        
            services.AddRouting();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                    .AddCookie()
                    .AddGitLab("Gitlab", options => 
                        options.ClientId = "...";
                        options.ClientSecret = "...";

                        options.AuthorizationEndpoint = "https://mygitlabserver.com/oauth/authorize";
                        options.TokenEndpoint = "https://mygitlabserver.com/oauth/token";
                        options.Scope.Clear();
                        options.Scope.Add("api");
                        options.SaveTokens = true;

                        options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                        options.UserInformationEndpoint = "https://mygitlabserver.com/api/v4/user"; 
                    );

            services.AddMvc();

        

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        
            app.UseDeveloperExceptionPage();
            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();
               
            app.UseEndpoints(endpoints =>
            
                endpoints.MapDefaultControllerRoute();
            );
        
    

我的控制器:

using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;

namespace MyApp.Controllers

    public class HomeController : Controller
    
        [HttpGet("/")]
        public IActionResult Index()
        
            return View();
        

        [HttpGet("/login")]
        public IActionResult LogIn()
        
            // Instruct the middleware corresponding to the requested external identity
            // provider to redirect the user agent to its own authorization endpoint.
            // Note: the authenticationScheme parameter must match the value configured in Startup.cs
            return Challenge(new AuthenticationProperties  RedirectUri = "https://myhost.com/signin-gitlab" , "Gitlab");
           
    

【问题讨论】:

【参考方案1】:

首先,ASP.NET 外部身份提供者/社交登录可以使用或不使用身份框架来完成。如果没有身份,它应该像这样设置(https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/social-without-identity?view=aspnetcore-5.0):

public void ConfigureServices(IServiceCollection services)

    // requires
    // using Microsoft.AspNetCore.Authentication.Cookies;
    // using Microsoft.AspNetCore.Authentication.Google;
    // NuGet package Microsoft.AspNetCore.Authentication.Google
    services
        .AddAuthentication(options =>
        
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
        )
        .AddCookie()
        .AddGoogle(options =>
        
            options.ClientId = Configuration["Authentication:Google:ClientId"];
            options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
        );

    services.AddRazorPages();

第二个问题是在控制器内部:

return Challenge(new AuthenticationProperties  RedirectUri = "https://myhost.com/signin-gitlab" , "Gitlab");

正如 aspnet-contrib 团队 (https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers/blob/dev/samples/Mvc.Client/Controllers/AuthenticationController.cs) 在 MVC 示例应用程序中一样,它实际上应该是:

return Challenge(new AuthenticationProperties  RedirectUri = "/" , "Gitlab");

用户实际上是经过身份验证的,问题是他们随后被重定向到 OAuth 中间件的内部路由 /signin-gitlab 没有状态或代码参数,而不是主路由/索引操作,因此出现错误。

换句话说,我搞混了:

RedirectUri(用户在身份验证后被重定向) 回调 URL(OAuth 应用程序将带有状态和代码的用户重定向到 OAuth 中间件内部路由,默认为 /signin-gitlab、/signin-google、/signin-facebook,但也可以使用选项覆盖.CallbackPath)。

也许我的困惑是因为回调 url 在 GitLab 文档 (https://docs.gitlab.com/ee/api/oauth2.html) 中称为 REDIRECT_URI。

感谢 Nan Yu (https://***.com/a/61452853/2768479) 和 Tratcher (https://github.com/dotnet/aspnetcore/issues/22125, https://github.com/aspnet/Security/issues/1756) 的精彩帖子。

【讨论】:

以上是关于例外:oauth 状态丢失或无效。 (ASP.NET Core 外部标识符 OAuth)的主要内容,如果未能解决你的问题,请参考以下文章

获取新的访问令牌以处理过期的访问令牌时,grant_type 参数无效或参数丢失

无法加载 http://localhost:9999/auth-service/oauth/token:预检响应具有无效的 HTTP 状态代码 401

处理 OAuth 2.0 身份验证 - 在 ASP.NET MVC 应用程序中获取令牌重定向令牌响应

为啥我在尝试实施 Gmail Oauth 时将“SameSite”属性设置为“无”或无效值,而没有“安全”错误

错误 ITMS-9000:“签名丢失或无效。

请求具有无效的身份验证凭据。预期的 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据 automl