Monday, January 8, 2018

REST tutorial : security with JWT token

Greetings!

This is the last part of our security tutorial.
Complete source code
$ git clone https://github.com/slmanju/todoapp.git
$ cd todoapp
$ git checkout security

follow the complete tutorial

JWT

JSON Web Token is an open standard that defines a compact and self-contained way for securely sharing data between parties using a JSON object.
  • Compact - smaller size
  • Self-contained - payload contains all the required information
Typically contains,
  • Header - consists of the type of the token, hashing algorithm being used
  • Payload - contains the claims.
  • Signature
A token fields are separated by dots like this, xxx.yyy.zzz

https://jwt.io/introduction/

Since we already have added token support in our previes tutorial, we only have to modify it to a JWT token.


Sample Header

{
  "alg": "HS512"
}

Sample Payload

{
  "sub": "manjula",
  "userId": "1",
  "role": "ADMIN",
  "iat": 1515401468,
  "exp": 1515405068
}

Testing with JWT

// requesitng a token
$ curl -i -H "Content-Type: application/json" -X POST -d '{"username":"manjula","password":"password"}' http://localhost:8080/token
{
    "token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJtYW5qdWxhIiwidXNlcklkIjoiMSIsInJvbGUiOiJBRE1JTiIsImlhdCI6MTUxNTQwMTQ2OCwiZXhwIjoxNTE1NDA1MDY4fQ.fzEAwy3110zhYe-XtBUV2Owsr_20CmnbaQ64jnAKh9eoCC41OWwbNddb1Hi-d7cDXARvuko2ADV88iXBos0UqA"
}

// request with token
$ curl -i -H "Authorization":"Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJtYW5qdWxhIiwidXNlcklkIjoiMSIsInJvbGUiOiJBRE1JTiIsImlhdCI6MTUxNTQwMTQ2OCwiZXhwIjoxNTE1NDA1MDY4fQ.fzEAwy3110zhYe-XtBUV2Owsr_20CmnbaQ64jnAKh9eoCC41OWwbNddb1Hi-d7cDXARvuko2ADV88iXBos0UqA" http://localhost:8080/todos


Congratulations!!! you have successfully created a secure RESTful API.

No comments:

Post a Comment