我正在编写一个 Bolero (F# Blazor) 应用程序,并且在尝试挑战 GitHub 进行身份验证时遇到了一些关于 CORS 的问题。我以前用其他语言处理过类似的 CORS 错误消息,所以 CORS 对我来说并不是什么新鲜事。消息如下所示:
手动访问 URL 就可以了。
我已经阅读并应用了Microsoft的文档,以及其他具有相同或类似问题的 SO 帖子,例如。这个和这个。我创建了一个可以在GitHub 上找到的 repro 。这些是我为重现该问题所采取的步骤:
bolero-app
使用客户端和服务器创建 Bolero 模板。- 将身份验证更改为 GitHub OAuth2.0 ( AspNet.Security.OAuth.GitHub )
- 将 CORS 添加到
Startup.fs
. 在Configure
和ConfigureServices
。
运行应用程序时重现问题:
- 运行应用程序。我用
dotnet run -p src/ReproGithubOAuth.Server
. - 导航到
Download data
页面,在检查视图中打开控制台选项卡。 - 现在您可以单击
Sign in
按钮,应该会看到与上图相同的错误。
这就是我通过远程服务挑战 GitHub 的方式(参见 GitHub 中的代码):
signIn = fun () -> async {
let! res = Async.AwaitTask (ctx.HttpContext.ChallengeAsync "GitHub")
printfn $"res: {res}"
// Do some parsing of request
// Never gets this far, so returning whatever
return option.Some "myusername"
}
至于中的配置Startup.fs
(参见GitHub中的代码):
member this.ConfigureServices(services: IServiceCollection) =
let configureCors (builder: Infrastructure.CorsPolicyBuilder) =
builder.WithOrigins("http://localhost:5000")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
|> ignore
...
services.AddCors(fun options ->
options.AddPolicy("_allowSpecificOrigins", configureCors)
) |> ignore
services
.AddAuthorization()
.AddAuthentication(fun options ->
options.DefaultAuthenticateScheme <- CookieAuthenticationDefaults.AuthenticationScheme
options.DefaultSignInScheme <- CookieAuthenticationDefaults.AuthenticationScheme
options.DefaultChallengeScheme <- "GitHub"
)
.AddCookie(fun config ->
config.Cookie.SameSite <- SameSiteMode.None
config.Cookie.SecurePolicy <- CookieSecurePolicy.Always
)
.AddGitHub(fun options ->
options.ClientId <- "GitHub ClientId should be here";
options.ClientSecret <- "GitHub Client Secret should be here";
options.CallbackPath <- new PathString("/github-oauth");
options.AuthorizationEndpoint <- "https://github.com/login/oauth/authorize";
options.TokenEndpoint <- "https://github.com/login/oauth/access_token";
options.UserInformationEndpoint <- "https://api.github.com/user";
)
.Services
|> ignore
...
member this.Configure(app: IApplicationBuilder, env: IWebHostEnvironment) =
// Putting UseCors() after UseRouting() according to
// https://stackoverflow.com/a/65937838/12094643
app
.UseRouting()
.UseCors("_allowSpecificOrigins")
...
我试过一堆东西。我基本上已经尝试了到目前为止我读过的帖子中的所有修复,除了这篇文章说我应该使用await Http.GetJsonAsync<put here your return type>("/api/Login/Test");
,当从远程服务挑战 GitHub 时,这对我来说没有意义。
感谢我能得到的所有帮助<3