简体   繁体   English

如何使用 JWT 和 Passport 正确使用 nodeJs API 的身份验证?

[英]How to correctly use the authentication for nodeJs API using JWT and Passport?

I am using JWT-simple for authenticating my express routes.我正在使用 JWT-simple 来验证我的快速路线。

server side:服务器端:

var jwt = require('jwt-simple');
var bcrypt = require('bcrypt');
var passport = require('passport');

require('../passport')(passport);

/* Create an Account */
router.post('/signup', function (req, res, next) {
    var verifyCode = Math.random().toString(36).slice(-8);
    var userData =  {
        name: req.body.name,
        email: req.body.email,
        phone: req.body.contact,
        password: req.body.password,
        verify_code: verifyCode,
        status: 0
    };

   loginService.createUser(userData, function (err, data) {
            if (err) {
                res.status(500).json({error: true, data: {message: err.message}});
            } else {
                var token = jwt.encode(data, "secret");
                res.json({success: true, data: {token: 'JWT ' + token}});
            }
        });
});
/* GET the info of an API using the jwt token data */
router.get('/info', passport.authenticate('jwt', {session: false}), function (req, res, next) {
    var token = tokenRetrive.getToken(req.headers);
    if (token) {
        var decoded = jwt.decode(token, configVar.config.secret);
        UserService.getContentUserById(decoded.id, function (err, user) {
            if (err) {
                res.status(500).json({error: true, data: {message: err.message}});
            } else {
                if (!user) {
                    res.send({success: false, msg: 'Authentication failed. User not found.'});
                } else {
                    if (!user) {
                        return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
                    } else {
                        res.json({success: true, data: user.toJSON()});
                    }
                }
            }
        });
    } else {
        return res.status(403).send({success: false, msg: 'No token provided.'});
    }
});

client side客户端

var signup = function(user) {
            return $q(function(resolve, reject) {
                $http.post(API_ENDPOINT.url + '/signup', user).then(function(result) {
                    if (result.data.success) {
                        storeUserCredentials(result.data.data.token);
                        resolve(result.data);
                    } else {
                        reject(result.data.msg);
                    }
                });
            });
        };

 function storeUserCredentials(token) {
            window.localStorage.setItem(TOKEN_KEY, token);
            var loggedIn_user_Data = jwt_decode(token);
            $http.defaults.headers.common.Authorization = token;
        }

Using REST client (POSTMAN) when I pass the header info to the API I use当我将标头信息传递给我使用的 API 时使用 REST 客户端 (POSTMAN)

API : localhost:8080/info API : 本地主机:8080/信息

Key钥匙

Authorization
Content-Type   

Value价值

JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiYXR1bCIsImVtYWlsIjoidHJlZUB0cmVlLmNvbSIsInBob25lIjpudWxsLCJwYXNzZHJlc3MiOm51bGwsImNvdW50cnkiOm51bGwsInN0YXRlIjpudWxsLCJwaW5jb2RlIjpudWxsLCJvcmdfaWQiOjAsInJvbGVzIjpudWxsLCJjcmVhdGVfZGF0ZSI6IjIwMTctMDUtMThUMTk6NTE6MDYuMDAwWiIsImxhc3RfbG9naW4iOiIyMDE3LTA1LTE4VDE5OjUxOjA2LjAwMFoiLCJhdmF0YXJfdXJsIjpudWxsfQ.umxBRd2sazaADSDOW0e8rO5mKDpQYIK1hsaQMZriZFE

application/json

The above API gives me the data only if the correct token is passed and seems working fine.仅当传递了正确的令牌并且似乎工作正常时,上述 API 才会为我提供数据。

However in client side I can get the token retrieve using jwt-decode, without the use of any secret in client side, what if the token is caught by middle man, How can the security be enhanced?但是在客户端,我可以使用 jwt-decode 获取令牌检索,而无需在客户端使用任何秘密,如果令牌被中间人捕获怎么办,如何增强安全性?
Is there something I am missing to have correct use of JWT for my node api routes?对于我的节点 api 路由,我是否缺少正确使用 JWT 的东西?

Some places I see the Authorisation is passed as bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiYXR1bCIsImVtYWlsIjoidHJlZUB0cmVlLmNvbSIsInBob25lIjpudWxsLCJwYXNzd29yZCI6IiQyYSQxMCRIQVJPTy5PUEdYWFBvVktXOVhmYnZldk When I try to use bearer I get error to get the info after authenticating.有些地方我看到了授权作为传递bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiYXR1bCIsImVtYWlsIjoidHJlZUB0cmVlLmNvbSIsInBob25lIjpudWxsLCJwYXNzd29yZCI6IiQyYSQxMCRIQVJPTy5PUEdYWFBvVktXOVhmYnZldk当我尝试使用承载我得到验证错误后能得到的信息。 What is this bearer and JWT being passed in value to header?这个承载和 JWT 被传递给标头的值是什么?

I am using passport-jwt var JwtStrategy = require('passport-jwt').Strategy;我使用的是passport-jwt var JwtStrategy = require('passport-jwt').Strategy;

To use JWT tokens, you have to use SSL (https).要使用 JWT 令牌,您必须使用 SSL (https)。 Without it, you won't have protection at all.没有它,您将根本无法获得保护。

JWT tokens are signed (check the site ). JWT 令牌已签名(检查站点)。 So if someone (middle man) try to change it, it will be invalidated.所以如果有人(中间人)试图改变它,它就会失效。

JWT and Bearer are basic the same thing. JWT 和 Bearer 是基本相同的东西。 They are just the auth scheme for the authorization header.它们只是authorization标头的auth scheme

The 'JWT' auth scheme is the default of the passport-jwt . “JWT” auth schemepassport-jwt的默认设置。 If you want to change it, you can use a different jwtFromRequest value.如果要更改它,可以使用不同的jwtFromRequest值。

See:见:

new Strategy({ ... jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer') ... }, verifyFunction)

Hope its clear.希望它清楚。

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

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