Spring Boot 3.35 Basic Authentication with AuditorAware and Custom Endpoint - Angular 18 Front...

Discussão em 'Angular' iniciado por Bill D., Dezembro 6, 2024.

  1. Bill D.

    Bill D. Guest

    Spring Boot 3.35 Basic Authentication with AuditorAware works fine but does work with a custom endpoint

    With these two modules, using the default Spring Boot Login, I am able to add or edit a record in my application and the createdBy or updated are populated with the name of the logged on user.

    This is accomplished with AuditAware and the following two snippets from my User Model and UserRepository.

    // From User.java

    @PrePersist
    public void prePersist() {
    if (this.createdBy == "" || this.createdBy == null) {
    this.createdBy = "System";
    }
    if (this.updatedBy == "" || this.updatedBy == null) {
    this.updatedBy = "System";
    }
    }

    // From UserRepository.java
    User findByUserName(String userName);
    User findByFirstName(String userName);
    User findByLastName(String userName);


    // AuditorAwareImpl.java

    package com.test.config;

    import java.util.Optional;
    import org.springframework.data.domain.AuditorAware;
    import org.springframework.lang.NonNull;
    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.context.SecurityContextHolder;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.stereotype.Component;

    @Component
    public class AuditorAwareImpl implements AuditorAware<String> {
    @Override
    @NonNull
    public Optional<String> getCurrentAuditor() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null || !authentication.isAuthenticated()
    || authentication.getPrincipal().equals("anonymousUser")) {

    return Optional.ofNullable("System");
    }

    Object principal = authentication.getPrincipal();
    String username;

    if (principal instanceof UserDetails) {
    username = ((UserDetails) principal).getUsername();
    } else {
    username = principal.toString();
    }

    return Optional.of(username);
    }
    }

    package com.test.config;

    import static org.springframework.security.config.Customizer.*;
    import java.util.List;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.core.authority.SimpleGrantedAuthority;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.core.userdetails.UsernameNotFoundException;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    import org.springframework.security.crypto.password.PasswordEncoder;
    import org.springframework.security.web.SecurityFilterChain;


    // SecurityConfig.java
    import com.idea.User.User;
    import com.idea.User.UserRepository;

    @Configuration
    public class SecurityConfig {
    // private final UserRepository userRepository;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(auth -> auth
    .anyRequest().authenticated())
    .csrf(csrf -> csrf.disable())
    .httpBasic(withDefaults());

    return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService(UserRepository userRepository) {
    return username -> {
    User user = userRepository.findByUserName(username);
    if (user == null) {
    throw new UsernameNotFoundException("User not found: " + username);
    }

    return new org.springframework.security.core.userdetails.User(
    user.getFirstName() + " " + user.getLastName(),
    user.getPassword(),
    List.of(new SimpleGrantedAuthority("ROLE_USER")) // Roles if needed
    );

    };
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
    return config.getAuthenticationManager();
    }
    }




    When I change SecurityConfig.java as follows and add the following controller, the authentication does not persist,


    package com.test.config;

    import java.util.List;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.core.authority.SimpleGrantedAuthority;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.core.userdetails.UsernameNotFoundException;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    import org.springframework.security.crypto.password.PasswordEncoder;
    import org.springframework.security.web.SecurityFilterChain;

    import com.idea.User.User;
    import com.idea.User.UserRepository;

    @Configuration
    public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
    .authorizeHttpRequests(auth -> auth
    .requestMatchers("/ds/login").permitAll()
    .anyRequest().authenticated()
    )
    return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService(UserRepository userRepository) {
    return username -> {
    User user = userRepository.findByUserName(username);
    if (user == null) {
    throw new UsernameNotFoundException("User not found: " + username);
    }

    return new org.springframework.security.core.userdetails.User(
    user.getFirstName() + " " + user.getLastName(),
    user.getPassword(),
    List.of(new SimpleGrantedAuthority("ROLE_USER")) // Roles if needed
    );

    };
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
    return config.getAuthenticationManager();
    }
    }



    // AuthController.java
    package com.test.config;

    import org.springframework.http.ResponseEntity;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.context.SecurityContextHolder;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RestController;

    @RestController
    public class AuthController {
    private final AuthenticationManager authenticationManager;

    public AuthController(AuthenticationManager authenticationManager) {
    this.authenticationManager = authenticationManager;
    }

    @PostMapping("/ds/login")
    public ResponseEntity<String> login(@RequestBody LoginRequest loginRequest) {
    Authentication authentication = authenticationManager.authenticate(
    new UsernamePasswordAuthenticationToken(
    loginRequest.getUsername(),
    loginRequest.getPassword()));
    SecurityContextHolder.getContext().setAuthentication(authentication);

    // For testing only, remove later
    Authentication test = SecurityContextHolder.getContext().getAuthentication();
    System.out.println(test.getPrincipal());

    return ResponseEntity.ok("Login successful");
    }

    public static class LoginRequest {
    private String username;
    private String password;

    public String getUsername() {
    return username;
    }

    public void setUsername(String username) {
    this.username = username;
    }

    public String getPassword() {
    return password;
    }

    public void setPassword(String password) {
    this.password = password;
    }
    }
    }

    Continue reading...

Compartilhe esta Página