我创建了一个具有单独后端和前端的 MERN 应用程序。我添加了对使用passport-google-oauth20
npm 包的 Google Oauth2 登录的支持。
所以我在后端暴露了一个端点,如下所示:
class AccountAPIs {
constructor() { }
redirectToSuccess(req, res) {
const accountServiceInst = AccountService.getInst();
let account = req.session.passport.user;
let filePath = path.join(__dirname + '../../../public/views/loginSuccess.html');
let jwt = accountServiceInst.generateJWT(account);
// how do I send this jwt to ui application
res.sendFile(filePath);
}
loadMappings() {
return {
'/api/auth': {
'/google': {
get: {
callbacks: [
passport.authenticate('google', { scope: ['profile', 'email'] })
]
},
'/callback': {
get: {
callbacks: [
passport.authenticate('google', { failureRedirect: '/api/auth/google/failed' }),
this.redirectToSuccess
]
}
},
'/success': {
get: {
callbacks: [this.successfulLogin]
}
}
}
}
};
}
}
以下是护照设置供参考:
let verifyCallback = (accessToken, refreshToken, profile, done) => {
const accountServiceInst = AccountService.getInst();
return accountServiceInst.findOrCreate(profile)
.then(account => {
return done(null, account);
})
.catch(err => {
return done(err);
});
};
let googleStrategyInst = new GoogleStrategy({
clientID: serverConfig.auth.google.clientId,
clientSecret: serverConfig.auth.google.clientSecret,
callbackURL: 'http://localhost/api/auth/google/callback'
}, verifyCallback);
passport.use(googleStrategyInst);
在 UI 应用程序中,单击按钮时,我将打开一个新窗口,该窗口将打开“/api/auth/google”后端 API。使用 google 帐户进行身份验证后,窗口将重定向到“/api/auth/google/callback”后端 API,我可以在其中生成 JWT。我不确定如何将此 JWT 传输到前端应用程序,因为它是在单独的窗口中打开的。
我知道这res.cookie('jwt', jwt)
是一种方法。请在此处建议最佳实践..