![image.png](https://static.studygolang.com/220323/963a180bdb3547ef42d0f56e5daf250f.png)
```go
func loginOidc(c *gin.Context) {
_, cfg := oidcx.NewProviderAndConfig()
state, err := oidcx.RandString(16)
if err != nil {
ginx.NewRender(c).Message("InternalServerError")
return
}
c.Redirect(http.StatusFound, cfg.AuthCodeURL(state))
}
func callbackOidc(c *gin.Context) {
provider, cfg := oidcx.NewProviderAndConfig()
// 获取token
oauth2Token, err := cfg.Exchange(c, c.Request.URL.Query().Get("code"))
if err != nil {
ginx.NewRender(c).Message("Failed to exchange token: " + err.Error())
return
}
// 获取userInfo
userInfo, err := provider.UserInfo(c, oauth2.StaticTokenSource(oauth2Token))
if err != nil {
ginx.NewRender(c).Message("Failed to get userinfo: " + err.Error())
return
}
// 获取的的user信息入库
user, err := models.OidcLogin(userInfo)
if err != nil {
ginx.NewRender(c).Message("Failed to find user: " + err.Error())
return
}
userIdentity := fmt.Sprintf("%d-%s", user.Id, user.Username)
ts, err := createTokens(config.C.JWTAuth.SigningKey, userIdentity)
ginx.Dangerous(err)
ginx.Dangerous(createAuth(c.Request.Context(), userIdentity, ts))
ginx.NewRender(c).Data(gin.H{
"user": user,
"access_token": ts.AccessToken,
"refresh_token": ts.RefreshToken,
}, nil)
}
```
![image.png](https://static.studygolang.com/220323/79cd308cca8c60efe012cfd0ce8dbfc4.png)
OIDC登录这里为啥我Get请求访问http://0.0.0.0:18000/api/auth/login 可以正常走登录流程,前端按钮调这个接口就跨域?
有疑问加站长微信联系(非本文作者)