Authentication & Authorization in Spring Security
~1 min read
·
Spring Boot
Authentication and authorization are core concepts in security. Let’s explore them in detail.
Authentication vs. Authorization Custom User Authentication
Authentication vs. Authorization 🔹 Authentication : Confirms "Who are you?" (identity verification)
🔹 Authorization : Determines "What are you allowed to do?"
Example: Login with username/password → Authentication Checking if user has "ADMIN" role → Authorization
How Spring Security Handles Authentication & Authorization? Authentication : Managed via UserDetailsService , AuthenticationManager Authorization : Controlled via SecurityFilterChain or annotations like @PreAuthorize
Custom User Authentication By default, Spring Security provides an in-memory user. But in real applications, we authenticate users from a database .
Step 1: Create a User Entity
User.java
import jakarta.persistence.*;
import lombok.*;
@Entity
@Table(name = "user")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class User {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String role; // e.g., ROLE_ADMIN, ROLE_USER
}
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Table name : user
id
username
password
role
1
John
$2a$12$PypIq6C.MQ4dPia2piWMZO5vZIq2OFqmA4x9YAtm11ndY6VrfdUZy (john@123)
ADMIN
2
Mike
$2a$12$fv/xTvNU0S9LoQQo2nTPLurmuMSRlYmYP.DPRjLLHbJQjw9RZ4wcq (mike@123)
USER
Bcrypt password generated here
Step 2: Configure UserRepository
UserRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import java.util.Optional;
public interface UserRepository extends JpaRepository, JpaSpecificationExecutor {
Optional findByUsername(String name);
}
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Step 3: Implement UserDetailsService This tells Spring Security how to fetch user details from the database.
MyUserDetailservice.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class MyUserDetailservice implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
return org.springframework.security.core.userdetails.User.withUsername(user.getUsername())
.password(user.getPassword())
.roles(user.getRole())
.build();
}
}
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Step 4: Configure Authentication in SecurityConfig
SecurityConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity // ✅ Explicitly enable security configuration
public class SecurityConfig {
@Autowired
private UserDetailsService userDetailsService; // userDetailsService auto connect MyUserDetailservice because of @Service
@Bean
public AuthenticationProvider authProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(userDetailsService);
provider.setPasswordEncoder(new BCryptPasswordEncoder(12)); // Set Password BCrypt Method
return provider;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(customizer -> customizer.disable())
.authorizeHttpRequests(request -> request
.requestMatchers("/public/**").permitAll() // Access for all users like /public/data etc
.requestMatchers("/admin").hasRole("ADMIN") // This route access for admin role only
.requestMatchers("/user").hasAnyRole("USER", "ADMIN") // This route access for user and admin
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}
}
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Step 5: Configure USerController
UserController.java
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("")
public class UserController {
@GetMapping("/public/search")
public String searchUsers(){
return "Success";
}
@GetMapping("/admin")
public String adminUsers(){
return "Admin Success";
}
@GetMapping("/user")
public String userUsers(){
return "User Success";
}
@GetMapping("/auth")
public String authUsers(){
return "Auth Success";
}
}
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Testing the REST API with Postman: Once the application is running, test the endpoints:
Get Public Route for all GET:http://localhost:8080/public/search
Get Admin user route GET:http://localhost:8080/admin
Get Admin and user route GET:http://localhost:8080/user