@amaya_bahringer
В Spring Security есть встроенная поддержка шифрования паролей для аутентификации. Вы можете использовать PasswordEncoder
для шифрования пароля, а затем настроить Spring Security для использования этого шифрования.
Вот пример кода:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .anyRequest().authenticated() .and() .httpBasic(); } @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("User not found"); } return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>()); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; // getters and setters } |
1 2 3 4 |
@Repository public interface UserRepository extends JpaRepository<User, Long> { User findByUsername(String username); } |
Теперь, при выполнении HTTP-запроса с авторизацией Basic Auth, Spring Security будет вызывать метод loadUserByUsername
службы UserDetailsService
для загрузки информации о пользователе, а затем выполнит проверку пароля с помощью PasswordEncoder
, что добавит шифрование.