ASP.NET Core Web API + 对预检请求的 Angular 响应未通过访问控制检查:预检请求不允许重定向

Roo*_*mey 5 c# google-api cors google-oauth asp.net-core

我在 ASP.NET Core Web API 上有一个后端,在 Angular 9 上有一个前端。我正在实施谷歌身份验证。在邮递员中它工作正常,但是在我的 angular 应用程序中,当我尝试通过 google 进行授权时,出现错误:

Access to XMLHttpRequest at 'https://accounts.google.com/o/oauth2/v2/... 
(redirected from 'https://localhost:44340/api/auth/googlelogin')
from origin 'http://localhost:4200' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check:
Redirect is not allowed for a preflight request.
Run Code Online (Sandbox Code Playgroud)

后端的 CORS 配置:

            services.AddCors(options =>
            {
                options.AddPolicy("MyPolicy",
                      builder =>
                      {
                          builder
                          .WithOrigins(Configuration["ApplicationSettings:Client_URL"].ToString())
                          .AllowAnyOrigin()
                          .AllowAnyHeader()
                          .AllowAnyMethod();
                      });
            });
Run Code Online (Sandbox Code Playgroud)
            app.UseCors("MyPolicy");

Run Code Online (Sandbox Code Playgroud)

我的服务中的方法

        public ChallengeResult LoginViaGoogle()
        {
            var provider = "Google";
            var redirectUrl = "/api/auth/ExternalLoginCallBack";
            var properties = Database.SignInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
            return new ChallengeResult(provider, properties);
        }
Run Code Online (Sandbox Code Playgroud)

我的控制器中的方法

        [HttpGet("GoogleLogin")]
        public IActionResult GoogleLogin()
        {
            ChallengeResult result;
            try
            {
                result = _authService.LoginViaGoogle();
            }
            catch(Exception ex)
            {
                throw ex;
            }
            return result;
        }
Run Code Online (Sandbox Code Playgroud)

我在 Angular 中的方法:

  googleLogin(){
    const httpOptions = {
      headers: new HttpHeaders({
        "Access-Control-Allow-Origin": "*"
      })
    };
    return this.http.get("https://localhost:44340/api/auth/googlelogin", httpOptions);
  }
Run Code Online (Sandbox Code Playgroud)

我从这个网站上尝试了很多解决方案,但没有一个帮助。

我认为问题可能是我在google oauth中错误地注册了URL。 在此处输入图片说明

Ser*_*lis 2

问题是您在此 get 请求上返回重定向,这在使用 CORS 时是不允许的

如果您遇到此类问题,我绝对建议您查看MDN文档,它们非常有用且接近完整。

要解决此问题,您可以返回具有正确身份验证 URL 的有效负载,并使用前端代码遵循该负载。

我不太了解角度,但我想它看起来像这样:

googleLogin(){
  // This header options was not doing anything, the request cannot tell the server how to do CORS.
  const authUrl = this.http.get("https://localhost:44340/api/auth/googlelogin");
  return this.http.get(authUrl);
}
Run Code Online (Sandbox Code Playgroud)