Spring Security Tutorial for Beginners
Introduction
Security is one of the most important aspects of modern web applications. Whether you're building a REST API, an e-commerce platform, or an enterprise application, protecting your resources from unauthorized access is essential.
Spring Security is the official security framework for the Spring ecosystem. It provides powerful features such as authentication, authorization, password encryption, session management, CSRF protection, and secure API access.
In this tutorial, you'll learn the fundamentals of Spring Security in Spring Boot with practical examples.
What is Spring Security?
Spring Security is a framework that helps secure Spring-based applications by handling authentication and authorization.
It provides built-in protection for common security concerns and integrates seamlessly with Spring Boot.
Spring Security Features
- Authentication
- Authorization
- Password Encryption
- CSRF Protection
- Session Management
- Secure REST APIs
- Login & Logout Support
- Role-Based Access Control (RBAC)
Authentication vs Authorization
Many beginners confuse these two concepts.
| Authentication | Authorization |
|---|---|
| Verifies who the user is | Determines what the user can access |
| Login process | Permission checking |
| Username & Password | Roles & Privileges |
Example
- Authentication: User logs in with a username and password.
-
Authorization: The application checks whether the user has permission to access the
/adminpage.
How Spring Security Works
Client ↓ Security Filter Chain ↓ Authentication Manager ↓ User Details Service ↓ Database ↓ Response
The Security Filter Chain intercepts every incoming request before it reaches your controllers.
Add Spring Security Dependency
Add the following dependency to your pom.xml:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
Default Spring Security Behavior
After adding the dependency, Spring Boot automatically:
- Protects all endpoints
- Generates a default username
- Generates a temporary password
- Displays a default login page
Console example:
Using generated security password: 5d3e-87af-91ac...
Create a Security Configuration Class
Create a configuration class to customize security.
@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain( HttpSecurity http) throws Exception { http .csrf(csrf -> csrf.disable()) .authorizeHttpRequests(auth -> auth .requestMatchers("/public/**").permitAll() .anyRequest().authenticated()) .httpBasic(); return http.build(); } }
Understanding SecurityFilterChain
SecurityFilterChain is responsible for defining which requests are allowed and which require authentication.
In the example above:
-
/public/**is accessible to everyone. - All other endpoints require authentication.
Create an In-Memory User
For testing purposes:
@Bean public UserDetailsService userDetailsService() { UserDetails user = User.withUsername("admin") .password(passwordEncoder().encode("admin123")) .roles("ADMIN") .build(); return new InMemoryUserDetailsManager(user); }
Password Encryption
Never store plain-text passwords.
Use BCryptPasswordEncoder:
@Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }
BCrypt hashes passwords before storing them, making them much more secure.
Accessing a Protected API
Example endpoint:
@GetMapping("/employees") public List<Employee> getEmployees() { return service.findAll(); }
Without authentication:
401 Unauthorized
With valid credentials:
200 OK
Role-Based Authorization
Restrict access based on user roles.
.authorizeHttpRequests(auth -> auth .requestMatchers("/admin/**").hasRole("ADMIN") .requestMatchers("/user/**").hasAnyRole("USER", "ADMIN") .anyRequest().authenticated())
Common Security Annotations
| Annotation | Purpose |
|---|---|
@EnableWebSecurity | Enables Spring Security |
@Configuration | Marks a configuration class |
@Bean | Registers a Spring bean |
@PreAuthorize | Method-level security |
@Secured | Restricts access by role |
Security Flow Diagram
User Request ↓ Security Filter Chain ↓ Authentication ↓ Authorization ↓ Controller ↓ Service ↓ Database
Best Practices
- Use HTTPS in production.
- Always encrypt passwords with BCrypt.
- Never hardcode credentials.
- Apply the principle of least privilege.
- Keep Spring Boot and Spring Security dependencies updated.
Common Mistakes
Storing Plain-Text Passwords
Always hash passwords before saving them.
Disabling Security Completely
Only disable features like CSRF when appropriate for your application.
Using Weak Passwords
Require strong passwords for all user accounts.
Interview Questions
What is Spring Security?
Spring Security is a framework that provides authentication, authorization, and protection for Spring applications.
What is the difference between authentication and authorization?
Authentication verifies identity, while authorization determines permissions.
Why use BCrypt?
BCrypt securely hashes passwords and protects them from being stored in plain text.
What is SecurityFilterChain?
It defines how incoming HTTP requests are secured.
FAQ
Does Spring Security work with REST APIs?
Yes. It is widely used to secure REST APIs.
Is Spring Security difficult to learn?
It has many features, but understanding authentication, authorization, and SecurityFilterChain provides a solid foundation.
Can I use Spring Security with JWT?
Yes. JWT authentication is one of the most common approaches for securing stateless REST APIs. We'll cover it in the next tutorial.
