spring boot logged in user
Add Spring Security Dependency:
xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
Configure Spring Security in Application:
java @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .and() .httpBasic(); } }
Create a UserDetailsService:
java @Service public class UserDetailsServiceImpl implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // Implement logic to load user details from the database } }
Autowire AuthenticationManagerBuilder in SecurityConfig:
java @Autowired public void configureGlobal(AuthenticationManagerBuilder auth, UserDetailsService userDetailsService) throws Exception { auth.userDetailsService(userDetailsService); }
Access Logged-In User in Controller:
java @RestController public class UserController { @GetMapping("/user") public String getCurrentUser(Authentication authentication) { return "Logged in user: " + authentication.getName(); } }
Customize User Entity and Repository (Optional): ```java @Entity public class CustomUser extends User { // Add custom fields or methods if needed }
public interface CustomUserRepository extends JpaRepository
Implement UserDetailsService with Custom Repository: ```java @Service public class CustomUserDetailsServiceImpl implements UserDetailsService { @Autowired private CustomUserRepository userRepository;
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return userRepository.findByUsername(username) .orElseThrow(() -> new UsernameNotFoundException("User not found")); } } ```
Update SecurityConfig to use Custom UserDetailsService:
java @Autowired public void configureGlobal(AuthenticationManagerBuilder auth, CustomUserDetailsServiceImpl userDetailsService) throws Exception { auth.userDetailsService(userDetailsService); }
Secure Endpoints based on Roles:
java @PreAuthorize("hasRole('ADMIN')") @GetMapping("/admin") public String adminEndpoint() { return "Admin Access"; }
Logout Configuration (Optional):
java @Override protected void configure(HttpSecurity http) throws Exception { http .logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/login"); }