Google APi + Passport + React:身份验证流程

xge*_*k95 5 node.js express google-oauth reactjs passport.js

我使用护照通过 Google API 进行身份验证,我通过 URL 向客户端(React 应用程序)发送令牌,并将其保存在 localStorage 中。

我想使用该令牌:对于每个 API 调用(获取、发布、放置),我想将该令牌发送到服务器,但我不知道如何在服务器端验证该令牌。

护照策略:

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);
Run Code Online (Sandbox Code Playgroud)

验证 :

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);
});
Run Code Online (Sandbox Code Playgroud)

Express 中的 API(包含 CRUD 方法):

app.use('/api', movieRouter)
Run Code Online (Sandbox Code Playgroud)

在反应端:获取令牌

  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("/");
    }
  }
Run Code Online (Sandbox Code Playgroud)

进行 API 调用:

import axios from 'axios'

const api = axios.create({
    baseURL: 'http://localhost:3000/api',
})

export const insertMovie = payload => api.post(`/movie`, payload)
Run Code Online (Sandbox Code Playgroud)

我只需要在每次调用中发送令牌并在服务器端检查它。

谢谢

小智 0

您最有可能想在标头中设置令牌,请尝试将 axios 客户端更改为类似的内容

const api = axios.create({
  baseURL: 'http://localhost:3000/api',
  headers: {
    Authorization: `Bearer ${your_token_here}`
  }
})
Run Code Online (Sandbox Code Playgroud)

我不能 100% 确定这是否是护照所期望的正确标题形式,但这是您需要做的一般想法。