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
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.
It's secure duh?
Well, this will be a case-to-case basis, on this documentation I will show how to do it in javascript using angularjs.
- 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...
- Usage :
var req = {
method: "GET",
url: '/api/to/your/heart',
headers: {
email: '[email protected]',
'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"
});
- Use angularjs services to read and write tokens across all controllers on client end.
- Store tokens on localStorage of the browser to access it even in new tabs.
- Prepare a resuable function that will test if the user is still authenticated else logout.
- Delete the token from localStorage when the user logs out.
- Will add more...
- angularjs services - https://docs.angularjs.org/guide/services
- locaStorate - https://developer.mozilla.org/en/docs/Web/API/Window/localStorage
- jwt - https://jwt.io/
- angularjs http req - https://docs.angularjs.org/api/ng/service/$http
Route : /renew-token
Query : email
Usage : api_endpoint/[email protected]
*requires Authorization