Skip to main content

BezKoder

  • Courses
  • Full Stack
  • Spring
  • Node
  • Vue
  • Angular
  • React
  • Firebase
  • Django
  • Dart
  • JsonFormatter
  • Categories

Angular 15 + Spring Boot: JWT Authentication & Authorization example

Last modified: December 20, 2022 bezkoder Angular, Full Stack, Security, Spring

In this tutorial, I will show you how to build a full stack Angular 15 + Spring Boot Login and Registration with JWT example. The back-end server uses Spring Boot with Spring Security for JWT Authentication & Role based Authorization, Spring Data JPA for interacting with database. The front-end will be built using Angular 15 with HttpInterceptor & Form validation.

Related Posts:
– Angular 15 + Spring Boot: File upload/download example
– Spring Boot JWT Auth with MySQL/PostgreSQL
– Spring Boot JWT Auth with MongoDB

Fullstack CRUD Application:
– Angular 15 + Spring Boot + H2 example
– Angular 15 + Spring Boot + MySQL example
– Angular 15 + Spring Boot + PostgreSQL example
– Angular 15 + Spring Boot + MongoDB example

Contents

  • Overview
    • Screenshots
    • Demo
  • Flow for Authentication and Authorization
  • Spring Boot & Spring Security for Back-end
    • Overview
    • Technology
    • Project Structure
    • Implementation
  • Angular 15 for Front-end
    • Overview
    • Technology
    • Project Structure
    • Implementation
  • Source Code
  • Conclusion
  • Further Reading

Angular 15 + Spring Boot JWT Authentication example

It will be a full stack, with Spring Boot for back-end and Angular 15 for front-end. The system is secured by Spring Security with JWT for Authentication and Authorization.

  • User can signup new account, login with username & password.
  • Role based Authorization (admin, moderator, user).
  • Store JWT in HttpOnly Cookies.

Screenshots

Here are UI screenshots of our system.

– Anyone can access a public page before logging in:

angular-15-spring-boot-jwt-authentication-public-access

– New user registration:

angular-15-spring-boot-jwt-authentication-registration

– Signup Form Validation:

angular-15-spring-boot-jwt-authentication-form-validation

More details about Form Validation at:
– Angular 15 Template Driven Forms Validation example
– Angular 15 Reactive Forms Validation example

– After signup is successful, User can login:

angular-15-spring-boot-jwt-authentication-login

-Now User can access Profile page/ User page:

angular-15-spring-boot-jwt-authorization

– HttpOnly Cookie sent automatically with HTTP Request:

angular-15-spring-boot-jwt-auth-httponly-cookie

– This is UI for mod:

angular-15-spring-boot-jwt-authentication-authorization

– If a User who doesn’t have Admin role tries to access Admin Board page:

angular-15-spring-boot-jwt-authentication-authorization-403

Demo

This is full Angular + Spring Boot JWT authentication demo (with form validation, check signup username/email duplicates, test authorization with 3 roles: Admin, Moderator, User).

In the video, we use Angular 10 and HTTP Authorization Header, but logic and UI are the same as this Angular version 15 and HttpOnly Cookie.

Flow for Authentication and Authorization

The diagram shows flow for User Registration process and User Login process.

angular-15-spring-boot-jwt-authentication-authorization-flow

It’s not too difficult to understand. We have 3 endpoints for authentication:

  • api/auth/signup for User Registration
  • api/auth/signin for User Login
  • api/auth/signout for User Logout

This Angular Client uses JWT in Cookies while sending request to protected resources (Authorization).

Spring Boot & Spring Security for Back-end

Overview

Our Spring Boot Application can be summarized in the diagram below:

angular-15-spring-boot-jwt-authentication-authorization-server-architecture

Now I will explain it briefly.

Spring Security

– WebSecurityConfig is the crux of our security implementation. It configures cors, csrf, session management, rules for protected resources. We can also extend and customize the default configuration that contains the elements below.
(WebSecurityConfigurerAdapter is deprecated from Spring 2.7.0, you can check the source code for update. More details at:
WebSecurityConfigurerAdapter Deprecated in Spring Boot)

– UserDetailsService interface has a method to load User by username and returns a UserDetails object that Spring Security can use for authentication and validation.

– UserDetails contains necessary information (such as: username, password, authorities) to build an Authentication object.

– UsernamePasswordAuthenticationToken gets {username, password} from login Request, AuthenticationManager will use it to authenticate a login account.

– AuthenticationManager has a DaoAuthenticationProvider (with help of UserDetailsService & PasswordEncoder) to validate UsernamePasswordAuthenticationToken object. If successful, AuthenticationManager returns a fully populated Authentication object (including granted authorities).

– OncePerRequestFilter makes a single execution for each request to our API. It provides a doFilterInternal() method that we will implement parsing & validating JWT, loading User details (using UserDetailsService), checking Authorizaion (using UsernamePasswordAuthenticationToken).

– AuthenticationEntryPoint will catch authentication error.

Repository contains UserRepository & RoleRepository to work with Database, will be imported into Controller.

Controller receives and handles request after it was filtered by OncePerRequestFilter.

– AuthController handles signup/login requests

– TestController has accessing protected resource methods with role based validations.

Understand the architecture deeply and grasp the overview more easier:
Spring Boot Architecture for JWT with Spring Security

Technology

To implement the server with concept above, we will use:

  • Java 8
  • Spring Boot 2 (with Spring Security, Spring Web, Spring Data JPA)
  • jjwt 0.9.1
  • PostgreSQL/MySQL/H2 – embedded database
  • Maven 3.6.1

Project Structure

The structure of Spring Boot back-end project is pretty complicated:

angular-15-spring-boot-jwt-authentication-authorization-server-project

security: we configure Spring Security & implement Security Objects here.

  • WebSecurityConfig
  • UserDetailsServiceImpl implements UserDetailsService
  • UserDetailsImpl implements UserDetails
  • AuthEntryPointJwt implements AuthenticationEntryPoint
  • AuthTokenFilter extends OncePerRequestFilter
  • JwtUtils provides methods for generating, parsing, validating JWT

controllers handle signup/login requests & authorized requests.

  • AuthController: @PostMapping(‘/signup’), @PostMapping(‘/signin’), @PostMapping(‘/signout’)
  • TestController: @GetMapping(‘/api/test/all’), @GetMapping(‘/api/test/[role]’)

repository has interfaces that extend Spring Data JPA JpaRepository to interact with Database.

  • UserRepository extends JpaRepository<User, Long>
  • RoleRepository extends JpaRepository<Role, Long>

models defines two main models for Authentication (User) & Authorization (Role). They have many-to-many relationship.

  • User: id, username, email, password, roles
  • Role: id, name

payload defines classes for Request and Response objects

We also have application.properties for configuring Spring Datasource, Spring Data JPA and App properties (such as JWT Secret string or Token expiration time).

Implementation and Source code

You can find steps to implement this Spring Boot – Spring Security App (with Github) in the post:
Spring Boot JWT Auth example with JWT and H2 Database

For working with MySQL/PostgreSQL:
Spring Boot JWT Auth example with JWT and MySQL/PostgreSQL

Or MongoDB:
Spring Boot JWT Auth example with MongoDB

Before running the backend server, you need to add minor configuration:

/* In AuthController.java */
// @CrossOrigin(origins = "*", maxAge = 3600)
@CrossOrigin(origins = "http://localhost:8081", maxAge = 3600, allowCredentials="true")

/* In TestController.java */
// @CrossOrigin(origins = "*", maxAge = 3600)
@CrossOrigin(origins = "http://localhost:8081", maxAge = 3600, allowCredentials="true")

Angular 15 for Front-end

Overview

Our Angular 15 App can be summarized in component diagram below:

angular-15-spring-boot-jwt-authentication-authorization-client-overview

Let’s try to understand it right now.

– The App component is a container using Router. It gets user user information from Browser Session Storage via storage.service. Then the navbar now can display based on the user login state & roles.

– Login & Register components have form for submission data (with support of Form Validation). They use storage.service for checking state and auth.service for sending signin/signup requests.

– auth.service uses Angular HttpClient ($http service) to make authentication requests.
– every HTTP request by $http service will be inspected and transformed before being sent by auth-interceptor.

– Home component is public for all visitor.

– Profile component get user data from Session Storage.

– BoardUser, BoardModerator, BoardAdmin components will be displayed depending on roles from Session Storage. In these components, we use user.service to get protected resources from API (with JWT in HttpOnly Cookie).

Technology

  • Angular 15
  • RxJS 7
  • Angular CLI 15
  • Bootstrap 4

Project Structure

This is the folder structure of our Angular front-end project:

angular-15-spring-boot-jwt-authentication-authorization-client-project

You can understand it properly without any explanation because we’ve looked at the overview before.

Implementation and Source code

You can find steps implement this Angular 15 Client (with Github) in the post:
Angular 15 JWT Authentication & Authorization example

Further Reading

  • Spring Boot: Spring Security
  • In-depth Introduction to JWT-JSON Web Token

Fullstack CRUD Application:
– Angular + Spring Boot + H2 example
– Angular + Spring Boot + MySQL example
– Angular + Spring Boot + PostgreSQL example
– Angular + Spring Boot + MongoDB example

Source Code

The complete source code for this tutorial can be found at Spring Boot + Angular Github.

Conclusion

Now we have an overview of Angular 15 Spring Boot Authentication and Role based Authorization example using JWT, Spring Security, Angular HttpInterceptor along with flow for signup/login actions.

We also take a look at Spring Boot server architecture for JWT Authentication using Spring Sercurity & Spring Data JPA, as well as Angular project structure for building a front-end app working with JWT.

Next tutorials will show you more details about how to implement this interesting system (with Github):
– Back-end:

  • Using H2 (Embedded Database)
  • Using MySQL/PostgreSQL
  • Using MongoDB

– Front-end: Angular 15 JWT Authentication & Authorization example

Happy learning, see you again!

angular angular 15 authentication authorization httponly cookie jwt login registration security spring boot spring security token based authentication

Post navigation

Spring Boot + Angular 15 example: CRUD (full stack)
Spring Boot + Angular 15 + MySQL: CRUD example
Buy me a coffee

Follow us

  • Facebook
  • Youtube
  • Github

Tools

  • Json Formatter
  • .
  • Privacy Policy
  • Contact
  • About
DMCA.com Protection Status © 2019-2022 bezkoder.com
X