πŸ“–
Maissen's Grimoire
  • Maissen's Grimoire
  • Html and css grimoire
    • HTML5 Periodical Table
    • HTML Cheat Sheet
    • CSS Cheatsheets
  • Javascript Grimoire
    • JavaScript Cheat Sheet
      • Javascript Array in depth
      • Tagged Template Literals
      • Guard Clauses - The Best Way To Write Complex Conditional Logic
      • JavaScript Optional Chaining
      • JavaScript Null Coalesce
      • What Are Magic Numbers And Why Are They Bad
      • ES6/ECMAScript2015 Cheatsheet
      • First-class and Higher Order Functions: Effective Functional JavaScript
    • Useful JavaScript Tips, Tricks and Best Practices
    • Bits of code
    • Useful JavaScript libraries
      • Components
      • Animation
      • Maps
      • Helpers
      • Presentations
      • Charts
      • Games
      • Audio
      • Images
      • Video
    • Js the right way
  • Angular Grimoire
    • Angular doc
    • Getting Started
    • Angular clean architecture
    • Angular Cheat Sheet
    • TypeScript Cheat Sheet
    • My Favorite Tips and Tricks in Angular
    • NgRx: tips & tricks
    • Bits of code
      • Execute Multiple HTTP Requests in Angular
      • Authentification
        • Angular 8 JWT Authentication with HttpInterceptor and Router
      • Integrations
        • Spring Boot
          • Rest Example
            • Angular,Spring Boot,Spring Data and Rest Example(CRUD)
          • Authentification
            • Angular, Spring Boot: JWT Authentication with Spring Security example
            • Angular Spring Boot Security Oauth2
              • Spring Boot OAUTH2 Role-Based Authorization
              • Spring Boot Security Google Oauth
              • Spring Security OAuth2 User Registration
    • Most used dependency
  • Node Grimoire
    • Express.js 4 Cheatsheet
    • Useful Dependencies
    • How To Use And Write Express Middleware
    • Node.js with SQL databases
      • Node.js Token Based Authentication & Authorization example
      • Node.js Rest APIs example with Express, Sequelize & MySQL
      • Node.js Express & PostgreSQL: CRUD Rest APIs example with Sequelize
      • Sequelize
        • Sequelize Many-to-Many Association example – Node.js & MySQL
        • Sequelize One-to-Many Association example with Node.js & MySQL
    • Node.js with NOSQL databases
      • Node.js + MongoDB: User Authentication & Authorization with JWT
      • Node.js, Express & MongoDb: Build a CRUD Rest Api example
      • MongoDB One-to-One relationship tutorial with Mongoose example
      • MongoDB One-to-Many Relationship tutorial with Mongoose examples
      • MongoDB Many-to-Many Relationship with Mongoose examples
  • Upload files
    • How to upload multiple files in Node.js
    • Upload & resize multiple images in Node.js using Express, Multer, Sharp
    • Upload/store images in MySQL using Node.js, Express & Multer
    • How to upload/store images in MongoDB using Node.js, Express & Multer
  • React Grimoire
    • React Doc
    • React Grimoire
    • React Cheat Sheet
  • spring boot Grimoire
    • Getting started
    • Spring Boot, Spring Data JPA – Rest CRUD API example
    • Spring Boot Token based Authentication with Spring Security & JWT
  • Mongo Grimoire
    • MongoDb-Mongoose Cheat Sheet
  • Development tools
    • Design Patterns
  • maissen_grimoire
Powered by GitBook
On this page
  • Flow for User Registration and User Login
  • Spring Boot & Spring Security for Back-end
  • Angular 8 for Front-end
  • Further Reading

Was this helpful?

  1. Angular Grimoire
  2. Bits of code
  3. Integrations
  4. Spring Boot
  5. Authentification

Angular, Spring Boot: JWT Authentication with Spring Security example

PreviousAuthentificationNextAngular Spring Boot Security Oauth2

Last updated 5 years ago

Was this helpful?

Flow for User Registration and User Login

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

spring-boot-authentication-jwt-spring-security-flow

I think it’s not too difficult to understand. We have 2 endpoints for authentication:

  • api/auth/signup for User Registration

  • api/auth/signin for User Login

If Client wants to send request to protected data/endpoints, a legal JWT must be added to HTTP Authorization Header.

Spring Boot & Spring Security for Back-end

Overview

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

Let me explain it.

Spring Security

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

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.

Technology

To implement the server with concept above, we will use: – Java 8 – Spring Boot 2.1.8.RELEASE (with Spring Security, Spring Web, Spring Data) – jjwt 0.9.1 – PostgreSQL/MySQL – Maven 3.6.1

Project Structure

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

You can see that there are 5 packages:

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

  • WebSecurityConfig extends WebSecurityConfigurerAdapter

  • 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(β€˜/signin’), @PostMapping(β€˜/signup’)

  • TestController: @GetMapping(β€˜/api/test/all’), @GetMapping(β€˜/api/test/[role]’)

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

  • UserRepository extends JpaRepository

  • RoleRepository extends JpaRepository

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

Angular 8 for Front-end

Overview

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

Let’s try to understand it right now.

– The App component is a container using Router. It gets user token & user information from Browser Session Storage via token-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 token-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.

Technology

– Angular 8 – RxJS 6

Project Structure

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

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

Implementation

Further Reading

spring-boot-authentication-spring-security-architecture

– is the crux of our security implementation. It provides configurations to configure cors, csrf, session management, rules for protected resources. We can also extend and customize the default configuration that contains the elements below.

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

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

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

– 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).

– will catch unauthorized error and return a 401 when Clients access protected resources without authentication.

spring-boot-authentication-spring-security-project-structure

You can find step by step to implement this Spring Boot – Spring Security App in the post:

angular-8-jwt-authentication-overview
angular-8-jwt-authentication-project-structure

You can find step by step to implement this Angular 8 App in the post:

WebSecurityConfigurerAdapter
HttpSecurity
UserDetailsService
UsernamePasswordAuthenticationToken
AuthenticationManager
OncePerRequestFilter
AuthenticationEntryPoint
Secure Spring Boot App with Spring Security & JWT Authentication
Angular 8 JWT Authentication with HttpInterceptor and Router
Angular 8 + Spring Boot: File upload example - BezKoderBezKoder
Logo