Securing node.js RESTful services with JWT Tokens
I wanted to create a web service in node. It needed to be stateless, and secure such that only users with the correct credentials could access certain entities. The answer was to use a token. There are a few token modules for node, and I settled on node-jwt-simple. This gives you a JWT (JSON Web Token), which is a:
…means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JavaScript Object Notation (JSON) object that is digitally signed or MACed using JSON Web Signature (JWS) and/or encrypted using JSON Web Encryption (JWE).
To implement this in Node; first, allow users to log in, check they’re ok, and return them a token (I’m using express):
var app = require('express').express(); var jwt = require('jwt-simple'); app.get('/token/', function(req, res) { var username = req.headers.username; var password = req.headers.password; if(checkUser(username, password)) { var token = jwt.encode({username: username}, tokenSecret); res.json({token : token}); } else { res.json({result: "AuthError"}); } });
Notice that I’m sending the username and password as headers. I could be using a post and pass them in the body. I don’t think it really matters. When you create the token, you have the opportunity to set some claims, basically properties of an object. Here I set the username, but if there’s something you need to know about your user, you can put it here.
From the browse I can call this endpoint, passing the username and password in on the header, to retrieve the token:
$.ajax({ type: "GET", cache: false, dataType: "json", url: "/token/", headers: {username:username, password:password}, success: function(token){ setToken(token); } });
Back in Node, I can then add some more endpoints to my API, and check the token on each request to ensure it’s valid.
app.get('/XYZ/', function(req, res){ var decoded = jwt.decode(req.headers.token, tokenSecret); if (checkUserCanAccessResource(decoded.username)){ ... } }
The token is read from the header, so you need to add it to each jQuery request:
$.ajax({ type: "GET", cache: false, dataType: "json", url: "/XYZ/", headers: { token:getToken(); }, success: function(data){ ... } });
This code is only an illustration. You need to think about expiry, error messages etc…
canadagoosejakkeonlinesale.blogspot.com 9:58 am on November 28, 2012 Permalink | Log in to Reply
I’m usually just using the search engines to look up information.What you need is just rest.Spring is a pretty season.Walking up and down the stairs would beat any exercise machine.Help yourself.The population of the city is close to a million.The population of the city is close to a million.What shall we do tonight? Keep it up!I think you have the Wrong number.
Authentication between node.js and android - How-To Video 5:26 pm on April 2, 2013 Permalink | Log in to Reply
[…] Is there any implementation for passport.js which is based on the same authentication method like this: coderead.wordpress.com/2012/08… […]
Code Answers » Generate token after login nodejs API 4:12 am on June 21, 2013 Permalink | Log in to Reply
[…] have looked at using JWT tokens ie, https://coderead.wordpress.com/2012/08/16/securing-node-js-restful-services-with-jwt-tokens/. However I am not really sure how to create a secure token with JWT. I have read that using the […]
vrossign 3:23 pm on October 3, 2013 Permalink | Log in to Reply
I’m wondering what’s the point of decoding the token?
Since the token is probably attached to the user somewhere in a database you can still find the user by toke. Did I miss something ?
Richard 3:43 pm on October 3, 2013 Permalink | Log in to Reply
Decoding it ensures that your node process is the one that encoded in the first place (because only node knows the secret). This protects you against spoof tokens. You can also embed some extra information in the token, which may save you some database lookups.
vrossign 1:04 pm on October 4, 2013 Permalink | Log in to Reply
thanks for the answer, still if the token has been stolen there is nothing that can prevent the bad user to use it.
At the end of the post you talk about expiry of the token… any useful link to share regarding this topic and jwt-simple.
Richard 1:15 pm on October 4, 2013 Permalink | Log in to Reply
Sure, if the token is stolen, then you’ve got a problem. But if you decode it and check it, then you prevent users from creating their own tokens (a more likely attack vector).
For expiry, just write an expiry date to your payload data, and check it after you have decrypted it.
gsarwohadi 11:48 pm on March 3, 2014 Permalink | Log in to Reply
Thanks for the article. I’ve successfully implemented with passport-local and jwt-simple, and it works great. I’m using this for a cordova app calling REST server. I’ve also improvise it a bit, by including the device uuid in the jwt.encode body and for the secret, I use the session ID generated from passport-local. I know that jwt has an expire parameter, but not sure if it’s secure enough as the encoded token is always the same (due to same data and secret). With using session ID as the secret, it acts as an expiry date and also help generate different token.
Let me know what you think about this. Thanks
vrossign 8:20 pm on March 11, 2014 Permalink | Log in to Reply
how do you get the session ID from passport local ?
alejandropaciotti 3:44 pm on June 12, 2014 Permalink | Log in to Reply
Where is the setToken function?
Thanks!
Richard 3:47 pm on June 12, 2014 Permalink | Log in to Reply
Good question, that’s up for you to implement in the browser.By storing it in a variable or local storage.
alejandropaciotti 3:50 pm on June 12, 2014 Permalink | Log in to Reply
Yes! but…how?
Richard 3:53 pm on June 12, 2014 Permalink | Log in to Reply
var token;
function setToken(x){
token = x;
}
function getToken(){
return token;
}
alejandropaciotti 4:12 pm on June 12, 2014 Permalink | Log in to Reply
Spectacular!
使JSON Web令牌无效 | CODE问答 4:10 pm on November 21, 2017 Permalink | Log in to Reply
[…] cookie的方法相同/不同类型的攻击的影响。 所以,说我有以下(改编自this和this): […]
Недействительный токен JSON — Вопросы и ответы по программированию 12:56 pm on October 5, 2018 Permalink | Log in to Reply
[…] Итак, скажем, у меня есть следующее (адаптировано из this и this): […]
无效的JSON Web令牌_javascript问答 10:30 pm on September 26, 2020 Permalink | Log in to Reply
[…] 因此,说我有以下内容(适应了this和this): […]
[javascript] JSON 웹 토큰 무효화 - 리뷰나라 9:21 pm on November 5, 2020 Permalink | Log in to Reply
[…] 다음 (에서 적응이 있다고 이 와 이 ) […]
AngularFixing 8:22 am on March 8, 2022 Permalink | Log in to Reply
[…] So, say I have the following (adapted from this and this): […]
Invalidating JSON Web Tokens 5:10 pm on September 6, 2022 Permalink | Log in to Reply
[…] So, say I have the following (adapted from this and this): […]
JSON 웹 토큰을 무효화하는 중 - 다양한 이야기들 11:04 pm on October 15, 2022 Permalink | Log in to Reply
[…] 들어 다음과 같은 것이 있다고 합시다(이러한 것과 […]
Memvalidasi Token Web JSON – Kode Contoh 3:41 pm on March 12, 2023 Permalink | Log in to Reply
[…] katakan saya memiliki yang berikut (diadaptasi dari ini dan ini […]