[英]How to use Google oAuth with Node.js backend and Angular frontend?
I am using Node.js on backend and creates a token for a user each time logins. 我在后端使用Node.js,并在每次登录时为用户创建令牌。
angularx-social-login
package makes it very easy to integrate Google OAuth with Angular but how to use it with API? angularx-social-login
软件包可以非常轻松地将Google OAuth与Angular集成在一起,但是如何将其与API结合使用? After successful login the Google returns user information with token. 成功登录后,Google会返回带有令牌的用户信息。 I was thinking to send this information to backend and login the user but for that I need to create a route which accepts email address and logins user.
我当时正在考虑将此信息发送给后端并登录用户,但是为此,我需要创建一个接受电子邮件地址并登录用户的路由。 And this will return JWT token which is not secure.
这将返回不安全的JWT令牌。 By secure I mean, anyone can access the route without Google Authentication and generate token.
所谓安全,是指任何人都可以在没有Google身份验证的情况下访问该路由并生成令牌。
I am looking for ideas how developers achieved this. 我正在寻找开发人员如何实现这一目标的想法。
I found google-auth-library
client package for Node.js managed by Google. 我找到了由Google管理的Node.js的
google-auth-library
客户端程序包。
Here is the follow: 以下是:
Node.js: Node.js的:
exports.googleLogin = function(req, res, next) {
//verify the token using google client
return googleClient
.verifyIdToken({
idToken: req.body.token,
audience: config.google.clientID
})
.then(login => {
//if verification is ok, google returns a jwt
var payload = login.getPayload();
var userid = payload['sub'];
//check if the jwt is issued for our client
var audience = payload.aud;
if (audience !== config.google.clientID) {
throw new Error(
'error while authenticating google user: audience mismatch: wanted [' +
config.google.clientID +
'] but was [' +
audience +
']'
);
}
//promise the creation of a user
return {
name: payload['name'], //profile name
pic: payload['picture'], //profile pic
id: payload['sub'], //google id
email_verified: payload['email_verified'],
email: payload['email']
};
})
.then(user => {
return res.status(200).json(user);
})
.catch(err => {
//throw an error if something gos wrong
throw new Error(
'error while authenticating google user: ' + JSON.stringify(err)
);
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.