Spring Security Basics Explained with Real-Time Examples | Authentication, Authorization, and Security Configuration

Introduction :

While developing Spring Boot REST APIs, I quickly realized that creating APIs is only half the job. The other half is ensuring that only authorized users can access them.

For example, imagine an Employee Management System. If someone knows the API URL, they should not be able to view employee information, update records, or delete data without proper permissions.

Similarly, in banking applications, customer account details should only be accessible to authenticated users. In e-commerce platforms, only administrators should be allowed to manage products and orders.

This is where Spring Security becomes important.

Spring Security is one of the most widely used security frameworks in the Java ecosystem. It helps developers secure applications by providing authentication, authorization, password encryption, session management, and protection against common security vulnerabilities.

In this article, I will explain the fundamentals of Spring Security using simple examples and practical scenarios based on real-world application development.




What is Spring Security?

Spring Security is a powerful and highly customizable framework used to secure Spring applications.

It provides built-in support for:

  • User Authentication

  • Authorization

  • Password Encryption

  • Session Management

  • CSRF Protection

  • Secure HTTP Configuration

  • Integration with JWT and OAuth2

Instead of writing custom security code from scratch, developers can use Spring Security to implement industry-standard security practices quickly and efficiently.


Why Do We Need Security?

Consider the following API:

@GetMapping("/employees")
public List<Employee> getEmployees() {
    return employeeService.getAllEmployees();
}

Without any security configuration, anyone who knows the endpoint URL can access employee information.

In real-world applications, this can lead to serious security risks such as:

  • Unauthorized access to sensitive data

  • Data modification by unauthorized users

  • Exposure of confidential business information

  • Compliance and privacy violations

To prevent such issues, applications must verify user identity and control what resources users can access.

This is achieved through Authentication and Authorization.


Authentication vs Authorization

One of the most frequently asked Spring Security interview questions is:

What is the difference between Authentication and Authorization?

Authentication (Who Are You?)

Authentication is the process of verifying a user's identity.

For example:

  • User enters username and password.
  • Application validates the credentials.
  • If valid, the user is authenticated.

Think of entering an office building.

Before allowing entry, the security guard checks your ID card to verify your identity.

This verification process is called Authentication.


Authorization (What Can You Access?)

Authorization occurs after successful authentication.

Once the application knows who you are, it determines what resources and actions you are allowed to access.

Example:

RolePermissions
Admin        Create, Update, Delete
Manager        View and Update
Employee         View Only

The user is already authenticated.

The system now decides what actions the user can perform.

This process is called Authorization.


Real-Time Banking Application Example :

Consider an Internet Banking Application.

Step 1: Authentication

The customer enters:

  • Username

  • Password

Spring Security verifies the credentials.

If the credentials are valid, the customer is authenticated.

Step 2: Authorization

After successful login:

  • Customer can view account details.

  • Customer can transfer funds.

  • Bank Employee can process transactions.

  • Administrator can manage user accounts.

This demonstrates how Authentication and Authorization work together in a real-world application.


Adding Spring Security Dependency

To enable Spring Security, add the following dependency to your project.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

After adding the dependency and restarting the application, Spring Security automatically secures all endpoints.


What Happens After Adding Spring Security?

When I first added Spring Security to a Spring Boot application, I noticed that all APIs suddenly required authentication.

The application logs displayed something similar to:

Using generated security password:
8f3b2f1d-xxxx-xxxx-xxxx-xxxxxxxx

Spring Security automatically creates:

  • Username: user

  • Generated Password

  • Default Login Page

This default configuration is useful for learning and testing purposes.


Creating Sample APIs

@RestController
@RequestMapping("/api")
public class DemoController {

    @GetMapping("/public")
    public String publicApi() {
        return "Public API";
    }

    @GetMapping("/admin")
    public String adminApi() {
        return "Protected API";
    }
}

Goal:

  • Anyone can access /api/public

  • Only authenticated users can access /api/admin


Security Configuration Using SecurityFilterChain

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(
            HttpSecurity http) throws Exception {

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

        return http.build();
    }
}
Here :
crsf
means
Cross-Site Request Forgery

Understanding the Configuration

permitAll()

.requestMatchers("/api/public")
.permitAll()

Allows anyone to access the endpoint without authentication.

authenticated()

.anyRequest()
.authenticated()

Requires authentication for all remaining endpoints.

httpBasic()

.httpBasic()

Enables Basic Authentication using username and password.


Password Encryption Using BCrypt

One of the biggest mistakes developers make is storing passwords as plain text.

Spring Security provides BCryptPasswordEncoder to securely hash passwords.

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

Benefits:

  • Passwords are stored as hashes.

  • Original passwords cannot be retrieved easily.

  • Industry-standard security practice.


Testing APIs Using Postman

Public API

GET /api/public

Response:

Public API

No authentication required.

Protected API

GET /api/admin

Without credentials:

401 Unauthorized

With valid credentials:

Protected API

This confirms that Spring Security is successfully protecting application endpoints.


Common Mistakes Beginners Make

Forgetting Default Security

After adding Spring Security, all APIs become secured by default.

Many beginners assume their APIs are broken when authentication prompts start appearing.

Disabling Security Completely

Some developers disable security during development and forget to re-enable it before deployment.

This creates serious security risks.

Storing Plain Text Passwords

Passwords should always be encrypted using BCrypt or another secure hashing algorithm.


Spring Security Interview Questions

1. What is Spring Security?

Spring Security is a framework used to secure Spring applications through authentication, authorization, encryption, and protection against security threats.

2. What is the difference between Authentication and Authorization?

Authentication verifies user identity, while Authorization determines what resources an authenticated user can access.

3. What is SecurityFilterChain?

SecurityFilterChain is the modern approach used to configure Spring Security rules and endpoint access.

4. Why is BCryptPasswordEncoder used?

It securely hashes passwords before storing them in the database.

5. What happens after adding Spring Security dependency?

Spring Security automatically secures all endpoints and generates a default username and password.


Conclusion :

Spring Security is one of the most important frameworks in the Spring ecosystem. Understanding Authentication and Authorization is the first step toward building secure and enterprise-ready applications.

In this article, we explored the fundamentals of Spring Security, understood how authentication and authorization work, configured basic endpoint security, and learned password encryption using BCrypt.

Although this example uses Basic Authentication, modern applications typically use JWT Authentication for stateless and scalable security.

In the next article, we will learn how to generate JWT tokens, validate incoming requests, and secure REST APIs using token-based authentication.

Comments

Popular posts from this blog

React Basics – How to Create Component

How to Build REST API using Spring Boot (Step-by-Step Guide)

Spring Boot @RequestParam Annotation Explained with Real-Time Examples