#Spring Security principal user returning null after login.

1 messages ยท Page 1 of 1 (latest)

proud mantleBOT
#

<@&1004656351647117403> please have a look, thanks.

proud mantleBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.

Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.

#

Here is an AI assisted attempt to answer your question ๐Ÿค–. Maybe it helps! In any case, a human is on the way ๐Ÿ‘. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#

null value. This can happen due to several reasons. Here are some possible causes and solutions:

  1. Incorrect configuration: Check your Spring Security configuration to ensure that it is properly set up. Make sure you have defined the appropriate authentication provider and user details service.

  2. Custom UserDetailsService: If you are using a custom UserDetailsService implementation, make sure it is correctly implemented and returning the user details object with the correct authorities.

  3. Authentication success handler: If you have defined a custom authentication success handler, make sure it is properly configured to set the principal in the security context.

  4. Session management: Check if your session management configuration is causing any issues. For example, if you have enabled session fixation protection, it may be creating a new session after login, resulting in a null principal.

  5. Remember me functionality: If you have enabled remember me functionality, ensure that it is working correctly and not interfering with the authentication process.

  6. Debugging: Enable debug logging for Spring Security to get more information about the authentication process and any potential errors or warnings.

  7. Testing with different users: Try logging in with different users to see if the issue persists or if it is specific to a particular user account.

If none of these solutions work, please provide more details about your Spring Security configuration and any relevant code snippets for further assistance.

tough blade
#

controller method-

#

@PostMapping("/login")
public void login(@RequestBody VisitorDTO visitorDTO) {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(visitorDTO.getUsername(), visitorDTO.getPassword()));
}

#

loadbyusername method:

#

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    Visitor visitor = visitorRepository.findByUsername(username);

    if (visitor == null){
        throw new UsernameNotFoundException("user not found");
    }else {
        return new PrincipalUser(visitor);
    }

}
#

security config-

#

@Configuration
@EnableWebSecurity
public class SecurityConfig{

private VisitorService visitorService;



public SecurityConfig(VisitorService visitorService) {
    this.visitorService = visitorService;
}
@covert nacelle
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception{
    return http.getSharedObject(AuthenticationManagerBuilder.class)
            .userDetailsService(visitorService)
            .passwordEncoder(passwordEncoder())
            .and().build();
}

@covert nacelle
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
     http.cors().and().csrf().disable().exceptionHandling().authenticationEntryPoint(
            (request, response, authException) -> response.sendError(
                    HttpServletResponse.SC_UNAUTHORIZED,
                    authException.getMessage())
    ).and().authorizeRequests()
            .requestMatchers("/login","/add","/visitors").permitAll()
            .anyRequest().authenticated();
    return http.build();
}


@covert nacelle
PasswordEncoder passwordEncoder(){
    return new BCryptPasswordEncoder();
}


@covert nacelle
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedMethods("*");
        }
    };

}

}

eternal pollen
#

pls use message formatting

#

like the bot shows

#

that way you also dont ping randoms when using annotations in discord