Spring Security Basics
Imagine you have a house with multiple rooms. Some rooms are open to guests, some are locked, and some are only for family members. You need a system to manage who can go where. Spring Security is exactly that – it manages authentication (who are you?) and authorization (what are you allowed to do?) in your application.
Core Concepts:
- Authentication – Verifying identity (login with username/password).
- Authorization – Checking permissions (admin vs normal user).
- Principal – The currently authenticated user.
- Granted Authority – Permissions assigned to user (e.g., ROLE_ADMIN).
Setup: Add Spring Security dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Basic Security Configuration:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authz -> authz
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
)
.formLogin(form -> form
.loginPage("/login")
.defaultSuccessUrl("/home")
.permitAll()
)
.logout(logout -> logout
.logoutSuccessUrl("/login?logout")
.permitAll()
);
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withUsername("user")
.password(passwordEncoder().encode("password"))
.roles("USER")
.build();
UserDetails admin = User.withUsername("admin")
.password(passwordEncoder().encode("admin"))
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Securing Methods with Annotations:
@RestController
public class AdminController {
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin/data")
public String getAdminData() {
return "Sensitive admin data";
}
@PreAuthorize("hasAnyRole('USER', 'ADMIN')")
@GetMapping("/user/profile")
public String getUserProfile() {
return "User profile";
}
}
Getting Current User in Controller:
@GetMapping("/me")
public Authentication getCurrentUser(Authentication authentication) {
return authentication;
}
// Or with @AuthenticationPrincipal
@GetMapping("/profile")
public String getProfile(@AuthenticationPrincipal UserDetails userDetails) {
return "Logged in as: " + userDetails.getUsername();
}
Two Minute Drill
- Spring Security handles authentication (who you are) and authorization (what you can do).
- @EnableWebSecurity enables security configuration.
- SecurityFilterChain defines URL-based security rules.
- UserDetailsService defines users and roles.
- PasswordEncoder encodes passwords (always use BCrypt).
- @PreAuthorize adds method-level security.
Need more clarification?
Drop us an email at career@quipoinfotech.com
