I’m new to Spring Boot. I am doing JWT authentication. When I register a new user, the database somehow stores the wrong encoding. Can you help me?
it registers user and creates token, but when i try to log in, it says invalid password
here is my code:
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.cors(withDefaults())
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(
req->req.requestMatchers("/login/**", "register/**")
.permitAll()
.anyRequest()
.authenticated()
)
.userDetailsService(userDetailsServiceimpl)
.exceptionHandling(e->e.accessDeniedHandler(accessDeniedHandler)
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
)
.sessionManagement(session->session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
public AuthenticationResponse authenticate(User request) {
User user = userRepo.findByEmail(request.getEmail())
.orElseThrow(() -> new IllegalArgumentException("User not found"));
System.out.println("Raw Password: " + request.getPassword());
System.out.println("Stored Encoded Password: " + user.getPassword());
if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
throw new IllegalArgumentException("Invalid password");
}
String token = jwtService.generateToken(user);
return new AuthenticationResponse(token);
}
Make sure the password is properly encoded using BCryptPasswordEncoder before saving it to the database during user registration.
Specifically, when saving the password during registration, you should encode it using the passwordEncoder().encode() method.
2