如何使用ngResource将JWT令牌从Express转换为Angular?

时间:2016-07-11 14:57:56

标签: javascript angularjs node.js express jwt

我正在使用jwt令牌来验证用户注册。一个唯一的URL发送到用户的电子邮件,它重定向到身份验证页面,令牌在服务器端解码,我需要在客户端将此json数据发送到角度。如何使用token作为查询参数并使用ngResource检索它?

server.js

'use strict';

var express = require('express');
var app = express();
var router = express.Router();
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var jwt = require('jsonwebtoken');
var moment = require('moment');

var port = process.env.PORT || 5000;

app.use(express.static('./src/client/'));
app.use(express.static('./'));
app.use(express.static('./.tmp'));
app.use('/*', express.static('./src/client/index.html'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// sign with default (HMAC SHA256)
var expires = moment().add(12, 'hours').valueOf();
var token = jwt.sign({
    user: 'userdata',
    iat: Math.floor(Date.now() / 1000),
    expireIn: expires
}, 'thisismysecretstring');


// nodemailer sendMail function
app.post('/sendMail', function(req, res) {
  var transporter = nodemailer.createTransport('smtp://b204bf8f6ede15:71b5c1473852e2@mailtrap.io:2525');
  var data = req.body;
  var mailOptions = {
    from: 'noreply@ixfire.com',
    to: data.email,
    subject: 'Email sent by ' + data.displayName,
    html: '<p>Please click on url below to register</p><br><a href="http://localhost:3000/auth/?token='+token+'">CLICK HERE</a>'
  };
  transporter.sendMail(mailOptions, function(error, info) {
    if (error) {
      return console.log(error);
    }
    console.log('Message sent: ' + info.response);
  });
  res.json(token);
});

// decode token from url parameter
app.get('/auth', function(req, res) {
  var token = req.query.token;
      try {
          var decoded = jwt.verify(token, 'thisismysecretstring');
          if (decoded.exp <= Date.now()) {
            res.end('Access token has expired', 400);
          }
          res.json(decoded);
      } catch (err) {
          console.log(err);
          res.json(err);
      }
});

// router.use(function(req, res, next) {
//     var token = req.query.token;
//     try {
//         var decoded = jwt.verify(token, 'thisismysecretstring');
//         res.json(decoded);
//     } catch (err) {
//         console.log(err);
//         res.json(err);
//     }
// });
// app.use('/auth', router);

app.listen(port, function () {
  console.log('Express app listening on port: ' + port);
  console.log(__dirname);
});

token.js

(function() {
    'use strict';
    angular
        .module('xfire.token', ['ngResource'])
        .factory('Token', function($resource) {
            return $resource('auth/:token', {
                token: '@token'
            });
        });
})();

网址格式:

http://localhost:3000/auth/?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiZ2NmYWJyaSIsImlhdCI6MTQ2ODI0NDI1NCwiZXhwaXJlSW4iOjIxNjAwMDAwfQ.5rs1rlWMTTcap4idG-XOU-UiwbU0YzlnAYjm9Vwz-B0

1 个答案:

答案 0 :(得分:0)

我通常会在标题中发送它,通常我将其命名为x-auth-header

我不会使用,也不推荐任何人(除了玩游戏)使用ngResource,因为它是限制性的。

就个人而言,我使用restangular和请求/响应拦截器。

用于获取和解码令牌的响应拦截器,并请求拦截器使用"Bearer" + tokenString授权请求。