最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

创建一个中间件功能检查,如果用户角色等于“管理员”

IT培训 admin 4浏览 0评论

创建一个中间件功能检查,如果用户角色等于“管理员”

我创建使用最新MEAN堆栈技术,一个博客。登录的用户可以创建一个角色,“管理员”和“版主新用户。

Creating a new user with an admin role or moderator role

这条路线是受保护的,目前,用户只有记录的可以访问它。这是因为如果用户进行身份验证或不检查中间件。

//check_auth.js

const jwt = require('jsonwebtoken');

module.exports = (req, res, next) => {
  try {
    const token = req.headers.authorization.split(' ')[1];
    jwt.verify(token,  'my_jwt_secret');
    next();
  } catch (error) {
    res.status(401).json({ message: 'Auth failed!'});
  }


};
回答如下:

添加路由处理给需要验证并导入它需要的地方所有端点。 https://expressjs/en/guide/routing.html

恩。

router.post('/login', verify.isAdmin, (req, res, next) => {
    //do something
})

//验证在单独的文件中的功能

module.exports = {
    isAdmin: (req, res, next) =>{
        if(req.user.admin){
            next();
        }else{
            res.status(403).send();
        }
    }
}

完整的代码示例:

https://medium/@maison.moa/using-jwt-json-web-tokens-to-authorize-users-and-protect-api-routes-3e04a1453c3e

https://medium.freecodecamp/securing-node-js-restful-apis-with-json-web-tokens-9f811a92bb52

创建一个中间件功能检查,如果用户角色等于“管理员”

我创建使用最新MEAN堆栈技术,一个博客。登录的用户可以创建一个角色,“管理员”和“版主新用户。

Creating a new user with an admin role or moderator role

这条路线是受保护的,目前,用户只有记录的可以访问它。这是因为如果用户进行身份验证或不检查中间件。

//check_auth.js

const jwt = require('jsonwebtoken');

module.exports = (req, res, next) => {
  try {
    const token = req.headers.authorization.split(' ')[1];
    jwt.verify(token,  'my_jwt_secret');
    next();
  } catch (error) {
    res.status(401).json({ message: 'Auth failed!'});
  }


};
回答如下:

添加路由处理给需要验证并导入它需要的地方所有端点。 https://expressjs/en/guide/routing.html

恩。

router.post('/login', verify.isAdmin, (req, res, next) => {
    //do something
})

//验证在单独的文件中的功能

module.exports = {
    isAdmin: (req, res, next) =>{
        if(req.user.admin){
            next();
        }else{
            res.status(403).send();
        }
    }
}

完整的代码示例:

https://medium/@maison.moa/using-jwt-json-web-tokens-to-authorize-users-and-protect-api-routes-3e04a1453c3e

https://medium.freecodecamp/securing-node-js-restful-apis-with-json-web-tokens-9f811a92bb52

发布评论

评论列表 (0)

  1. 暂无评论