【发布时间】:2019-11-26 22:10:00
【问题描述】:
我一直在使用 dotNet core 2.2 设置 WebApi,我想使用 GitHub 的 OAuth 授权我的用户。
我查找并设置我的 API 以将 Swashbuckle.AspNetCore.Swagger 用于其 Swagger 文档和 UI,并使用 AspNetCore 自己的身份验证来设置 OAuth。通过我的端点auth/signin|out 登录或注销时,一切都像魅力一样,但是每当我尝试通过 SwaggerUI 的授权按钮授权我的客户端时,我都会收到错误消息:
Exception: The oauth state was missing or invalid.
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)
Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
以下是我用来设置 API 相关内容的一些代码:
// Setting up Authentication
services
.AddAuthentication(opt =>
{
opt.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
opt.DefaultChallengeScheme = "GitHub";
})
.AddCookie()
.AddGitHub("GitHub", opt =>
{
opt.ClientId = GitHubSettings.ClientId;
opt.ClientSecret = GitHubSettings.ClientSecret;
opt.CallbackPath = new PathString(GitHubSettings.CallbackPath);
opt.SaveTokens = true;
});
// Setting up SwaggerDoc Generation
services.AddSwaggerGen(c =>
{
c.AddSecurityDefinition("GitHub", new OAuth2Scheme
{
Type = "oauth2",
Flow = "accessCode",
AuthorizationUrl = "https://github.com/login/oauth/authorize",
TokenUrl = "https://github.com/login/oauth/access_token"
});
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "NetCore Playground API",
Description = "API para testes com .NET Core 2.2",
Contact = new Contact { Name = "HocusPocus", Url = @"https://google.com", Email = "not.my.email@gmail.com" }
});
});
// Using SwaggerUI
app.UseSwagger();
app.UseSwaggerUI(opt =>
{
opt.DisplayRequestDuration();
opt.RoutePrefix = string.Empty;
opt.SwaggerEndpoint("swagger/v1/swagger.json", "Playground API V1");
opt.OAuth2RedirectUrl("https://localhost:5001/auth/callback");
opt.OAuthClientId(GitHubSettings.ClientId);
opt.OAuthClientSecret(GitHubSettings.ClientSecret);
opt.OAuthAppName("dotNet Core Playground");
});
app.UseAuthentication();
这是一个开源学习项目,所以源代码在 GitHub 上可用: https://github.com/rodolphocastro/ARDC.NetCore.Playground/tree/feature/stackoverflow-57086626/src/ARDC.NetCore.Playground
编辑:我已根据https://www.jerriepelser.com/blog/authenticate-oauth-aspnet-core-2/ 对代码进行了一些更改,但使用 SwaggerUI 的授权按钮仍然没有成功。
【问题讨论】:
-
如果有人感兴趣,请在 Swashbuckle 的 GitHub 上创建一个关于此的问题:github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1199
标签: c# asp.net-core oauth-2.0 swagger-ui swashbuckle