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

2024年 2月 9日 96.4k 0

重定向后 golang 与 gin 中的 cors 错误

php小编小新在此为大家介绍重定向后Golang与Gin中的CORS错误。CORS(跨源资源共享)是一种用于在不同域之间进行安全数据传输的机制,然而,在使用Golang和Gin框架时,遇到CORS错误是常见的问题。本文将详细解释CORS错误的原因和解决方法,帮助开发者更好地理解和处理这个问题。无论您是初学者还是有经验的开发者,本文都能为您提供有用的指导和解决方案。让我们一起来探索Golang和Gin中的CORS错误吧!

问题内容

我正在尝试在用 go 和 gin 编写的网络服务器中实现 google oauth2。我添加了两个新端点,名为 /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,它已添加到 google cloud oauth 凭据中。

我知道我错过了回调请求中的 access-control-allow-origin,但如何添加该标头?

解决方法

根据问题中的信息,您正在访问http://localhost:4200页面,并向http://localhost:3000/google/sign-in发送AJAX请求,该请求将重定向到https://accounts.google.com/o/oauth2/auth。这行不通。您需要将页面重定向到 https://accounts.google.com/o/oauth2/auth

有两种选择可以解决此问题:

  • 修改客户端代码以将 AJAX 请求替换为表单请求(使用 元素)。在这种情况下,RedirectToGoogleAuthPage 中的 c.JSON 应替换为其他内容。

  • 或者修改 RedirectToGoogleAuthPage 以使用包含要重定向到的目标 URL 的 JSON 内容进行响应,并修改客户端代码以将页面重定向到目标 URL(使用 window.location = targetURL)。

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

以上就是重定向后 Golang 与 Gin 中的 CORS 错误的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论