Angular 5 JWT Authentication(Spring Boot Security)

Welcome to angular 5 jwt authentication with spring security.In this tutorial, we will be creating a full stack app using jwt authentication in an angular5 single page application having backened server supported by spring boot with integration of spring security.Having said that we will have a sample angular5 example application with HttpInterceptor integrated with it to intercept all the HTTP request to add jwt authorization token in the header and in the server we will have some REST endpoints exposed and secured using spring security.The resource will be accessible only if valid jwt token is found in the header.We will be using Mysql DB for persistant storage.

This article is comprised of 4 sections.In the first section we will be building our single page angular 5 application using material design. In the second section we will be creating a spring boot application with sample REST endpoints exposed. In the third section we will have JWT integration with spring security and in the fourth section we will have jwt integration with angular 5 using HttpIntrceptor.So, let's get started.Here is an another article of Securing REST API with Spring Boot Security Oauth2 JWT Token.The JWT example below has user role hardcoded in the code to make this example simpler. I have created another full-fledged application here - spring boot security role based jwt authorization with user role mapping defined in database.

Technologies Used

We have frequent version upgrades in angular as well as in spring boot. Hence, let us first confirm the versions of these technologies that we will be using to build this application.

1. Spring Boot 1.5.8.RELEASE

2. jjwt 0.6.0

3. Angular 5.2.0

4. Angular Material 5.1.0

5. MySql

6. Java 1.8

Jwt Authentication

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object.a stateless authentication mechanism as the user state is never saved in server memory.A JWT token consists of 3 parts seperated with a dot(.) i.e. Header.payload.signature

Header has 2 parts type of token and hashing algorithm used.The JSON structure comprising these two keys are Base64Encoded.

{
"alg": "HS256",
"typ": "JWT"
}

Payload contains the claims.Primarily, there are three types of claims: reserved, public, and private claims. Reserved claims are predefined claims such as iss (issuer), exp (expiration time), sub (subject), aud (audience).In private claims, we can create some custom claims such as subject, role, and others.

The server's protected routes will check for a valid JWT in the Authorization header, and if it's present, the user will be allowed to access protected resources.Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization header using the Bearer schema. The content of the header should look like the following:

Create Angular5 Application

We already have our angular5 application created in my last article here - Angular5 Material App.This was a very simple application with angular material integrated.In this application, we have 2 modules user and login module with routing integrated.But here the login validation was hard coded in the client application itself and once the user is successfully logged in, he will be redirected to user page where he can see a list of users in a data table.

Following is the previous project structure and the project structure which we will be building now.

In this example we need to create a HTTP client first that will be consuming the REST APIs.To do so we will be using HttpClient from @angular/common/http. Following is our app.service.ts.For demo purpose we only have one HTTP call to fetch the user list.

Don'st forget to include userService and HttpClientModule in the providers in app.module.ts

Similarly, in the user.component.ts we have following changes to the service and populate the data table.One more thing to note here is we have disabled the authentication for /users endpoint in spring security config.

Create Spring Boot Application

The spring boot application has an endpoint exposed at /users from controller class. It's a simple implementation.Also, we have CORS enabled for angular and the user model class has 4 attributes as id, username, age and salary.

Spring Security Configuration

Now we will configure the security to secure our application. For now, we will allow /users endpoint for public access so that we can validate our jwt authentication later and display users list in the data table as in the image above.All this configurations have been discussed in my last article here - Spring Boot Security JWT Authentication.Here authenticationTokenFilterBean() has no effect as we have allowed /users endpoint for public access.

Adding JWT Authentication in Spring Security

The simple implementation for JWT is to write a filter class that will intercept all the requests and look for JWT Authorization token and if the token is found in the header, it will extract the token, parse it to find the user related information such as username and roles.Once he token is validated, it will prepare the spring security context and forward the request to next filter in the filter chain.

So for this purpose, we have spring provided OncePerRequestFilter class that executes once per request. In the filter, we are hard coding the roles but in real time application either we can extract it from custom scopes from JWT token or do a DB lookup in UserDetailsService

Once this implementation is done, we can actually remove the "/users" from WebSecurityConfig.java and validate that we will get 401 while trying to load data in our angular data table.

Create JWT Token in Spring Security

We have this controller defined to generate the JWT token.This controller will method will be called from client during login request. It will validate the user from DB with the username and password combination and accordingly generate JWT token.

Angular5 JWT Authorization

Now when coming to JWT authorization integration in angular5 with spring security, first we need to make a POST request for login with username and password. In the response, server will provide you a JWT token after successfull authentication.Once, we get this token, we can cache it in our browser for reuse for further API calls.For now let us define our authservice that will request for JWT token on login.

Adding this token manually in the header for all the API requests is not a cleaner way yo do. Hence, we will be implementing a HTTPInterceptor that will intercept all the rquest and add this JWT authorization token in the header. Also, we can intercept the response and for any unauthorized request or expired token we can redirect user to login page.Also, to store this token locally, we can use sessionstorage - The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed). The interceptor will implement the HttpInterceptor interface and override intercept(). Here, we are cloning the request to set the headers we want.Following is the interceptor implementation.