Skip to content

Instantly share code, notes, and snippets.

@jofftiquez
Last active May 19, 2018 06:45
Show Gist options
  • Save jofftiquez/a89f3df937b092aa2545 to your computer and use it in GitHub Desktop.
Save jofftiquez/a89f3df937b092aa2545 to your computer and use it in GitHub Desktop.
How to use JWT to authenticate REST calls from client side.

JWT Auth Bearer Bible

Token

Upon login the API will provide a jwt token bearer which is on the response headers. Extract the token from the headers.

Sample Token :

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3N1ZXIiOiJhcGkubXlDdXJlLnBoIiwiYXVkaWVuY2UiOiJ3d3cubXlDdXJlLnBoIiwiZW1haWwiOiJqb2ZmdGlxdWV6QGdtYWlsLmNvbSIsImV4cGlyeSI6IjIwMTYtMDItMTZUMDM6NDA6NDUuMTc0WiIsImlhdCI6MTQ1NTU5MDQ0NX0.1tJCtBYyy6DWwnsap_jIp16pzVx1RK8BrxJIXAqrXrE

What to do?

The token should be included on the request headers for every request to the server, like literally every request except for login of course. This way we can eliminate cookies for session and do it on the server side.

Why?

It's secure duh?

TL;DR How?

Well, this will be a case-to-case basis, on this documentation I will show how to do it in javascript using angularjs.

  1. The jwt strategy requires the token to have a "Bearer " prefix to it before sending to the server. Before saving the the token to localStorage or sessionStorage prepend the string "Bearer " to the token. Add the account email to the headers as well.
var token = "Bearer "+eyJ0eXAiOiJKV1QiLCJhbGciO...
  1. Usage :
var req = {
    method: "GET",
    url: '/api/to/your/heart',
    headers: {
    	email: 'jofftiquez@gmail.com',
        'Authorization' : token, // the 'Authorization' key is super required.
    }
}

$http(req).then(function(response) {
	// success callback
}, function(error) {
	// errah callback
	// if token doesnt exist or is expired 
	// will return 401, "Unauthorized":"Invalid Token"
});

Tips

  1. Use angularjs services to read and write tokens across all controllers on client end.
  2. Store tokens on localStorage of the browser to access it even in new tabs.
  3. Prepare a resuable function that will test if the user is still authenticated else logout.
  4. Delete the token from localStorage when the user logs out.
  5. Will add more...

Useful references

  1. angularjs services - https://docs.angularjs.org/guide/services
  2. locaStorate - https://developer.mozilla.org/en/docs/Web/API/Window/localStorage
  3. jwt - https://jwt.io/
  4. angularjs http req - https://docs.angularjs.org/api/ng/service/$http

Renew Token*

Route : /renew-token

Query : email

Usage : api_endpoint/renew-token?email=jofftiquez@gmail.com

*requires Authorization

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment