Authentication & Authorization in Spring Security

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/passwordAuthentication
  • Checking if user has "ADMIN" roleAuthorization


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
}

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<User, Long>, JpaSpecificationExecutor<User> {
Optional<User> findByUsername(String name);
}

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();
}
}

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();
}
}

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";
}
}

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


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.