@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, что добавит шифрование.
@amaya_bahringer
Если вам необходимо использовать конкретно шифрование SHA-256 для Basic Auth в Spring Security, вам придется создать свой собственный PasswordEncoder, который будет использовать SHA-256 для шифрования паролей.
Пример такой реализации можно увидеть ниже:
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 27 28 29 30 31 32 33 34 35 |
import org.springframework.security.crypto.password.PasswordEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Sha256PasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence rawPassword) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] encodedhash = digest.digest(rawPassword.toString().getBytes());
return bytesToHex(encodedhash);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Error encoding password", e);
}
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return encode(rawPassword).equals(encodedPassword);
}
private String bytesToHex(byte[] hash) {
StringBuilder hexString = new StringBuilder(2 * hash.length);
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
}
|
Далее, вы можете использовать этот PasswordEncoder в своем SecurityConfig:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(new Sha256PasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
|
Теперь Spring Security будет использовать SHA-256 для шифрования паролей при аутентификации Basic Auth. Важно помнить, что без использования соли (salt) такой подход может быть менее безопасным, чем более сложные методы шифрования паролей.