简体   繁体   English

将JWT从AngularJS发送到Node.js

[英]Send JWT from AngularJS to Node.js

An AngularJS app needs to exchange a JWT with the Node.js instance that serves it. AngularJS应用程序需要与为其提供服务的Node.js实例交换JWT。 The Node.js instance has a /user route which returns a JWT to the Angular client. Node.js实例具有一个/user路由,该路由将JWT返回到Angular客户端。 What specific changes need to be made to the code below so that 1.) The AngularJS app can send the JWT back to the Node.js instance's /user route, and 2.) the Node.js code can isolate the JWT as a variable for processing? 以下代码需要进行哪些具体更改,以便1.)AngularJS应用可以将JWT发送回Node.js实例的/user路由,并且2.)Node.js代码可以将JWT隔离为变量进行处理?

The current AngularJS code for calling the backend /user route is: 当前用于调用后端/user路由的AngularJS代码为:

$http.get('user').then(function(response) {
        console.log('response is: ');
        console.log(response);
        if (response.data.token === 'anonymous') {
            $rootScope.authenticated = false;
        } else {
            $rootScope.userJWT = response.data.token; 
            var payload = $rootScope.userJWT.split('.')[1];
            payload = $window.atob(payload);
            payload = JSON.parse(payload);
            self.name = payload.name;
            self.authorities = payload.authorities;
            $rootScope.authenticated = true;
        }
    }, function() {
        $rootScope.authenticated = false;
    });

And the Node.js code for the backend /user route is: 后端/user路由的Node.js代码为:

app.get('/user**', function(req, res) {
    console.log("You Hit The User Route TOP");
    //How do we get the JWT from req?
    var user = getUserName(theJwt);
    var token = getToken(user);
    var jwtJSON = getUser(token);
    if( (jwtJSON["token"] == 'error') || jwtJSON["token"] == 'anonymous' ) {
        res.sendStatus(500);  // Return back that an error occurred
    } else {
        res.json(jwtJSON);
    }
    console.log("You Hit The User Route BOTTOM");
});

Note, the Node.js instance includes var jwt = require('jsonwebtoken'); 注意,Node.js实例包括var jwt = require('jsonwebtoken'); , and one of the processing methods will decode the JWT using var decoded = jwt.decode(token, {complete: true}); ,其中一种处理方法将使用var decoded = jwt.decode(token, {complete: true});来解码JWT var decoded = jwt.decode(token, {complete: true}); , as per the jsonwebtoken API . ,按照jsonwebtoken API进行

When using JWT there is no required way to communicate the token. 使用JWT时,没有必要的方式来传递令牌。

The most common way is to place the token into an HTTP Header. 最常见的方法是将令牌放入HTTP标头中。

On the AngularJS side you would make an HTTP request with an extra header (eg X-Auth-Token) which contains the JWT. 在AngularJS端,您将使用包含JWT的额外标头(例如X-Auth-Token)发出HTTP请求。

Example of AngularJS side: AngularJS方面的示例:

var config = {
    headers: {
        "X-Auth-Token": $rootScope.userJWT
    }
}
$http.get('routeThatNeedsJWT', config).then(function(response) { ... });

On the Node.js side you would get the contents of the header and process it using the jsonwebtoken library. 在Node.js端,您将获取标头的内容并使用jsonwebtoken库对其进行处理。

Example of Node.js side: Node.js方面的示例:

app.get('/routeThatNeedsJWT', function(req, res) {
    var rawTokenFromHeader = req.get('X-Auth-Token'); // Get JWT from header
    try {
        var jwtJSON = jwt.verify(token, 'secret'); // Verify and decode JWT
        res.json(jwtJSON);
    } catch (err) {
        res.sendStatus(500);  // Return back that an error occurred
    }
});

Helpful links: 有用的网址:

Express 4.x getting header value Express 4.x获取标头值

jsonwebtoken library verify token jsonwebtoken库验证令牌

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

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