最近我开始使用 passport.js 和 oauth2 策略进行身份验证。起初,我使用会话,一切都很好,但我希望我的 API 是无状态的。我发现唯一可以帮助我的是不记名策略(passport-http-bearer)。我找不到任何一起使用这两种策略的好例子,所以我有点迷茫。也许我走错路了。让我解释一下我想要做什么。
假设我已经像这样配置了谷歌策略(passport-google-oauth2):
passport.use(
new GoogleStrategy(
{
clientID: <googleClientId>,
clientSecret: <googleClientSecret>,
callbackURL: `localhost:4000/auth/google/callback`,
scope: ["profile", "email"],
},
async function (_accessToken, _refreshToken, profile, done) { // this is the verify function
let user = <create new user>
return done(null, user);
}
)
);
此路由将用户重定向到他们将进行身份验证的谷歌:
app.get("/auth/google", passport.authenticate("google", { session: false }));
这个处理响应并将用户登录:
app.get(
"/google/callback",
passport.authenticate("google", {
session: false,
})
);
Google 策略发出一个不记名令牌,我想将该令牌返回给用户,以便我可以将其存储在客户端的 localStorage 中,并将其发送Authorization
到每个请求的标头中以对用户进行身份验证。我的第一个问题是如何以及在哪里?我可以访问策略的验证令牌中的令牌,但我不知道应该如何在响应正文中将其返回给用户。
我使用承载策略 (passport-http-bearer) 保护需要经过身份验证的用户的路由。我已经这样配置它:
passport.use(
new BearerStrategy(async function (token, done) { // this is the verify function
const user = await userManager.find({ oauthToken: token });
return done(null, user);
})
);
验证函数的第一个参数是Authorization
标头中的令牌。当用户使用谷歌注册时,我将颁发的令牌保存在数据库中(假设它是“1234”)。用户应在Authorization
标头中发送他们的令牌(如“Beader 1234”),如果令牌在数据库中,则他们已通过身份验证。
现在我可以使用承载策略保护路由:
app.get(
"/protected",
passport.authenticate("bearer", { session: false }),
(req: Request, res: Response) => {
res.send({ data: req.user });
}
);
将 google OAuth 令牌保存在数据库中好吗?我需要刷新它吗?您如何看待我正在尝试做的整个过程?我来自 jwt 世界,它对我来说是有线的。