【问题标题】:Google Auth token from Chrome Extension with PassportJS returns 401 Unauthorized来自带有 PassportJS 的 Chrome 扩展的 Google Auth 令牌返回 401 Unauthorized
【发布时间】:2016-06-07 14:00:23
【问题描述】:

我正在尝试设置一个 Chrome 扩展程序,它使用 chrome.identity.getAuthToken 来获取登录用户的身份验证令牌,然后使用它通过 Passport 和 passport-google-token 策略向 Express 服务器进行身份验证。

getAuthToken 正在给我令牌,但是当它发送到我的服务器时,我收到了 401 unauthorized 错误。

我对 Passport 和基于令牌的授权很陌生,所以我不确定我是否犯了错误或误解了它的工作原理。

我的 chrome 扩展是这样做的:

chrome.identity.getAuthToken({"interactive": true}, function(token){
  var url = "http://localhost:30000/auth/chrome";
  var x = new XMLHttpRequest();
  x.open("GET", url);
  x.setRequestHeader('Authorization', "Bearer " + token);
  x.send();
});

并且令牌被正确传递到我的回调中。

我这样设置我的 Express 服务器和 Passport 策略:

import * as express from "express";
import * as passport from "passport";
const GoogleTokenStrategy = require("passport-google-token").Strategy;

// set up Express and Passport...

passport.use(new GoogleTokenStrategy({
  clientID: --client id--,
  clientSecret: --client secret--
}, (accessToken, refreshToken, profile, done) => {
  return done(null, profile);
}));

app.get('/auth/chrome', passport.authenticate("google-token"), (req, res) => {
  res.send(req.user);
});

客户端 ID 和密钥来自我在 Google API 管理器中设置的凭据:

如果有人能指出我还需要做什么或我做错了什么,将不胜感激。

【问题讨论】:

  • 你在哪里指定重定向网址?

标签: express google-chrome-extension passport.js google-authentication


【解决方案1】:

这对我来说失败有两个原因。

当我单步执行一些passport-google-token 代码时,我意识到如果req.body 未定义,它将失败。我通过添加 body-parser 中间件解决了这个问题。

主要问题是我在标头中发送访问令牌的方式。我从Google sample apps 之一复制了x.setRequestHeader('Authorization', 'Bearer ' + token);,但它实际上需要发送为:

x.setRequestHeader('Access_token', token);

或在查询字符串中为:

var url = "http://localhost:30000/auth/chrome?access_token=" + token;

【讨论】:

  • 注意事项:通过查询参数传递令牌是不安全的。
猜你喜欢
  • 2020-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-17
  • 2017-08-27
  • 2014-10-02
  • 2016-06-26
  • 2021-05-26
相关资源
最近更新 更多