Search code examples
javaspring-bootspring-securityjwt

Password is not getting encoded in spring security


The password is not getting encoded. It is saved as same as the user is entering it while signing in. I have tried using BCryptPasswordEncoder but it is not working. Seems like I am making a mistake somewhere. Please help!

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    /**
     * Password Encoder Bean
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * Authentication Manager Bean.
     * It is required for login process
     */
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    /**
     * Method for configuring the authentication service based on user details
     * provided
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(this.passwordEncoder());
    }

    /**
     * Method for configuring HTTP requests for the application
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/generate-token").permitAll()
                .antMatchers(HttpMethod.POST).permitAll()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .anyRequest().authenticated().and().exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Check JWT authentication token before any request
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

This is the security configuration class. I suspect error is here only in this class maybe


Solution

  • Your SecurityConfig is ok.

    I think you misunderstand the usage of auth.userDetailsService(userDetailsService).passwordEncoder(this.passwordEncoder()); here.

    This code will apply BCryptPasswordEncoder on the password when authorization and authentication, not when you store your user into DB.

    You should encode your users' passwords by hand when persisting them on the DB.

    Something like this:

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    
    public User registerNewUserAccount(UserDto accountDto) throws EmailExistsException {
        if (emailExist(accountDto.getEmail())) {
            throw new EmailExistsException(
              "There is an account with that email adress:" + accountDto.getEmail());
        }
        User user = new User();
        user.setFirstName(accountDto.getFirstName());
        user.setLastName(accountDto.getLastName());
        
        // Encoding user's password:
        user.setPassword(passwordEncoder.encode(accountDto.getPassword()));
        
        user.setEmail(accountDto.getEmail());
        user.setRole(new Role(Integer.valueOf(1), user));
        return repository.save(user);
    }