JWT authentication with Spring Web - Part 4

In parts 1 through 3 of this series, we built a Spring API that can issue a JWT when a user successfully authenticates. In this blog post, we will add the capability to verify the JWT presented by the client for subsequent requests.
These are the blog posts in this series:

We will start by configuring Spring security with a filter to capture the JWT passed by the client in the Authorization header. We will wire up this filter to go before the UsernamePasswordAuthenticationFilter provided by Spring security.

The JwtAuthenticationProvider receives the Authentication instance set on the SecurityContext, which in our case is the JwtAuthToken we set using the JwtAuthFilter. This token is then verified using the JwtService. If the token is valid, we return a JwtAuthenticatedProfile or throw an exception if it is invalid.

When we generated the JWT, we had set the username as the JWT subject.

The last thing to do is to ensure that we handle exceptions that occur during token verification gracefully. Since the token verification is happening outside controllers, we won’t be able to leverage ControllerAdvice to handle exceptions. This is where Spring Security’s AuthenticationEntryPoint comes in to play. We will configure a custom AuthenticationEntryPoint as follows:

In the next blog post, the fifth is this series, we will move on to building the front end with Angular JS and managing authentication from the front end. The source code for this example for the progress made from part 1 through part 4 is available on GitHub.

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