重定向后Golang与Gin中的CORS错误

whhtz7ly  于 2023-08-01  发布在  Go
关注(0)|答案(1)|浏览(183)

我试图在我的Web服务器上实现Google Oauth2,它是用Go with gin编写的。我添加了两个新端点,分别是/google/sign-in和/google/callback。第一个接收到请求并重定向到google auth url,第二个在用户选择了一个有效的google帐户后调用,验证令牌并创建一个jwt用于我的内部身份验证。
一切都很好,除了它不是,因为当我调用第一个API路由时,我得到一个CORS错误:

Access to XMLHttpRequest at 'https://accounts.google.com/o/oauth2/auth?access_type=online&client_id=xxxxxxxxxxxxx-337ka657nqlo84q6697vv2efsc2vqvm0.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fgoogle%2Fcallback&response_type=code&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&state=7e5f86fe352b4563c7d1bd62408285dcbc44e3e26a4f142bbae915279008ece6' (redirected from 'http://localhost:3000/google/sign-in') from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

字符串
这是我的Golang代码:

r := gin.Default()

r.Use(cors.New(cors.Config{
    AllowOrigins: []string{"*"},
    AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"},
    AllowHeaders: []string{"Origin", "Authorization", "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "baggage", "sentry-trace", "X-User-Lang"},
}))

r.POST("/google/sign-in", authController.RedirectToGoogleAuthPage)
r.GET("/google/callback", authController.GoogleSignIn)


授权控制器

func (a AuthController) RedirectToGoogleAuthPage(c *gin.Context) {
  googleAuthConfig := utils.GetGoogleAuthConfig()
  state := utils.GenerateRandomKey()
  url := googleAuthConfig.AuthCodeURL(state, oauth2.AccessTypeOnline)
  session := sessions.Default(c)
  session.Set(state, state)
  err := session.Save()
  if err != nil {
      c.JSON(http.StatusInternalServerError, a.Errors.InternalError(err.Error()))
      return
  }
  c.Header("X-Auth-State", state)
  c.Redirect(http.StatusTemporaryRedirect, url)
}


在googleAuthConfig中有一个回调URL,它是http://localhost:3000/google/callback,它被添加到谷歌云oauth凭据中。
我知道我错过了回调请求中的Access-Control-Allow-Origin,但是我如何添加那个头呢?

kmpatx3s

kmpatx3s1#

根据问题中的信息,您正在访问位于http://localhost:4200的页面,并向http://localhost:3000/google/sign-in发送 AJAX 请求,该请求将重定向到https://accounts.google.com/o/oauth2/auth。这样不行您需要一个页面重定向到https://accounts.google.com/o/oauth2/auth
有两种方法可以解决此问题:

  • 修改客户端代码,用表单请求(使用<form action="http://localhost:3000/google/sign-in" method="POST">元素)替换 AJAX 请求。在这种情况下,RedirectToGoogleAuthPage中的c.JSON应该替换为其他内容。
  • 或者修改RedirectToGoogleAuthPage以使用包含要重定向到的目标URL的JSON内容进行响应,并修改客户端代码以将页面重定向到目标URL(使用window.location = targetURL)。

看起来第二个选择需要对代码进行更少的更改。

相关问题