NestJS - 回调未经授权

时间:2021-02-16 20:54:03

标签: javascript typescript api oauth-2.0

我想通过 Github 创建对我的应用的授权,并在成功授权后将我的 access_token 保存到当前登录到系统用户的数据库中,但我在 {{1 上的授权有问题}} 到我的 GET :(

在我的 vue.js 应用中点击按钮后:

callback

我已正确重定向到 github 身份验证页面。在我的 Github 应用程序的设置中,我将 <a href="https://github.com/login/oauth/authorize?client_id=SOME_CLIENT_ID&scope=repo/"> <b-button variant="danger" style="height:38px;" class="ml-1"> Connect </b-button> </a> 设置为我的函数(在 callback 服务器中)侦听的端点,这里是来自服务的控制器和函数:

控制器

nestjs

服务 在这两种方法中,首先我从回调的响应中得到一个 @Get('github-callback') @AuthRequired() async githubCallback( @Req() req: Request, @Res() res: Response, @CurrentUser() user: User): Promise<void> { return await this.authService.githubAuthAccessToken(req, res, user); } ,在第二个(引用第一个)中,我得到我的用户的数据并在数据库中更新用户 access_token

access_token

async githubAuthAccessToken(req: Request, res: Response, user: User): Promise<void> { console.log("user: " + user); let token; const body = { client_id: process.env.GITHUB_CLIENT_ID, client_secret: process.env.GITHUB_CLIENT_SECRET, code: req.query.code }; const opts = { headers: { accept: 'application/json' }}; const response = await axios.post(`https://github.com/login/oauth/access_token`, body, opts); token = response.data.access_token; console.log(response.data); await this.getGithubUserData(token, user); res.redirect('http://localhost:8080/github'); } async getGithubUserData(accessToken: string, user: User): Promise<void> { const response = await axios.get('https://api.github.com/user', { headers: { authorization : `token ${accessToken}`, 'X-OAuth-Scopes': 'repo, user', 'X-Accepted-OAuth-Scopes': 'repo, user' } }); await this.userService.updateGithubToken(accessToken, response.data.login, user); } 应用程序中单击我的按钮后,我重定向到 github 身份验证页面,在单击 vuejs 而不是重定向到 authorize 后,我的服务器返回我 {{1 }} :(

有人能告诉我为什么我在回电时 http://localhost:8080/github 不同意我的服务器吗? (我需要授权,因为我需要更新用户对象),有人可以帮我吗?感谢您的帮助!

0 个答案:

没有答案