DEV Community

Cover image for Spring Boot Login example
Tien Nguyen
Tien Nguyen

Posted on • Edited on

Spring Boot Login example

In this tutorial, we're gonna build a Spring Boot Login and Registration example (Rest API) that supports JWT with HttpOnly Cookies. You'll know:

  • Appropriate Flow for User Login and Registration with JWT and Cookies
  • Spring Boot Rest Api Architecture with Spring Security
  • How to configure Spring Security to work with JWT
  • How to define Data Models and association for Authentication and Authorization
  • Way to use Spring Data JPA to interact with MySQL Database

Full Article: Spring Boot Login example with JWT and MySQL

Overview of Spring Boot Login example

We will build a Spring Boot application in that:

  • User can signup new account (registration), or login with username & password.
  • By User's role (admin, moderator, user), we authorize the User to access resources.

These are APIs that we need to provide:

Methods Urls Actions
POST /api/auth/signup signup new account
POST /api/auth/signin login an account
POST /api/auth/signout logout the account
GET /api/test/all retrieve public content
GET /api/test/user access User's content
GET /api/test/mod access Moderator's content
GET /api/test/admin access Admin's content

The database we will use is MySQL by configuring project dependency & datasource.

Flow of Spring Boot Login and Registration example

The diagram shows flow of how we implement User Registration, User Login and Authorization process.

spring-boot-login-example-jwt-mysql-flow

A legal JWT must be stored in Cookies if Client accesses protected resources.

You will need to implement Refresh Token:

spring-boot-refresh-token-jwt-example-flow

More details at: Spring Boot Refresh Token with JWT example

Spring Boot Rest API Server Architecture with Spring Security

You can have an overview of our Spring Boot Login example with the diagram below:

spring-boot-login-example-jwt-mysql-spring-security-architecture

Now I will explain it briefly.

Spring Security

  • WebSecurityConfigurerAdapter is the crux of our security implementation. It provides HttpSecurity 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.

  • 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

  • Java 8
  • Spring Boot 2.6.1 (with Spring Security, Spring Web, Spring Data JPA)
  • jjwt 0.9.1
  • MySQL
  • Maven 3.6.1

Project Structure

This is folders & files structure for our Spring Boot Login example:

spring-boot-login-example-jwt-project-structure

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('/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 MySQL 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).

For step by step instruction and Github, please visit:
Spring Boot Login example with JWT and MySQL

Further Reading

Related Posts:

Deployment:

Fullstack CRUD App:

If you need a working front-end for this back-end, you can find Client App in the posts:
(just modify using Local Storage to HttpOnly Cookies)

Top comments (1)

Collapse
 
making profile image
Toshiaki Maki

You don't need to implement AuthTokenFilter
Spring Security has the same filter
docs.spring.io/spring-security/ref...

Here is an example
github.com/making/demo-jwt