Token based authorization in nodejs/ExpressJs and Angular(Single Page Application)

1.9k views Asked by At

In my application,while registering the users i am saving username,password and jwt generated token with these fields in MONGO DB.When user tries to login with correct credentials then i will send the response with stored token.Then at client side(In my controller) i am using the localstorage to store the token so that i can send the same token for each and every request sent by the client.But I found some issues regarding this procedure:

  1. I am generating same token for one user every time.So if any third person is able to get the token then he can access the restricted page.
  2. Am i wasting space in db by storing the generated token in MONGODB
  3. Can Anyone access the token stored in localstorage other than the user.
  4. for each and every request in my single page application,I am again querying mongodb to get the token for that user and validating.Here,I am checking both client side and server side.

I am using jwt to generate tokens,Node,Express,Mongoose in my application

Am i following the good procedure.If not,can you please provide the solution for my approach or any new approach. I have searched many sites for token based authorization and session based authorization,But nothing worked for me. Note:I am beginner for Nodejs,AngularjS

3

There are 3 answers

3
Kevin Le - Khnle On BEST ANSWER

When a user registers, you would need to generate a JWT like you're doing now. That's OK. You don't need to save it to the database however. You didn't ask but I assume that the password should not be stored in clear text. You can use something bcrypt to encrypt before saving it to the database.

When user tries to login with correct credentials then i will send the response with stored token

Yes, that's correct way to do.

Then at client side(In my controller) i am using the localstorage to store the token so that i can send the same token for each and every request sent by the client.

Yes, on the client side, you can save the JWT to local storage and send it in subsequent requests to the server.

Now your bullet points:

  1. So that you won't have the same JWT each time, you can include an "exp" claim in the payload (I'm assuming you're using something like jwt-simple to generate a JWT). Something like:

    var payload = { sub: account.username, exp: moment().add(10, 'days').unix() }; var token = jwt.encode(payload, "secret");

  2. You don't need to store the JWTs in the database. In some cases, the token issuers (the authorization servers) are not the same as the resource servers. The resource servers only receives the JWTs in a request but there's no way for the resource servers to touch the database used by the authorization servers. Side note: If you eventually need to support refresh tokens, i.e. the JWTs that you hand to the clients will need to eventually expire, then you can store the refresh token in a database. Refresh tokens are not the same as JWTs (access tokens). The complexity to support refresh tokens will increase.

  3. Local storage is not where you store passwords, but it can be used to store JWTs. For that very reason, a JWT must and should expire after a certain time.

  4. Not sure what you mean by saying you check both client side and server side. When the client needs to access a resource (again it's fair to assume that the resource server might not be the same as the authorization server), the only thing that the resource server is passed is the JWT. Anyone can decode a JWT. For example, try to paste your JWT on this site http://jwt.io/. That's why a JWT should not contain any sensitive data. But if the resource server knows the secret that the authorization server uses when it encode the JWT, the resource server can verify the signature. Back to your third bullet, that's why it's OK to store the JWT in local storage of the client.

Update I'm updating this to answer to some of your questions in the comment box.

User clicks on 'Login' button triggers the Angular controller to post a request to the server, something like:

$http.post(url, {
    username: $scope.username,
    password: $scope.password
}).success(function(res) { ... })

Server receives the POST request, it checks username/password, then it generates a JWT, and sends back to the browser. Note that it does not have to save the JWT to the database. The code would be something like

var payload = {
    sub: account.username,
    exp: moment().add(10, 'days').unix()
};
var token = jwt.encode(payload, "secret");
res.status(200).json({      
  token: token
});

Back on the client side, in the success() callback above, now you can save the JWT in local storage:

.success(function(res) { $window.localStorage.setItem('accessJWT', res.token) })

The user is now authenticated. Now when user wants to access a protected resource, user don't have to provide username/password. With the JWT which can be retrieved from local storage, the client can now put the JWT in the Authorization header of the request using the bearer scheme, and sends the request to the server. In code, it would like:

headers.Authorization = 'Bearer ' + token;

The server receives the request. Again, this server receiving this request does not have to be the same as the server which generates the JWT above. The 2 servers can be in 2 different continents. Even if you save the JWT above, that does not do any good to this server which can not access the database where the JWT is stored. But this server can pull out the bearer token from the header of the request, validates the token and carries on with the normal tasks.

Hope this helps.

0
venturz909 On

You do not want to store the JWT in mongoose because it appears in headers when logging in. You first generate a token then hash it using a module like crypto.

There are different ways to do this and they all use Passport which handles the tokens. Here's an example project Satellizer

I would recommend you generate the angular-fullstack project. Then go through the server/auth folder and the client/account folder. You will see how to securely handle authentication in a MEAN based app.

3
Maher Abuthraa On

You should store token in advanced key-value cache tool like: Redis That would improve performance remarkably.

You will get token from database for 1st time then it should be stored in Redis. I used to set token as key and username as value. Next request , the token will be given from cache. with Redis you can set expire for token.