🔐 Spring Security Basics
Security is a critical concern in modern web applications. With the rise of distributed systems and microservices, securing applications has never been more important. Spring Security is a powerful and customizable authentication and access-control framework that is widely used in the Java ecosystem. In this post, we will explore the basics of Spring Security, how it works, and how to get started.
🚀 What is Spring Security?
Spring Security is a framework that provides authentication, authorization, and protection against common attacks. It is highly customizable and integrates seamlessly with the Spring ecosystem.
Key Features:
-
Authentication and authorization
-
Protection against CSRF, session fixation, and clickjacking
-
Integration with Spring MVC
-
OAuth2 and JWT support
🧰 Adding Spring Security to Your Project
Use Spring Initializr to bootstrap your project and include the Spring Security dependency.
Maven dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
🧪 Default Behavior
Once Spring Security is added, the application is secured by default:
-
All endpoints require authentication
-
A login page is provided at
/login
-
A default user is generated with a password printed in the console
🔑 Basic Authentication Example
@RestController
public class HelloController {
@GetMapping("/")
public String home() {
return "Welcome to the secured application!";
}
}
application.properties (optional password config):
spring.security.user.name=admin
spring.security.user.password=admin123
Navigate to http://localhost:8080
and log in with the configured credentials.
⚙️ Custom Security Configuration
You can customize authentication rules using a security configuration class.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated())
.formLogin(withDefaults());
return http.build();
}
}
🔐 In-Memory Authentication
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
🔄 Role-Based Authorization
.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated())
Annotate controller methods with @PreAuthorize
:
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin")
public String adminPage() {
return "Admin content";
}
Enable method-level security:
@EnableMethodSecurity
🛡️ CSRF Protection
Spring Security enables CSRF protection by default. Disable it for APIs if you're using tokens:
http.csrf(csrf -> csrf.disable())
🧾 Custom Login Page
You can define your own login page:
.formLogin(form -> form
.loginPage("/login")
.permitAll())
Create a controller and HTML template for /login
.
🔗 Secure REST APIs with Basic Auth
Add @RestController
, then secure using HTTP Basic Auth:
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.httpBasic(withDefaults());
🪪 JWT and OAuth2 (Intro)
For advanced scenarios like token-based authentication:
-
Use Spring Security OAuth2 Resource Server
-
Integrate with JWT (JSON Web Token)
-
Secure with OAuth2/OpenID Connect
http.oauth2Login();
JWT and OAuth2 require additional setup (e.g., token validation, key management).
🧠 Best Practices
-
Always use HTTPS in production
-
Never disable CSRF unless absolutely necessary
-
Use roles and permissions for granular control
-
Store credentials securely
-
Rotate passwords and tokens regularly
✅ Summary
Spring Security is an essential part of any production-grade Spring Boot application. While it comes with a secure default configuration, it’s also extremely flexible, allowing for in-memory users, database-backed authentication, and integration with external identity providers.
By understanding its basic principles and configuration patterns, you can ensure your application is both secure and user-friendly.
Sign up here with your email
ConversionConversion EmoticonEmoticon