后端到前端回调URL的Oauth2方法

问题描述 投票:0回答:1

我有一个前端 javascript (svelte) 和一个 go 后端 API。前端调用go后端URL从github生成OAuth2令牌。后端使用精心设计的 url 作为响应进行回复)

https://github.com/login/oauth/authorize?access_type=online&client_id=xxxxxxx&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fapi%2Fv1%2Fcallback&response_type=code&scope=user%3Aemail&state=state

此网址由用户使用

location.assign(authUrl);

打开

实际完整代码:

const authUrl = await fetch('http://localhost:8080/api/v1/authurl', {
  method: 'GET',
  headers: {
                'Content-Type': 'application/json'
            }
        }).then(res => res.json()).then(data => data.url);

// Redirect the user to the GitHub authorization URL
location.assign(authUrl);

后端处理回调,然后执行交换并接收有效的 OAuth2 令牌(耶!)

从这里我需要通知客户交易已完成,但我不确定如何做到这一点(这是我坦白承认我在前端很糟糕并且没有太多经验的地方)。我决定向前端返回一个 httponly 会话 cookie,并将 GitHub OAuth2 令牌安全地存储在后端,但是我应该如何将此令牌获取到前端以便它可以存储它?

请记住,没有从客户端获取,后端 API 通过回调启动。

我能做的一件事就是重定向;

cookie := &http.Cookie{ Name: "token", Value: jwt_token, MaxAge: 3600, Path: "/", Domain: "localhost", Secure: false, HttpOnly: true, } c.SetCookie(cookie.Name, cookie.Value, cookie.MaxAge, cookie.Path, cookie.Domain, cookie.Secure, cookie.HttpOnly) c.Redirect(http.StatusFound, "http://localhost:3000/dashboard/")
http://localhost:3000/dashboard/ 将是前端的登陆页面

但是要做到这一点,我需要从后端 POST 到前端的监听 API,这感觉不对吗?这是错误的方法吗?我应该使用更优化的方法吗?

node.js go oauth-2.0 sveltekit
1个回答
0
投票
正确的方法是在前端设置回调 URL。然后,此回调将使用从 OAuth 提供程序接收到的信息向后端发出第二个请求以进行身份验证,然后应生成 JWT 令牌(或您用于身份验证的任何内容)。

© www.soinside.com 2019 - 2024. All rights reserved.