Spring Boot Authentication and Authorization with MySQL – Part 1

Others
4 minutes read

Introduction

Spring Boot is a popular Java framework for building web applications. It provides a fast and easy way to create standalone, production-grade applications that can be deployed in various environments. 

One of the main advantages of Spring Boot is that it reduces the complexity of setting up and configuring a Spring-based application. It comes with a set of pre-configured components and tools, which makes it easier for developers to get started with Spring. With Spring Boot, developers can focus on writing business logic instead of spending time on boilerplate code and configuration. 

In this tutorial, we’ll explore the basics of Spring Boot and create a security-based application step-by-step.

Project’s Requirements

User registration

The application should allow users to register and create a new account. The registration process should include validation of the user’s input data, such as username, email, password, and role.

User login

The application should allow users to log in and access their accounts. The login process should include validation of the user’s credentials, such as username and password, and the creation of a token to maintain the user’s authentication.

Role-based access control

The application should restrict access to certain features based on the user’s role or permission level. For example, only administrators can access specific data.

APIs

These are the APIs that we need to provide:

MethodsUrlsActions
POST/api/auth/signupCreate new account
POST/api/auth/signinLogin to an account
GET/api/test/allRetrieve public content
GET/api/test/userAccess User’s content
GET/api/test/modAccess Moderator’s content
GET/api/test/adminAccess Admin’s content

Project Setup & Configuration

Install JDK

You need to install JDK (Java Development Kit) on your system to develop Java applications. You can download the latest version of JDK from the official Oracle website.

Install Maven

Maven is a build automation tool that helps manage project dependencies and build the project. You can download and install Maven from the official website.

Create a new Spring Boot project

To create a new Spring Boot project, you can use either Spring Initializr. This tool generates a basic Spring Boot project with the required dependencies.

Signup & Login with JWT Authentication Flow

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

NOTE: The JWT token must be added to HTTP Authorization Header if the client requests protected resources.

Spring Boot Server Architecture with Spring Security

The diagram below shows an overview of the overflow we will implement

Now, let me explain what’s happening here. The application consists of 3 parts, The spring security, controller, and repository parts.

Spring Security

WebSecurityConfig is the base of our security implementation. It configures CORS, CSRF, session management, and rules for protected resources. 

We can also extend and customize the default configuration that contains the elements below.

UserDetailsService has a method to load the user by user name and returns a user details object that Spring Security can use for authentication and validation.

UserDetails contains the necessary information (such as username, password, and authorities) to build an authentication object.

UsernamePasswordAuthenticationToken gets {username, password} from the login request, and 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 for parsing & validating JWT, loading User details (using UserDetailsService), and checking authorization (using UsernamePasswordAuthenticationToken).

AuthenticationEntryPoint will catch any authentication error.

Controller

The controller receives and handles requests after it was filtered by OncePerRequestFilter. Our application has 2 controllers. AuthController handles signup/login requests, and TestController has accessing protected resource methods with role-based validations.

Repository

Our project has 2 repositories, UserRepository & RoleRepository to work with Database, which will be imported into the controller.

Project Structure

This is the folders & files structure for our Spring Boot application

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(‘/signin’), @PostMapping(‘/signup’)
  • 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 user authentication & role authorization. They have a many-to-many relationship.

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

Payload

Defines classes for the request and response objects

Application.properties

For configuring a spring data source, Spring Data JPA and app properties (such as JWT Secret string or Token expiration time).

Conclusion

In part2 of the series, we will go through the implementation process in detail and test our application

Leave a Reply

Your email address will not be published. Required fields are marked *