Thinkster
Angular

Simple AngularJS Authentication with JWT

Learn how to implement JWT authentication with AngularJS, localStorage, and HTTP Interceptors

Up to date (Jan '17) AngularJS

In this tutorial I'm going to take you through building a simple authentication mechanism for AngularJS apps using JWTs (JSON web tokens) combined with local storage. We'll build out a service for managing the tokens and create an $http interceptor for automatically attaching the tokens to requests. As this guide discusses front-end concepts only, I have built out a publicly accessible test API that you are encouraged to test your own code against. If you're interested in learning about the backend component, checkout our MEAN tutorial or let me know on twitter!

What are JWTs

JWTs provide a way for clients to authenticate every request without having to maintain a session or repeatedly pass login credentials to the server. A JWT consists of three main components: a header object, a claims object, and a signature. These three properties are encoded using base64, then concatenated with periods as separators. Some important things to know about JWT's:

  • The claims object contains an expiration date which dictates how long the token is valid for
  • The claims object can also contain custom bits of information such as a user ID
  • The token is NOT encrypted so anyone with it can read all the properties
  • The token IS signed by the server so if any of the values are changed, the server will reject it
Read Atlassian's understanding JWT guide

You can also find more information about JWT at jwt.io.