簡體   English   中英

使用公司提供程序的 ASP.NET Core OAuth2 實現。 異常:oauth 狀態丟失或無效

[英]ASP.NET Core OAuth2 implementation using company provider. Exception: The oauth state was missing or invalid

我正在 ASP.NET Core(使用 .NET 5、Razor Pages)應用程序中實現 OAuth。 我遇到了一個錯誤,但我不太明白它在告訴我什么。

背景信息

我還沒有讓 OAuth 實現工作,所以即使我能夠讓它工作並解決這個錯誤,我也不相信我已經完美地設置了一切。 如果您對我可以改進的事情有任何建議,將不勝感激!

作為參考,我只嘗試使用 OAuth 幾天,並且我之前沒有任何身份驗證/授權經驗。 不過,我已經閱讀了一些指南,我會在我的帖子末尾提到這些。

我已經包含了有關以下內容的詳細信息:

  • 異常消息和堆棧跟蹤
  • 我的代碼
  • 我的想法
  • 參考

錯誤

Exception: The oauth state was missing or invalid.

堆棧跟蹤:

System.Exception: An error was encountered while handling the remote login.
 ---> System.Exception: The oauth state was missing or invalid.
   --- End of inner exception stack trace ---
   at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

我的代碼

  • 我不確定與我公司實施 OAuth 相關的信息有多私密,因此為了安全起見,我省略了可以識別公司的詳細信息。

Startup.cs ConfigureServices()

  • 僅包括與 OAuth2 相關的部分
public void ConfigureServices(IServiceCollection services)
{
    // OAuth2 Authentication 

    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = "MyCompanyAuthenticationScheme";
    }).AddCookie(options =>
    {
        options.Cookie.IsEssential = true;
    }).AddOAuth("MyCompanyAuthenticationScheme", options => 
    { 
        options.ClientId = Configuration["Company:ClientId"];
        options.ClientSecret = Configuration["Company:ClientSecret"];
        options.CallbackPath = new PathString("/Auth/Login");
        
        options.AuthorizationEndpoint = "...";
        options.TokenEndpoint = "...";
        options.UserInformationEndpoint = "...";

        // todo: are all three of these necessary?
        options.Scope.Add("loginAccountInfo");
        options.Scope.Add("contactInfo");
        options.Scope.Add("employeeInfo");

        options.SaveTokens = true;

        // todo: are the jsonKeys defined in the above Scopes? follow up when you have a better understanding of how these work, or if the MapJsonKey lines are even necessary
        options.ClaimActions.MapJsonKey(ClaimTypes.Name, "firstName");
        options.ClaimActions.MapJsonKey(ClaimTypes.Email, "emailAddress");
    });
}

Startup.cs 配置()

  • 再次只包含相關的代碼部分
  • 重要的是我確實包含了app.UseAuthentication()
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();

    app.UseAuthentication();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapControllers();
    });
}

驗證控制器:

[AllowAnonymous]
[Route("[controller]/[action]")]
public class AuthController : Controller
{
    [HttpGet]
    public IActionResult Login(string returnUrl = "/")
    {
        if(!User.Identity.IsAuthenticated)
            return Challenge(new AuthenticationProperties() { RedirectUri = returnUrl});

        return Forbid();
    }
}

我認為這是與 OAuth 相關的所有代碼,但如果您認為我需要包含更多詳細信息,請告訴我!

我的想法

  • 我認為問題出在我在 Startup.cs ConfigureServices() 中定義的options.CallbackPath中,在 services.AddOAuth() 下。
    • 我已經看到一些帖子詳細說明我不需要設置這個變量,但在這些帖子中,他們似乎正在為具有 NuGet 包的提供者(例如 Google、GitHub、Facebook 等)實施 OAuth提前定義了哪些options.CallbackPath
    • 我還看到一些信息說options.CallbackPath由 OAuth 中間件在內部使用,並且它不對應於控制器操作(這意味着我不需要我的 Auth 控制器及其登錄操作)。 但是,如果我刪除定義options.CallbackPath的行,我會收到另一個錯誤,指出它未定義,這讓我相信這是非常必要的。

參考

options.CallbackPath = new PathString("/Auth/Login");

如果您有一個綁定到/Auth/Login的控制器操作,這應該是問題的根源。

options.CallbackPath的值不必匹配任何控制器操作。 它是中間件接收身份提供者答案的內部路由。 您可以簡單地將/callback指定為其值或與現有路由不匹配的任何其他值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM