如何在machinepack-jwt中捕获令牌是否过期

时间:2016-07-12 05:03:48

标签: angularjs node.js jwt access-token satellizer

我使用machinepack-jwt登录并在我的项目中注册。它成功地创建了令牌,一切都顺利接受到期部分。如果令牌过期,我不知道如何捕获。虽然我把过期时间,但它没有在那个时候到期。以下是我的登录后端代码,

var JWT = require('machinepack-jwt'),
    Passwords = require('machinepack-passwords'),
    GoogleAPIsOAuth2v2 = require('machinepack-googleapisoauth2v2'),
    Facebook = require('machinepack-facebook'),
    request = require('request');
   module.exports = {
    authenticate : function(req, res) {
    console.log("login");
          User.findOne({
            email: req.body.email
          }, function foundUser(err, user) {
            if (err) return res.negotiate(err);
            if (!user) return res.notFound();
    Passwords.checkPassword({
      passwordAttempt: req.body.password,
      encryptedPassword: user.password
    }).exec({
      error: function (err){
        console.log(err);
        return res.negotiate(err);
      },
      incorrect: function (){
        return res.notFound();
      },
      success: function (){
        JWT.encode({
          secret: '17ca644f4f3be572ec33711a40a5b8b4',
          payload: {
            id :  user.id,
            email:  user.email
          },
          algorithm: 'HS256',
          expires: 1
        }).exec({
          error: function (err){
            return err;
          },
          success: function (result){
            JWT.decode({
              secret: '17ca644f4f3be572ec33711a40a5b8b4',
              token : result,
              payload: {
                id :  user.id,
                email:  user.email
              },
              algorithm: 'HS256',
              expires: 1
            }).exec({
                error: function (err) {
                  res.send(err);
                },
                success: function(decodedToken){
                console.log(decodedToken);
                console.log(result);
                res.send({decodedToken,token : result, expires_in:1});
                }
            })
          }
        });
      }
    });
   });  
  }
}

以下是前端代码

angular.module('app')
  .factory('Auth', function($http, LocalService, AccessLevels ,$auth) {
    return {
      authorize: function(access) {
        if (access === AccessLevels.user) {
          return this.isAuthenticated();
        } else {
          return true;
        }
      },
      isAuthenticated: function() {
        return $auth.isAuthenticated();
      },
      login: function(credentials) {
        var login = $http.post('/auth/authenticate', credentials);
        login.success(function(result) {
        console.log(result);
          LocalService.set('satellizer_token', result.token );
          LocalService.set('user', result.user);
        });
        return login;
      },
      logout: function() {

        LocalService.unset('satellizer_token');
      }
    }
  })

我想抓住令牌是否过期以及是否过期想要重定向到登录页面。如果令牌过期,如何捕获?

2 个答案:

答案 0 :(得分:1)

您只需要使用当前日期检查已解码令牌的“exp”字段(到期时间)

function isExpired(exp){
    if (exp){
         return exp <= Date.now()/1000;
    } else {
         return true; //True if the token has not the expiration time field
    }
}

请注意,在您的示例中,您正在创建具有错误值的令牌。它必须是1970-01-01T00:00:00Z UT的秒数。请参阅RFC例如,1分钟的到期时间应为

exp = Date.now()/1000 + 60

答案 1 :(得分:0)

我在这里进行了宁静的服务方验证。

@JsonIgnoreProperties(ignoreUnknown =真)     接口Jwt {

        Instant getExp();

        String getAud();

        String getIss();

}   

像这样解码

Jwt jwt = null;

        try {

            jwt = objectReader.readValue(payload);

        } catch (IOException e) {

            throw new AuthenticationException(e);

        }

        // assert not expired
        if (jwt.getExp().isBefore(Instant.now())) {
            throw new AuthenticationException("auth token expired");
        }