[英]How can I use the Google OAuth2 ID token with node.js / passport.js to verify if the user is valid and authenticated?
On my front end, I'm using vue.js
(not that that matters) and with the Google OAuth flow, I get back an id_token
from: 在前端,我正在使用
vue.js
( vue.js
),并通过Google OAuth流,从以下位置获取了id_token
:
let googleAuthIdToken = await this.auth2.currentUser
.get()
.getAuthResponse().id_token;
I want to then pass that token to my node.js server (Express / Passport) to verify that the user is allowed to login. 然后,我想将该令牌传递给我的node.js服务器(Express / Passport),以验证是否允许用户登录。
I want to use passport and send back a JWT to the front end in my response. 我想使用护照,并在回信中将JWT发送回前端。
Can someone please guide me as to how to accomplish this? 有人可以指导我如何做到这一点吗?
It is easier to make use of a node module called googleapis
, After installation, import the module. 使用名为
googleapis
的节点模块会更容易,安装后,导入该模块。
import { google } from 'googleapis';
Then you need to create an OAuthClient by specifying the CLIENT_ID, CLIENT_SECRET, REDIRECT_URL
. 然后,您需要通过指定
CLIENT_ID, CLIENT_SECRET, REDIRECT_URL
来创建OAuthClient。
const oauth2Client = new google.auth.OAuth2(
CLIENT_ID,
CLIENT_SECRET,
REDIRECT_URL,
);
Then you can get the token from google by using the oauth2Client
. 然后,您可以使用
oauth2Client
从Google获得令牌。
const {tokens} = await oauth2Client.getToken(code);
oauth2Client.setCredentials(tokens);
Inorder to obtain the neccessary user information to store in your own database, You need to call this method. 为了获取必要的用户信息以存储在您自己的数据库中,您需要调用此方法。
const plus = google.plus({ version: 'v1', oauth2Client });
const me = await plus.people.get({ userId: 'me' });
me
will contain the user information that you are looking for, once you obtain the user information you can then store it using passport js. me
将包含您要查找的用户信息,一旦获得用户信息,便可以使用护照js进行存储。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.