• Encoded password does not look like BCrypt. Как исправить?

    @KGirman Автор вопроса
    Нашел решение

    WebSecurityConfig.java
    package com.todo.todo.config;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    import com.todo.todo.services.UserService;
    
    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    	@Autowired
    	private UserService userService;
    
    	@Override
        protected void configure(HttpSecurity http) throws Exception {
            http
    			.authorizeHttpRequests((requests) -> requests
    				.antMatchers("/",
    				"/index",
    				"/tasks",
    				"/users",
    				"/registrate",
    				"/logout",
    				"/deleteuser/**",
    				"/create",
    				"/delete/**",
    				"/update/**",
    				"/create_task",
    				"/update_task",
    				"/h2-console/**",
    				"/webjars/**").permitAll()
    				.anyRequest().authenticated()
    			)
    			.formLogin((form) -> form
    				.loginPage("/login")
    				.permitAll()
    			)
    			.logout((logout) -> logout.permitAll());
        }
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
    		.userDetailsService(userService)
    		.passwordEncoder(new BCryptPasswordEncoder());
        }
    }


    UserController.java
    Добавил кодирование пароля в @PostMapping("/registrate")
    // some imports here
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    
    // some methods here
    
    @PostMapping("/registrate")
        public String registrateUser(@Valid User user, Map<String, Object> map){
            User userFromDatabase = userRepository.findByUsername(user.getUsername());
            if(userFromDatabase != null){
                map.put("message", "User has been already registrated!");
                return registratePage;
            }
            String encodedPassword = new BCryptPasswordEncoder().encode(user.getPassword());
            user.setPassword(encodedPassword);
            user.setCreatedDate(Instant.now());
            user.setRoles(Collections.singleton(Role.USER));
            userRepository.save(user);
            map.put("message", "User has been successfully registrated!");
            return redirectLoginPage;
        }
    Ответ написан
    Комментировать