Search Tutorials


Angular 7 + Spring Boot JWT Authentication | JavaInUse

Angular 7 + Spring Boot JWT Authentication Example

In previous tutorial we had implemented - Angular 7 + Spring Boot Basic Auth Using HTTPInterceptor Example to intercept all outgoing HTTP Requests and add basic authentication string to them. In this tutorial we will be modifying the application to perform authentication using JSON Web Token.
JWT httpinterceptor example

Angular 7+ Spring Boot - Table of Contents

Angular 7 + Spring Boot Application Hello World Example Angular 7 + Spring Boot Application CRUD Example Angular 7 + Spring Boot Application Login Example Angular 7 + Spring Boot Application Basic Authentication Example Angular 7 + Spring Boot Basic Auth Using HTTPInterceptor Example Angular 7 + Spring Boot JWT Authentication Hello World Example

Video

This tutorial is explained in the below Youtube Video.

Spring Boot + JWT Implementation

In a previous tutorial we had implemented Spring Boot + JWT Authentication Hello World Example. We will be modifying this project to add the TestController that we had implemented in 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 OPTIONS call in the Websecurity Config.These OPTIONS call are made by Angular application to 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 org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@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
		auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());
	}

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	@Bean
	@Override
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}

	@Override
	protected void configure(HttpSecurity httpSecurity) throws Exception {
		// We don't need CSRF for this example
		httpSecurity.csrf().disable()
				// dont authenticate this particular request
				.authorizeRequests().antMatchers("/authenticate").
				permitAll().antMatchers(HttpMethod.OPTIONS, "/**")
				.permitAll().
				// all other requests need to be authenticated
				anyRequest().authenticated().and().
				// make sure we use stateless session; session won't be used to
				// store user's state.
				exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
				.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 the previous 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 this.httpClient.post<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 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. Login using the credentials -username ='javainuse' ,password='password'. User will be authenticated using Basic Authentication and forwarded to employees page.
angular 7 login page

angular 7 login success

Download Source Code

Download it -
GITHUB- Angular 7 + JWT Authentication example code
Spring Boot + JWT Authentication code