简体   繁体   English

JWT刷新角度认证

[英]JWT Angular Authentication on Refresh

So I'm following the following Egghead.io guide: https://egghead.io/lessons/angularjs-finalizing-jwt-authentication-with-angularjs 因此,我正在遵循以下Egghead.io指南: https ://egghead.io/lessons/angularjs-finalizing-jwt-authentication-with-angularjs

With a twist, I am trying to incorporate a MongoDB to retrieve my users. 我正在尝试合并一个MongoDB来检索我的用户。 I have everything working so far, except the last part where he states that the /me route should just return req.user and it should be fine on refreshes. 到目前为止,我可以进行所有工作,除了最后一部分,他指出/ me路由应该只返回req.user,并且刷新后应该可以。 I don't get that. 我不明白 What I do get is blank user returned from my server. 我得到的是从服务器返回的空白用户。

My server code is setup like this: 我的服务器代码是这样设置的:

var jwtSecret = 'fjkdlsajfoew239053/3uk';

app.use(cors());
app.use(bodyParser.json());
app.use(expressJwt({ secret: jwtSecret }).unless({ path: [ '/login' ]}));
app.use(compression());
app.use(express.static(__dirname + '/client'));
app.get('/', function(req, res){
  res.render(__dirname + '/client/bundle.js');
});

app.get('/me', function (req, res) {
  res.send(req.user);
});

... setup for user schema and other boring stuff ...

  function authenticate(req, res, next) {
    var body = req.body;
    if (!body.username || !body.password) {
      res.status(400).end('Must provide username or password');
    }

    //do salting, hashing, etc here yo
    User.findOne({ username: body.username }, function(err, user){
      if (user === null || body.password !== user.password) {
        res.status(401).end('Username or password incorrect');
      }else{
        req.user = user;
        next();
      }
    });
  }

  // ROUTES
  app.post('/login', authenticate, function (req, res, next) {
    var token = jwt.sign({
      username: req.user.username
    }, jwtSecret);
    res.send({
      token: token,
      user: req.user
    });
  });

app.listen(process.env.PORT || 5000);

And my controller (Client-side) handling the basic authentication is: 我处理基本身份验证的控制器(客户端)是:

module.exports = function($scope, $state, $modal, UserFactory) {
  var vm = this;

  $scope.$state = $state;
  $scope.sign_in = false;

  $scope.open =  function () {
    var $modalInstance = $modal.open({
      templateUrl: 'suggestion-modal.html',
      controller: 'modalCtrl'
    });
  };

  // initialization
  UserFactory.getUser().then(function success(response) {
    vm.user = response.data;
  });

  function login(username, password) {
    UserFactory.login(username, password).then(function success(response) {
      vm.user = response.data.user;
    }, handleError);
  }

  function logout() {
    UserFactory.logout();
    vm.user = null;
  }

  function handleError(response) {
    alert('Error: ' + response.data);
  }

  vm.login = login;
  vm.logout = logout;
};

Can anyone catch the bug I'm not seeing here? 谁能找到我在这里没有看到的错误? Basically I have a JWT on the client when I'm logged in but my initialization on the client controller is not recognizing that I'm logged in (it's not setting the user object to anything). 基本上,登录时我在客户端上有一个JWT,但是在客户端控制器上的初始化未识别出我已登录(这没有将用户对象设置为任何对象)。 It's kinda strange. 有点奇怪

So my solution ended up taking into account Kent's help and a little brainstorming. 因此,我的解决方案最终考虑了Kent的帮助和一些头脑风暴。 It looked like the following. 看起来如下。 Note, apparently middleware ordering in express matters a lot since after changing when Express-jwt got loaded made a huge difference in whether or not the authentication headers were checked on initial directory load on the client (which if they were angular wouldn't load and the whole app broke). 请注意,显然,Express中的中间件排序很重要,因为更改Express-jwt的加载时间后,是否在客户端的初始目录加载时检查了身份验证标头(如果它们是角度的,则不会加载,并且整个应用程序坏了)。 Cheers! 干杯!

'use strict';
var faker = require('faker');
var cors = require('cors');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');
var compression = require('compression');
var express = require('express');
var bcrypt = require('bcrypt');
var connectLiveReload = require('connect-livereload');
var jwt = require('jsonwebtoken');
var app = express();

var jwtSecret = 'fjkdlsajfoew239053/3uk';

app.use(cors());
app.use(bodyParser.json());
app.use(compression());
app.use(express.static(__dirname + '/client'));
// app.get('/', function(req, res){
//   res.render(__dirname + '/client/bundle.js');
// });
app.use(expressJwt({ secret: jwtSecret }).unless({ path: ['/login']}));

app.get('/me', function (req, res) {
  res.send(req.user);
});


...schema stuff...

  // UTIL FUNCTIONS

  function authenticate(req, res, next) {
    var body = req.body;
    if (!body.username || !body.password) {
      res.status(400).end('Must provide username or password');
    }

    //do salting, hashing, etc here yo
    User.findOne({ username: body.username }, function(err, user){
      if (user === null || body.password !== user.password) {
        res.status(401).end('Username or password incorrect');
      }else{
        req.user = user;
        next();
      }
    });
  }

  // ROUTES
  app.post('/login', authenticate, function (req, res, next) {
    var token = jwt.sign({
      username: req.body.username
    }, jwtSecret);
    res.send({
      token: token,
      user: req.user
    });
  });

// app.use(connectLiveReload()); figure out whats wrong with this later and get livereload working

app.listen(process.env.PORT || 5000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM