{{announcement.body}}
{{announcement.title}}

Angular 7 + Spring Boot JWT Authentication Example

DZone 's Guide to

Angular 7 + Spring Boot JWT Authentication Example

Check out this post to learn more about implementing JSON Web Tokens with Spring Boot and Angular 7.

· Security Zone ·
Free Resource

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 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 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 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 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!

Topics:
spring boot ,spring security ,jwt ,jwt authentication ,angular 7 ,angular ,full stack development ,full stack ,hello world ,security

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}