JWT authentication with Spring Web - Part 5

In parts 1 through 4 of this series, we built a Spring API that can issue a JWT when a user successfully authenticates and verify the JWT presented by the client for subsequent requests. In this blog post - the last in the series, we will build a simple Angular JS application with authentication that uses this API as the backend.
These are the blog posts in this series:

We will use the following Angular plugins - angular-resource for interacting with our APIs, ngstorage to access the localStorage to store the JWT and angular-ui-router to handle routing and managing UI views.

For this example, our UI components are under the src/main/resources/static directory. We will be loading our dependencies using bower by adding a .bowerrc file at the root of our project.

The LoginController has two methods - login and logout. The login method uses the LoginService to make a request and saves the JWT and user profile returned up on successful login. It also sets the Authorization header default to the JWT returned so that every subsequent request uses it to authenticate. The user is then navigated to the home page. Logout is performed by removing the JWT and profile from local storage and clearing the header defaults.

The next step is to create app/app.js to wire up the Angular application together:

We start by wiring together our services and controllers to the main module. We use the state provider to map front end URLs to templates. The home page will use the home.html template and the sign in and sign out URLs will use the sigin.html template.

It also configures a listener that observes for URL changes made by the user and redirects them to the sign in page, unless they are already authenticated. If there is already a token in local storage when the application loads, that signifies that the user has already logged in a different tab and the authorization header default is set.

It also has a link for signing out. With this code in place, we can start our Spring application and sign in from the browser.

This is the last of this series of blog posts on JWT and Spring. We built an API capable of authenticating with JWTs and a front end capable of authenticating against this API. The code for the complete example is available on GitHub.

If you have questions or comments about this blog post, you can get in touch with me on Twitter @sdqali.