【问题标题】:NodeJS User AuthenticationNodeJS 用户认证
【发布时间】:2018-08-25 19:37:56
【问题描述】:

我被困在 NodeJs 中的某一点上。我将逐步解释我的系统。

  1. 用户注册到系统
  2. 后端创建 JWT 令牌并将其发送给用户
  3. 用户将 jwt 令牌存储在 本地存储

  4. 我想在用户登录时进入 /profile 页面。

  5. 用户点击一个按钮,将 http post 发送到 /api/profile
  6. 我们的 http 请求现在已经发送到 /api/profile。路由器和授权部分如下
  7. 如果用户通过此授权步骤。我的 /api/profile 函数返回 res.json({success : true})
  8. 我正在使用 response.data.success === true 检查 http 响应值。如果为真,则将用户发送到 /profile 页面。如果没有,请将用户发送到 /login 页面。

问题来了

如果用户在url栏输入/profile,用户可以直接进入该页面,因为缺少http.post请求,没有授权控制。

如何检查用户是否在登录时输入了/profile?

我的功能如下。

HTTP POST

var profile = function () {
    var token = $window.localStorage.getItem('jwt')
    return $http.post('/api/profile',  {'token': token}).then(function (response) {
        if(response.data.success === true){
                $window.location.href = "/profile";
        }else{
                $window.location.href = "/login";
        }
    });
}

个人资料页面

exports.profilePage = function (req, res) {
    categoryModel.find(function (err, allCategories) { //NOT TO LOSE MENS OR WOMENS FROM NAVBAR !
        res.render('profile', {
            allCategories: allCategories
        })   
    });
}

/API/配置文件

exports.profile = function (req, res) {
    res.json({
        success: true
    })
}

路由器

const userController = require('../controllers/userController')
app.get('/profile', userController.profilePage);
app.post('/api/profile', userController.authenticate, userController.profile);  //AUTHORIZATION REQUIRED

授权

exports.authenticate = function (req, res, next) {
    var token = req.body.token
    if (token != null) { //To know that user logged in
        var user = userDBModel.User().methods.verifyJWT(token)
        if (user) {
            return next()
        } else {
            return res.json({
                success: false
            })
        }
    } else {
        return res.json({
            success: false
        })
    }
}

【问题讨论】:

  • My problem isHere is the problem 这些问题中的哪一个完全不起作用?此外,您只为发布请求设置了授权检查,而不是 GET 请求。
  • 但是 window.location.href 不是 http 请求。我应该在 http 请求中发出 http 请求吗?

标签: node.js express jwt


【解决方案1】:

在这种情况下,connect-ensure-login 包可以为您工作吗?如果找不到令牌,我将它与 JWT/Express 一起使用以重定向到登录。

https://github.com/jaredhanson/connect-ensure-login

【讨论】:

  • 我会查的。谢谢你的回答
猜你喜欢
  • 2014-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-25
相关资源
最近更新 更多