Simple AngularJS Authentication with JWT

Authenticating with an Interceptor

Use an AngularJS Interceptor to automatically handle updated JWTs for authentication

Now that we have our JWT management in place, let's build out and HTTP interceptor to automatically send the token with each request that needs authentication.

Saving and Refreshing the Token

At this point, we have created methods for saving and loading tokens but we haven't actually wired them up to do so. We can easily do this using the response() callback of our interceptor. Simply check each returning response from the API server for the presence of a token then call auth.saveToken().

Automatically save JWT tokens sent back from the server
response: function(res) {
  if(res.config.url.indexOf(API) === 0 && {

  return res;

Now your register() and login() calls should actually save the JWT without having to do anything else!

One awesome result of using interceptors is the ability to automatically refresh the JWT. Anytime a user successfully makes an API call to a protected route, the server can attach a new token to the response payload. The interceptor will automatically grab the new token and save it so as long as the user continues to make requests to the server, the token will never expire and she won't be forced to re-authenticate.