【发布时间】:2020-06-02 14:58:16
【问题描述】:
我正在使用护照通过 Google API 进行身份验证,我正在通过 URL 向客户端(React 应用程序)发送一个令牌,客户端将其保存在 localStorage 中。
我想使用该令牌:对于每个 API 调用(get、post、put),我都想将该令牌发送到服务器,但我不知道如何在服务器端验证该令牌。
护照攻略:
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)
在反应方面:获取令牌
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)
我只需要在每次调用中发送令牌并在服务器端检查它。
谢谢
【问题讨论】:
标签: node.js reactjs express passport.js google-oauth