测试代码地址:spring-boot-security
问题1:认证失败异常UsernameNotFoundException在Security的逻辑中是会隐藏,需要自己注册Bean覆盖默认配置
@Bean
public UserDetailsService customUserService() {
return new CustomUserService();
}
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setHideUserNotFoundExceptions(false);
provider.setUserDetailsService(customUserService());
provider.setPasswordEncoder(passwordEncoder());
return provider;
}
前端获取错误信息如下(详细login.html):
${session.SPRING_SECURITY_LAST_EXCEPTION.message}
问题2:Security的角色都是带有前缀ROLE_,所以我们在设置角色时,需要带上前缀(最好在数据源上就符合此规范)
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> auths = new ArrayList<>();
List<RoleInfo> roles = getRoles();
roles.forEach(role -> {
auths.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
});
return auths;
}