Spring Security Explained for Beginners with Real Examples

Security is one of the most important requirements of modern web applications. Without proper security controls, unauthorized users may access sensitive information and business functionality.


Spring Security is the official security framework for Spring applications that provides authentication, authorization and protection against common security threats.


What is Spring Security?

Spring Security is a framework that helps secure Spring applications.

It provides:

  • Authentication
  • Authorization
  • Password Protection
  • CSRF Protection
  • Session Management
  • Role-Based Access Control

Why Do We Need Spring Security?

Imagine an online banking application.

Without security:



Anyone
      |
      v
View Accounts

Transfer Money

Access Customer Data

Clearly this is dangerous.

Spring Security ensures only authorised users can access sensitive resources.


Authentication vs Authorization

These terms are frequently confused.


Authentication

Authentication answers:


Who are you?

Example:



Username:
admin

Password:
secret123

Spring verifies the identity of the user.


Authorization

Authorization answers:


What are you allowed to do?

Example:



ADMIN
    |
    +---- Create User

    +---- Delete User

USER
    |
    +---- View Profile

After authentication, Spring determines permissions.


Spring Security Flow


User Request
      |
      v
Security Filter Chain
      |
      v
Authentication
      |
      v
Authorization
      |
      v
Controller

Every incoming request passes through Spring Security.


Add Spring Security Dependency

Add the following dependency to pom.xml.



<dependency>

    <groupId>
        org.springframework.boot
    </groupId>

    <artifactId>
        spring-boot-starter-security
    </artifactId>

</dependency>

What Happens After Adding Dependency?

Spring Boot automatically secures all endpoints.

When you start the application, a generated password appears in the console.



Using generated security password:

8c3f1c9d-xxxx-yyyy-zzzz

This default user can access the application.


Securing an API


@RestController

@RequestMapping("/api")
public class EmployeeController {

    @GetMapping("/employees")
    public String employees() {

        return "Employees Data";

    }
}

After adding Spring Security, authentication is required automatically.


Configure In-Memory Users


@Bean

public UserDetailsService
userDetailsService() {

    UserDetails admin =

        User.builder()

            .username("admin")

            .password(
                passwordEncoder()
                    .encode("admin123")
            )

            .roles("ADMIN")

            .build();

    return new InMemoryUserDetailsManager(
        admin
    );
}

This creates a simple in-memory administrator account.


Password Encoding

Passwords should never be stored as plain text.



@Bean

public PasswordEncoder
passwordEncoder() {

    return new BCryptPasswordEncoder();

}

BCrypt is one of the most commonly used password encoders.


Role-Based Security

Spring Security supports roles.


ADMIN

USER

MANAGER

Endpoints can be restricted to specific roles.


.authorizeHttpRequests(

    auth -> auth

        .requestMatchers(
            "/admin/**"
        )

        .hasRole("ADMIN")

)

Only ADMIN users can access those endpoints.


SecurityFilterChain Configuration


@Bean

public SecurityFilterChain
securityFilterChain(
    HttpSecurity http
) throws Exception {

    http

        .authorizeHttpRequests(

            auth -> auth

                .anyRequest()

                .authenticated()

        )

        .formLogin();

    return http.build();

}

This tells Spring Security to require authentication for all requests.


Common Security Features

  • Authentication
  • Authorization
  • Password Encryption
  • Session Management
  • CSRF Protection
  • Role Management

Real World Example

Consider an e-commerce application.



Customer
      |
      +---- View Products

Admin
      |
      +---- Add Products

      +---- Remove Products

      +---- Manage Orders

Different users have different access levels.

Spring Security manages these permissions.


Common Interview Questions

What is Spring Security?

A framework that provides authentication and authorization for Spring applications.


What is Authentication?

Authentication verifies the identity of a user.


What is Authorization?

Authorization determines what a user is allowed to do.


What is SecurityFilterChain?

A component that defines security rules for incoming requests.


Why use BCryptPasswordEncoder?

To securely store encrypted passwords instead of plain text passwords.


Best Practices

  • Always encrypt passwords.
  • Use role-based access control.
  • Never store passwords in plain text.
  • Secure sensitive endpoints.
  • Apply the principle of least privilege.

Frequently Asked Questions (FAQ)

Does Spring Boot provide Security automatically?

Yes. Adding Spring Security dependency automatically secures endpoints.


Can Spring Security work with JWT?

Yes. JWT is commonly used in modern REST APIs.


Can Spring Security secure REST APIs?

Yes. It is widely used to secure RESTful applications.


Conclusion

Spring Security is the standard framework for securing Spring Boot applications. Understanding Authentication, Authorization, SecurityFilterChain, Password Encoding and Role-Based Access Control provides a strong foundation for building secure enterprise applications.


Keywords

Spring Security Tutorial, Spring Security Basics, Spring Boot Security, Authentication vs Authorization, SecurityFilterChain, BCryptPasswordEncoder, Spring Boot Authentication, Spring Boot Authorization, Spring Security Interview Questions, Spring Boot REST Security, Role Based Access Control, Secure Spring Boot APIs, Java Backend Security, Spring Framework Security, Enterprise Java Security

Spring Security Explained for Beginners with Real Examples Spring Security Explained for Beginners with Real Examples Reviewed by 13thGhost on 12:19 PM Rating: 5

Recommended Posts

Powered by Blogger.