DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Authentication With Remote LDAP Server in Spring Web MVC
  • How to Implement Two-Factor Authentication in a Spring Boot OAuth Server? Part 1: Configuration
  • Angular JWT Autorefresh With Spring Boot
  • Authentication with Spring Boot and Spring Security — JWT and Postgres

Trending

  • Teradata Performance and Skew Prevention Tips
  • Microsoft Azure Synapse Analytics: Scaling Hurdles and Limitations
  • Understanding Java Signals
  • Solid Testing Strategies for Salesforce Releases
  1. DZone
  2. Coding
  3. Frameworks
  4. Angular 7 + Spring Boot JWT Authentication Example

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.

By 
Rida Shaikh user avatar
Rida Shaikh
·
Jun. 14, 19 · Tutorial
Likes (15)
Comment
Save
Tweet
Share
102.5K Views

Join the DZone community and get the full member experience.

Join For Free

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!

Spring Framework Spring Boot authentication JWT (JSON Web Token) AngularJS

Published at DZone with permission of Rida Shaikh. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Authentication With Remote LDAP Server in Spring Web MVC
  • How to Implement Two-Factor Authentication in a Spring Boot OAuth Server? Part 1: Configuration
  • Angular JWT Autorefresh With Spring Boot
  • Authentication with Spring Boot and Spring Security — JWT and Postgres

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!