Community for developers to learn, share their programming knowledge. Register!
User Authentication and Authorization

Setting Up Spring Boot Project for User Authentication


In this article, we will guide you through the process of setting up a Spring Boot project with a focus on user authentication and authorization. Whether you are looking to enhance your existing application or start a new one, this article serves as a training resource that covers all the necessary steps to implement secure user management. By the end, you will have a solid foundation to build upon.

Creating a New Spring Boot Application

To begin, let's create a new Spring Boot application. You can use the Spring Initializr, which is a web-based tool that simplifies the setup process. Navigate to Spring Initializr and configure your project settings as follows:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: Choose the latest stable version (e.g., 2.7.x)
  • Project Metadata:
    • Group: com.example
    • Artifact: user-auth
    • Name: user-auth
    • Package Name: com.example.userauth
    • Packaging: Jar
    • Java: 11 or later

Once you've filled in these details, add the necessary dependencies. For this project, we will initially require:

  • Spring Web
  • Spring Security
  • Spring Data JPA
  • H2 Database (for in-memory storage during development)

After configuring the dependencies, click on the Generate button to download the project as a ZIP file. Unzip the file and import it into your favorite IDE, such as IntelliJ IDEA or Eclipse.

Sample Project Structure

Once the project is imported, you will notice the typical Spring Boot structure:

user-auth
β”œβ”€β”€ src
β”‚   β”œβ”€β”€ main
β”‚   β”‚   β”œβ”€β”€ java
β”‚   β”‚   β”‚   └── com
β”‚   β”‚   β”‚       └── example
β”‚   β”‚   β”‚           └── userauth
β”‚   β”‚   β”‚               β”œβ”€β”€ UserAuthApplication.java
β”‚   β”‚   β”‚               └── config
β”‚   β”‚   β”‚               └── controller
β”‚   β”‚   β”‚               └── model
β”‚   β”‚   β”‚               └── repository
β”‚   β”‚   β”‚               └── service
β”‚   β”‚   └── resources
β”‚   β”‚       β”œβ”€β”€ application.properties
β”‚   β”‚       └── static
β”‚   β”‚       └── templates
└── pom.xml

Adding Necessary Dependencies for Security

To enable user authentication and authorization, we need to add a few more dependencies to our pom.xml file. Open the pom.xml file and include the following dependencies:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

Once you have added these dependencies, make sure to refresh your project to download the necessary JAR files.

Understanding Spring Security

Spring Security provides a comprehensive security framework that handles authentication and authorization. By default, it secures all endpoints and requires users to authenticate before accessing any resources. We will customize this behavior to suit our application's needs.

Configuring Application Properties for Security

Next, we will configure the application properties. Open the src/main/resources/application.properties file and add the following properties:

# H2 Database Configuration
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

# JPA Configuration
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true

These properties will set up an in-memory H2 database for development, allowing us to quickly test our application without the overhead of setting up an external database.

Customizing Security Configuration

To customize the security settings, create a new class named WebSecurityConfig in the config package:

package com.example.userauth.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user")
            .password(passwordEncoder().encode("password"))
            .roles("USER")
            .and()
            .withUser("admin")
            .password(passwordEncoder().encode("admin"))
            .roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/**").permitAll()
            .and()
            .formLogin()
            .permitAll()
            .and()
            .logout()
            .permitAll();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

Explanation of Configuration

In the above code, we have configured two users: one with the role of USER and another with the role of ADMIN. The configure(HttpSecurity http) method specifies that only users with the ADMIN role can access endpoints under /admin/**, while all other endpoints are accessible to everyone.

Summary

Setting up user authentication and authorization in a Spring Boot application is fundamental for building secure applications. By following the steps outlined in this article, you have learned how to create a Spring Boot project, add the necessary dependencies, and configure security settings to manage user access effectively.

With the foundation laid out, you can now delve deeper into Spring Security features such as JWT authentication, OAuth2, and more complex user management capabilities. By implementing these security measures, you can ensure that your application remains secure and user data is protected.

For additional resources and detailed documentation, consider checking the Spring Security Reference and Spring Boot Documentation.

Last Update: 28 Dec, 2024

Topics:
Spring Boot