I wanted to create a web service in node. here are some of the features of my web service.It needed to be
- stateless,
- secure such that only users with the correct credentials could access certain entities.
Well http and REST are by default stateless.
Do Read:- RethinkDB : Realtime Database Problem solved
The answer for secure is 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) and then check token with each request you get into your rest api endpoint(means , client app needs to send token back to you with each request.):
var app = require('express').express(); var jwt = require('jwt-simple'); var tokenSecret = "secret string"; app.get('/token',function(req, res) { var username = req.params.username; var password = req.params.password; if(checkUser(username, password)) { var token = jwt.encode({username: username,role:"admin"}, tokenSecret); res.json({token : token}); } else { res.json({result: "AuthError"}); } });
When you create the token, you have the opportunity to set some claims,means you can set userID and what user can access and all(authorization) as properties of an object.
Here I set the username and ar role = admin, but if there’s something you need to know about your user, you can put it here.
Recommended:- RethinkDB : server instance command options explained
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", data: {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('/accessAdminPanel',function(req, res){ var decoded = jwt.decode(req.headers.token, tokenSecret); if (checkUserCanAccessResource(decoded.username) && authorize(decoded.role)){ ... } }
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: "/accessAdminPanel", headers: { token:getToken(); }, success: function(data){ ... } });
This code is only an illustration. You need to think about expiry, error messages etc…
so that was it. if you interested in knowing more. we can have great talk on twitter of facebook. Ping Me 😉
Peace.