Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Authorizing with GitHub OAuth2 returns "The oauth state was missing or invalid" #1199

Closed
rodolphocastro opened this issue Jul 19, 2019 · 4 comments

Comments

@rodolphocastro
Copy link

Env~ Details

  • OS: Windows 10 Enterprise
  • AspNetCore 2.2
  • Nuget Packages:
    • AspNet.Security.OAuth.GitHub
    • Microsoft.AspNetCore.App
    • Microsoft.AspNetCore.Diagnostics.HealthChecks
    • Microsoft.AspnetCore.Razor.Design
    • Microsoft.Extensions.Configuration
    • Microsoft.Extensions.Configuration.Json
    • Microsoft.NETCore.App (v2.2.0)
    • Swashbuckle.AspNetCore (v4.0.1)

Reproduction Steps

Create or use an existing GitHub OAuth App on GitHub's Developer Settings, then:

  1. On Startup.ConfigureServices setup the following:
    a. Add.Mvc
    b. Add.Authentication with AddCookie and (AddGitHub OR .AddOAuth)
    c. AddSwaggerGen with SwaggerDoc and AddSecurityDefinition for a OAuth2Scheme with Type = "oauth2", Flow = "accessCode", AuthorizationUrl = "https://github.com/login/oauth/authorize", TokenUrl = "https://github.com/login/oauth/access_token"
  2. On Startup.Configure use the following:
    a. UseCors
    b. UseDeveloperExceptionPage
    c. UseHttpsRedirection
    d. UseSwagger
    e. UseSwaggerUI with the following parameters:
opt.DisplayRequestDuration();
opt.RoutePrefix = string.Empty;
opt.SwaggerEndpoint("swagger/v1/swagger.json", "Playground API V1");
opt.OAuth2RedirectUrl("https://localhost:5001/auth/callback");
opt.OAuthClientId("your clientId");
opt.OAuthClientSecret("your clientSecret");
opt.OAuthAppName("dotNet Core Playground");
  1. Run the API and attemp to signin using the Authorize button.

Some more information

I made a branch just to keep the exact version that gives out the exception, on this GitHub repo

I've tested out the other actions on the API and Signout via the auth/signin|out route works just fine, so I'm not sure if this is a bug with the Swashbuckle's Swagger or SwaggerUI, since both show up on the Stacktrace. (Altho I don't rule out it being a bug on my part too, but I've been trying to get it fixed for 3 days now and someone else's insight would be greatly appreciated!)

@rodolphocastro
Copy link
Author

rodolphocastro commented Jul 20, 2019

So I cloned the repo, checked out tag v4,0,1 and added my own project to the Solution, referencing Swashbuckle as a Project Dependency and managed to get some additional stacktrace information:

Exception: An error was encountered while handling the remote login.
Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler<TOptions>.HandleRequestAsync()
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) in SwaggerUIMiddleware.cs
-
            if (httpMethod == "GET" && Regex.IsMatch(path, $"/{_options.RoutePrefix}/?index.html"))
            {
                await RespondWithIndexHtml(httpContext.Response);
                return;
            }
            await _staticFileMiddleware.Invoke(httpContext);
        }
        private void RespondWithRedirect(HttpResponse response, string location)
        {
            response.StatusCode = 301;
            response.Headers["Location"] = location;
Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider) in SwaggerMiddleware.cs
-
        }
        public async Task Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
        {
            if (!RequestingSwaggerDocument(httpContext.Request, out string documentName))
            {
                await _next(httpContext);
                return;
            }
            var basePath = string.IsNullOrEmpty(httpContext.Request.PathBase)
                ? null
                : httpContext.Request.PathBase.ToString();

Addind a breakpoint to the method allowed me to see that there might be an InvalidOperationException regarding the Session.

image

@ivanpaulovich
Copy link

Hey @rodolphocastro,

I am facing the same issue.
Did you find a solution?

@rodolphocastro
Copy link
Author

Hey @ivanpaulovich, I haven't gotten around to working on this again, however I'll try to reproduce it on .net Core 3.1.

I think the issue might be related to using the AddCookie instead of AddJwtBearer

@rodolphocastro
Copy link
Author

rodolphocastro commented Mar 11, 2020

Hey @ivanpaulovich, I've made some progress into this.

Using .net core 3.1 and the latest versions of swashbuckle I've ran into a different issue, which is actually a problem on GitHub's CORS policy! Those were my steps:

  1. I changed my authenthication builder to use AddJwtBearer and configured GitHub's oauth endpoints as Token and Authorize URLs.
  2. I changed my Swagger Gen to use a AuthorizationCode Flow, as that seems better suited to GitHub's suggested flow
  3. Then, finally, I got into a CORS issue which seems to be on GitHub's end 😢 , according to similar issues within javascript projects. Check here, here and also here

So, in the end, this doesn't seem like an issue with Swashbuckle itself but a misconfiguration on my first attempt and GitHub's lack of CORS support on the token endpoint.

@domaindrivendev I don't think there's anything to be done about the CORS issue from Swashbuckle's side, mind if I close this issue?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants