Angular 7 + Spring Boot JWT Authentication Example

Image title

In the previous tutorial, we implemented Angular 7 + Spring Boot Basic Auth Using HTTPInterceptor to intercept all outgoing HTTP requests and add a basic authentication string to them. In this tutorial, we will be modifying the application to perform authentication using the JSON Web Token (JWT). 

JWT httpinterceptor example

This tutorial is explained in the below YouTube video.

Spring Boot + JWT Implementation

In a previous tutorial, we implemented a Spring Boot + JWT Authentication ”Hello World” example. We will be modifying this project to add the TestController that we had implemented in the previous tutorial. The Maven project will be as follows:
Spring Boot JWT Angular Maven

The only other change we will need to implement is to allow the OPTIONS call in the Web security Config. These OPTIONS calls are made by the Angular application to the Spring Boot application.

package com.javainuse.config; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import; @Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; @Autowired
private UserDetailsService jwtUserDetailsService; @Autowired
private JwtRequestFilter jwtRequestFilter; @Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// configure AuthenticationManager so that it knows from where to load
// user for matching credentials
// Use BCryptPasswordEncoder
} @Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
} @Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
} @Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
// We don't need CSRF for this example
// dont authenticate this particular request
permitAll().antMatchers(HttpMethod.OPTIONS, "/**")
// all other requests need to be authenticated
// make sure we use stateless session; session won't be used to
// store user's state.
.sessionCreationPolicy(SessionCreationPolicy.STATELESS); // Add a filter to validate the tokens with every request
httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);

Start the Spring Boot Application

  • Generate the token by making a POST request to localhost:8080/authenticate Spring Boot JWT Angular Authentication
  • Use the Token in the authorization header to get the list of employees Spring Boot JSON Web Token Angular Authentication Example

Implement Changes for JWT Authentication on the Angular Side

We will be modifying the code we developed in this tutorial:

Spring Boot JWT Angular Authentication Example

The Angular project we will be developing is as follows:

angular 7 intercptor project

In the authentication.service.ts, if the authentication for the user-entered username and password is successful, we will be saving the JSON Web Token, which we are adding the Authorization Header for JWT authentication in the session.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators'; export class User{ constructor( public status:string, ) {} } export class JwtResponse{ constructor( public jwttoken:string, ) {} } @Injectable({ providedIn: 'root'
export class AuthenticationService { constructor( private httpClient:HttpClient ) { } authenticate(username, password) { return<any>('http://localhost:8080/authenticate',{username,password}).pipe( map( userData => { sessionStorage.setItem('username',username); let tokenStr= 'Bearer '+userData.token; sessionStorage.setItem('token', tokenStr); return userData; } ) ); } isUserLoggedIn() { let user = sessionStorage.getItem('username') //console.log(!(user === null)) return !(user === null) } logOut() { sessionStorage.removeItem('username') }

Next, we will be modifying the HttpInterceptor service called BasicAuthInterceptor Service. This service checks if the session has a valid username and token string, then it will update the headers of all outgoing HTTP requests. We implement the interceptor by extending the HttpInterceptor.

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
import { AuthenticationService } from './authentication.service'; @Injectable({ providedIn: 'root'
export class BasicAuthHtppInterceptorService implements HttpInterceptor { constructor() { } intercept(req: HttpRequest<any>, next: HttpHandler) { if (sessionStorage.getItem('username') && sessionStorage.getItem('token')) { req = req.clone({ setHeaders: { Authorization: sessionStorage.getItem('token') } }) } return next.handle(req); }

Now if we go to localhost:4200/login, we need to log in using the credentials -username =’javainuse’ ,password=’password’. User will be authenticated using basic authentication and forwarded to the employees page. 

angular 7 login page

angular 7 login success

Happy authenticating!

This article was originally published here