【问题标题】:Implementing passport-http-bearer token with sails.js使用sails.js 实现passport-http-bearer 令牌
【发布时间】:2020-09-26 14:49:51
【问题描述】:

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

我的request 是发帖请求:

{'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);
    },

【问题讨论】:

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


    【解决方案1】:

    我们最近不得不使用不记名令牌来实现基于 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 中的策略保护必要的控制器/操作:

    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(或您认为更适合您的特定应用的任何其他位置)中定义护照的承载策略:

    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 标头中来访问 API:Bearer 8j4s36...

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

    【讨论】:

    • 非常感谢您知道passport.authenticate之后的最后一个(req res)参数是什么吗?
    • @VampireCoder 这些是当前的请求/响应。就像passport.authenticate 是一个函数,它返回一个被(req, res) 调用的函数。
    • 当我定义passport.use('bearer', new BearerStrategy... 时,function(accessToken, done) 永远不会被触发。知道为什么吗?
    • @CarlosRicardo 检查config/policies.jsapi/policies/authenticated.js 中的政策是否到位。
    • @bredikhin,抱歉,Bearer Authorization 标头不正确,错过了令牌之前的“Beared”:D 无论如何谢谢
    猜你喜欢
    • 2015-09-27
    • 1970-01-01
    • 2019-03-25
    • 2019-02-18
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    相关资源
    最近更新 更多