我使用 Passport 通过 Google API 进行身份验证,我通过 URL 将 token 发送到客户端(React 应用程序),客户端将其保存在 localStorage 中。
我想使用该 token :在每次 API 调用(get、post、put)时,我都想将该 token 发送到服务器,但我不知道如何在服务器端验证该 token 。
Passport 策略:
app.use(passport.initialize()); // Used to initialize passport
app.use(passport.session()); // Used to persist login sessions
passport.use(new GoogleStrategy({
clientID: 'IDxxxxx',
clientSecret: 'SecreXXX',
callbackURL: 'http://localhost:3000/callback'
},
(accessToken, refreshToken, profile, done) => {
// Directory API here
var userData = {
name: profile.displayName,
token: accessToken
};
done(null, userData);
身份验证:
app.get('/auth/google', passport.authenticate('google', {
scope: ['profile'] // Used to specify the required data
}));
// The middleware receives the data from Google and runs the function on Strategy config
app.get('/callback', passport.authenticate('google'), (req, res) => {
var token = req.user.token;
res.redirect("http://localhost:8000?token=" + token);
});
express 中的 API(包含 CRUD 方法):
app.use('/api', movieRouter)
在 react 方面:获取 token
componentWillMount() {
var query = queryString.parse(this.props.location.search);
if (query.token) {
window.localStorage.setItem("jwt", query.token);
// appel a directory api (avec token) puis sauvergarder dans redux puis redirection vers liste demandes
this.props.history.push("/");
}
}
进行 API 调用:
import axios from 'axios'
const api = axios.create({
baseURL: 'http://localhost:3000/api',
})
export const insertMovie = payload => api.post(`/movie`, payload)
我只需要在每次调用时发送 token 并在服务器端检查它。
谢谢
最佳答案
你最有可能想在 header 中设置 token ,尝试将你的 axios 客户端更改为类似
const api = axios.create({
baseURL: 'http://localhost:3000/api',
headers: {
Authorization: `Bearer ${your_token_here}`
}
})
我不是 100% 确定这是否是 Passport 所期望的正确标题格式,但这是您需要做的一般想法。
关于node.js - 谷歌 API + Passport + react : Authentication flow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60283429/