Simple AngularJS Authentication with JWT

Persisting JWTs to localStorage


As long as the client possess a valid token, they can be considered "authenticated." We can persist this state across multiple page visits by storing the JWT using localStorage.

HTML5 localStorage is a key-value store that can be accessed on the window object. The data is stored separately from cookies and sessionStorage, and can persist for multiple browsing sessions until it is cleared by your app or the browser. All of the keys and values in localStorage are always strings.

Add a method to save the token to localStorage thereby logging the user in:
self.saveToken = function(token) {
  $window.localStorage['jwtToken'] = token;
We'll also want a method to retrieve the token from localStorage:
self.getToken = function() {
  return $window.localStorage['jwtToken'];

Now we have methods on our service for getting and setting our JWT to localStorage, which we can now use throughtout the rest of our application.


I finished! On to the next chapter