spring secure加密方式
时间: 2023-11-11 17:07:58 浏览: 28
Spring Security提供了多种加密方式,下面列举一些常用的加密方式:
1. BCryptPasswordEncoder:使用BCrypt强哈希函数进行加密,是目前比较常用的一种加密方式。
2. StandardPasswordEncoder:使用SHA-256哈希函数进行加密。
3. MessageDigestPasswordEncoder:使用任何MessageDigest算法进行加密,比如SHA-1、MD5等。
4. Pbkdf2PasswordEncoder:使用PBKDF2算法进行加密。
使用这些加密方式可以在Spring Security中配置,例如:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username,password,enabled from users where username=?")
.authoritiesByUsernameQuery("select username,authority from authorities where username=?")
.passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
```
在这个例子中,使用了BCryptPasswordEncoder进行密码加密,并在配置中指定了使用该加密方式。在configure方法中,使用jdbcAuthentication()方法指定了从数据库中获取用户信息,并指定了使用该加密方式进行密码验证。