@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
private DataSource datasource;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(datasource)
.usersByUsernameQuery("select username as principal, password as credentials, active"
+ " from users where username = ? ").authoritiesByUsernameQuery
("select username as principal, role as role from users_roles where username = ?")
.rolePrefix("ROLE_")
.Md5PasswordEncoder());
}
////我已经使用MD5在DataBase中加密了我的密码,但在尝试调用此方法时(解密我的密码)它不起作用或者甚至不存在
答案 0 :(得分:0)
你的假设在这里是错误的。 MD5是单向算法。没有办法解密它Check this(除了具有大量计算能力的蛮力)。因此,您已使用MD5加密密码,并将根据db中的密码进行检查。因此,为此,您必须在AuthenticationManagerBuilder实例上设置AuthenticationProvider(使用passwordEncoder。(此处为md5 passwordEncoder))。
注意:MD5 / SHA 1易受攻击,请尝试BCryptPasswordEncoder(Brute-force: Bcrypt vs MD5)
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
private DataSource datasource;
@Autowired
@Qualifier("customUserDetailsService")
UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
{
auth.userDetailsService(userDetailsService);
auth.authenticationProvider(authenticationProvider());
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new Md5PasswordEncoder();
}
}
@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService{
@Transactional(readOnly=true)
public UserDetails loadUserByUsername(String ssoId)
throws UsernameNotFoundException {
// Your custom query to get the userDetails should go here.
}
}