node.js - 谷歌 API + Passport + react : Authenticati

我使用 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/

相关文章:

ruby-on-rails - jbuilder 空数组删除键

python - 如何在 TensorFlow 2 中保存/加载模型的一部分?

typescript - TypeScript 中的非破坏性类型断言

android - 蓝牙扫描设备,频繁扫描后无法写入设备

django - 使用 DjangoFilterConnectionField 时有没有办法删除边和

azure-devops - 在 Azure Devops 中编写 EF6 迁移脚本

google-cloud-platform - Terraform 0.12 使用模板创建入口规则

css - 使用 attr() 更新 CSS 变量

java - 如何将不同大小的元素立即放在彼此之上?

html - 什么决定了 Firefox 中的滚动条是否有颜色?