How to Build a Simple Spring Boot Application with User Authentication and Protected REST APIs

Modern web applications often require user authentication to protect sensitive data and functionality. Whether you are building an internal business application, a customer portal, or a SaaS platform, securing your REST APIs is one of the first steps toward creating a reliable solution.

In this tutorial, we will demonstrate how to create a simple Spring Boot application that:

  • Creates user accounts
  • Stores users in a database
  • Secures endpoints using Spring Security
  • Allows public access to selected endpoints
  • Restricts access to authenticated users only

This guide is written for beginners and provides a straightforward introduction to authentication in Spring applications.


What Is Spring Security?

Spring Security is a powerful framework that provides authentication, authorization, and protection against common security vulnerabilities.

With Spring Security, developers can:

  • Authenticate users
  • Manage user roles and permissions
  • Protect REST APIs
  • Implement login functionality
  • Secure web applications

It integrates seamlessly with Spring Boot and is considered the standard security framework for Java enterprise applications.


Application Architecture

Our sample application contains the following components:

User Entity

Represents users stored in the database.

User Repository

Handles database operations for user accounts.

Security Configuration

Defines which endpoints require authentication.

REST Controller

Provides API endpoints for creating and retrieving users.

Database

Stores user information securely.


Project Dependencies

A typical Maven project includes the following dependencies:

  • Spring Boot Starter Web
  • Spring Boot Starter Security
  • Spring Boot Starter Data JPA
  • H2 Database (or MySQL, PostgreSQL, Oracle, etc.)

These dependencies provide:

  • REST API support
  • Authentication and authorization
  • Database persistence
  • Embedded database for testing

Creating the User Entity

The user entity typically contains:

FieldDescription
IDUnique user identifier
UsernameLogin name
PasswordEncrypted password

Example structure:

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue
    private Long id;

    private String username;

    private String password;
}

The entity is mapped to a database table and represents each registered user.


Creating the Repository

Spring Data JPA simplifies database access through repositories.

Example:

public interface UserRepository
        extends JpaRepository<User, Long> {

    User findByUsername(String username);
}

This repository automatically provides:

  • Insert operations
  • Updates
  • Deletes
  • Searches
  • Pagination

without requiring manual SQL statements.


Configuring Security

The security configuration determines which endpoints are public and which require authentication.

Typical requirements:

Public Endpoints

Accessible without login:

/api/public/**

Protected Endpoints

Accessible only after authentication:

/api/users/**

Example configuration:

http
    .authorizeHttpRequests(auth -> auth
        .requestMatchers("/api/public/**").permitAll()
        .anyRequest().authenticated()
    )
    .httpBasic();

This setup enables HTTP Basic Authentication for simplicity.


Password Encryption

Passwords should never be stored as plain text.

Spring Security provides the BCryptPasswordEncoder:

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

When creating a user:

user.setPassword(
    passwordEncoder.encode(user.getPassword())
);

Benefits include:

  • Strong hashing
  • Salt generation
  • Protection against password theft

Creating a User Registration Endpoint

A public endpoint allows new users to register.

Example:

@PostMapping("/public/users")
public User createUser(
        @RequestBody User user) {

    user.setPassword(
        passwordEncoder.encode(
            user.getPassword()));

    return userRepository.save(user);
}

Users can submit:

{
  "username":"john",
  "password":"secret123"
}

The application stores the encrypted password in the database.


Creating Protected Endpoints

A protected endpoint requires authentication.

Example:

@GetMapping("/users/{id}")
public User getUser(
        @PathVariable Long id) {

    return userRepository.findById(id)
                         .orElse(null);
}

Unauthenticated requests receive:

401 Unauthorized

Authenticated users receive the requested data.


Testing Authentication

Access Public Endpoint

curl -X POST \
http://localhost:8080/api/public/users

No authentication is required.

Access Protected Endpoint

curl -u user:password \
http://localhost:8080/api/users/1

Authentication credentials must be supplied.


Benefits of Securing APIs

Implementing authentication provides several advantages:

Improved Security

Prevents unauthorized access.

User Accountability

Every action can be traced to a specific user.

Regulatory Compliance

Helps meet security requirements and standards.

Data Protection

Protects sensitive information from unauthorized users.

Scalability

Creates a foundation for future role-based access control.


Common Enhancements

As applications grow, developers typically add:

JWT Authentication

Stateless authentication using JSON Web Tokens.

Role-Based Authorization

Examples:

  • ADMIN
  • USER
  • MANAGER

OAuth2 Integration

Login using:

  • Google
  • Microsoft
  • GitHub
  • Apple

Refresh Tokens

Maintain secure user sessions.

Multi-Factor Authentication

Additional security through verification codes or authenticator apps.


Common Mistakes to Avoid

Storing Plain Text Passwords

Always hash passwords before saving them.

Exposing Sensitive Data

Never return passwords through APIs.

Disabling Security in Production

Avoid using insecure configurations outside development environments.

Missing Authorization Rules

Authentication alone may not be sufficient. Sensitive operations should also verify user permissions.


Conclusion

Spring Boot and Spring Security provide a simple yet powerful foundation for building secure web applications. By combining user management, password encryption, database persistence, and endpoint protection, developers can quickly create applications that authenticate users and safeguard sensitive functionality.

Starting with basic authentication allows developers to understand the fundamentals before moving to advanced techniques such as JWT tokens, OAuth2 integration, role-based access control, and enterprise-grade identity management. A well-designed security architecture established early in a project can significantly improve maintainability, compliance, and overall application security.

 

This article is inspired by real-world challenges we tackle in our projects. If you're looking for expert solutions or need a team to bring your idea to life,

Let's talk!

    Please fill your details, and we will contact you back

      Please fill your details, and we will contact you back