node.js - 使用sails.js 实现passport-http-bearer token

标签 node.js express sails.js passport.js http-token-authentication

我正在尝试实现 Passport 的 passport-http-bearer 策略,但没有找到具有信息 Bearer realm="Users" 的用户。

我的 request 是一个 post 请求:

{'token':'simple_access_token',} 

有人知道为什么会出现这个错误吗?我也知道这里 req 应该是 httpsssl 而不是 http。我该怎么做?

我使用的代码是:

bearerPassportToken: function(req,res){
        passport.authenticate('bearer', function(err, user, info){
          if ((err) || (!user)) {
            if (err) return;
            if (!user)  
                console.log("info");//Info: Bearer realm="Users"
            res.redirect('/login');
            return;
          }
          req.logIn(user, function(err){
            if (err){
                res.redirect('/login');
            }
            //Need to write code for redirection
            ;
          });
        })(req, res);
    },

最佳答案

最近我们不得不使用不记名 token 来实现基于 Sails 的 API 的保护,这就是我们所做的(使用 0.9.x 测试):

1) 在 config/passport.js 中将 Passport 作为自定义中间件连接(也可以是 config/express.js,取决于您的喜好):

/**
 * Passport configuration
 */
var passport = require('passport');

module.exports.express = {
  customMiddleware: function(app)
  {
    app.use(passport.initialize());
    app.use(passport.session());
  }
};

2) 使用 config/policies.js 中的策略保护必要的 Controller /操作:

module.exports.policies = {
  // Default policy for all controllers and actions
  '*': 'authenticated'
};

3) 在api/policies/authenticated.js中创建检查承载的策略:

/**
 * Allow any authenticated user.
 */
var passport = require('passport');

module.exports = function (req, res, done) {
  passport.authenticate('bearer', {session: false}, function(err, user, info) {
    if (err) return done(err);
    if (user) return done();

    return res.send(403, {message: "You are not permitted to perform this action."});
  })(req, res);
};

4) 在 services/passport.js 中定义 Passport 的承载策略(或者您认为更适合您的特定应用程序的任何其他地方):

var passport = require('passport'),
  BearerStrategy = require('passport-http-bearer').Strategy;

/**
 * BearerStrategy
 *
 * This strategy is used to authenticate either users or clients based on an access token
 * (aka a bearer token).  If a user, they must have previously authorized a client
 * application, which is issued an access token to make requests on behalf of
 * the authorizing user.
 */
passport.use('bearer', new BearerStrategy(
  function(accessToken, done) {
    Tokens.findOne({token: accessToken}, function(err, token) {
      if (err) return done(err);
      if (!token) return done(null, false);
      if (token.userId != null) {
        Users.find(token.userId, function(err, user) {
          if (err) return done(err);
          if (!user) return done(null, false);
          // to keep this example simple, restricted scopes are not implemented,
          // and this is just for illustrative purposes
          var info = { scope: '*' }
          done(null, user, info);
        });
      }
      else {
        //The request came from a client only since userId is null
        //therefore the client is passed back instead of a user
        Clients.find({clientId: token.clientId}, function(err, client) {
          if (err) return done(err);
          if (!client) return done(null, false);
          // to keep this example simple, restricted scopes are not implemented,
          // and this is just for illustrative purposes
          var info = { scope: '*' }
          done(null, client, info);
        });
      }
    });
  }
));

这样,您就可以通过在 Authorization header 中使用您的承载来访问 API:Bearer 8j4s36...

在此示例中,使用单独的服务器来请求/发出 token ,但您也可以在同一个应用程序中执行此操作(然后您必须仅将策略应用于选定的 Controller )。

关于node.js - 使用sails.js 实现passport-http-bearer token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21447155/

相关文章:

javascript - 输入 addEventListener 发生更改时未触发

node.js - azure 的阿尔戈利亚

node.js - 如何使用 Waterline Adapter for Mongo 在 Sails.js 中使用搜索修饰符 "OR"

node.js - 在WebStorm中使用supertest产生 'Argument type is not assignable to parameter type'和 'Unresolved function or method'

javascript - mongoose findOneAndUpdate 仅附加对象

javascript - 我收到一个错误, 'cant set headers after they are sent',无论在 node.js 上发生什么,电子邮件上的错误消息都会不断出现

node.js - 将函数传递给 Router-Functions 模块

node.js - Sequelize 数据库迁移问题

node.js - 如何在 sails.js 和水线中执行嵌套连接?

node.js - 将 Elasticsearch 与 PostgreSQL 集成,同时将 Sails.js 与 Waterline ORM 结合使用