Java 使用Spring Security的PasswordEncoder
我想在我的应用程序中使用Spring Security中的PasswordEncoder,但我在Google中找到的几乎所有文档和博客都使用SecurityConfig类中方法configureGlobal中的.userDetailsService()来教授这个过程 在我的应用程序中,我有一个自定义AuthenticationProvider,它使用AuthenticationService(如下所列)。任何人都可以指出如何修改我的代码以包含对此资源的支持 SecurityConfigJava 使用Spring Security的PasswordEncoder,java,spring,spring-mvc,spring-security,Java,Spring,Spring Mvc,Spring Security,我想在我的应用程序中使用Spring Security中的PasswordEncoder,但我在Google中找到的几乎所有文档和博客都使用SecurityConfig类中方法configureGlobal中的.userDetailsService()来教授这个过程 在我的应用程序中,我有一个自定义AuthenticationProvider,它使用AuthenticationService(如下所列)。任何人都可以指出如何修改我的代码以包含对此资源的支持 SecurityConfig @Con
@Configuration
@ComponentScan(value="com.spring.webapp.lojavirtual")
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider authenticationProvider;
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.authenticationProvider(authenticationProvider);
}
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/erro/login").permitAll()
.antMatchers("/bootstrap/**", "/jquery/**", "/extra/**", "/publico/**", "/erro/publico/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/acesso/login").permitAll()
.loginProcessingUrl("/login").permitAll()
.usernameParameter("login")
.passwordParameter("senha")
.successHandler(new CustomAuthenticationSuccessHandler())
.failureHandler(new CustomAuthenticationFailureHandler())
.and()
.rememberMe()
.key("lembrete")
.useSecureCookie(true)
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/acesso/login").permitAll();
}
}
CustomAuthenticationProvider
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private AuthenticationService usuario;
public CustomAuthenticationProvider() {
super();
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
UserDetails user = usuario.loadUserByUsername(name);
if(user.getPassword().equals(password)) {
Authentication auth = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities());
return auth;
}
else {
return null;
}
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
@组件
公共类CustomAuthenticationProvider实现AuthenticationProvider{
@自动连线
私人认证服务usuario;
公共CustomAuthenticationProvider(){
超级();
}
@凌驾
公共身份验证(身份验证)引发AuthenticationException{
String name=authentication.getName();
字符串密码=authentication.getCredentials().toString();
UserDetails user=usuario.loadUserByUsername(名称);
if(user.getPassword().equals(password)){
Authentication auth=new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword(),user.getAuthories());
返回auth;
}
否则{
返回null;
}
}
@凌驾
公共布尔支持(类身份验证){
返回authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
认证服务
@Service
public class AuthenticationService implements UserDetailsService {
@Autowired
private UsuarioHome accountDao;
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Usuario account = accountDao.findByField("login", username);
if(account==null) {
System.out.println("No such user: " + username);
throw new UsernameNotFoundException("No such user: " + username);
} else if (account.getAutorizacao().isEmpty()) {
System.out.println("User " + username + " has no authorities");
throw new UsernameNotFoundException("User " + username + " has no authorities");
}
List<Permission> lista = new ArrayList<Permission>();
int max = account.getAutorizacao().size();
for(int i=0; i<max; i++) {
for(int j=0; j<max; j++) {
lista.add(account.getAutorizacao().get(i).getPermissao().get(j));
}
}
boolean accountIsEnabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
return new User(account.getLogin(), account.getSenha(), accountIsEnabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities(lista));
}
public List<String> getRolesAsList(List<Permission> list) {
List <String> rolesAsList = new ArrayList<String>();
for(Permission role : list){
rolesAsList.add(role.getNome());
}
return rolesAsList;
}
public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
public Collection<? extends GrantedAuthority> getAuthorities(List<Permission> list) {
List<GrantedAuthority> authList = getGrantedAuthorities(getRolesAsList(list));
return authList;
}
}
@服务
公共类AuthenticationService实现UserDetailsService{
@自动连线
私人帐户;
@凌驾
@事务性(只读=true,传播=propagation.SUPPORTS)
public UserDetails loadUserByUsername(字符串用户名)引发UsernameNotFoundException{
Usuario account=accountDao.findByField(“登录”,用户名);
如果(帐户==null){
System.out.println(“没有这样的用户:+用户名”);
抛出新的UsernameNotFoundException(“没有这样的用户:+username”);
}else if(account.getautorizao().isEmpty()){
System.out.println(“用户”+用户名+“没有权限”);
抛出新的UsernameNotFoundException(“用户”+username+“没有权限”);
}
List lista=new ArrayList();
int max=account.getAutorizao().size();
对于(int i=0;i应该很简单。替换为:
user.getPassword().equals(password)
用这个
encoder.matches(password, user.getPassword())
为什么要使用CustomAuthenticationProvider
?您唯一需要的是customUserDetailsService
实现,其余部分可以使用Spring Security来完成!现在,我似乎不需要custom AuthenticationProvider,但我将来需要它;因为这样,我正在找到一个可以保存它的解决方案。如果您不需要它,也不需要构建它…最好的可维护代码是未编写的代码!一般来说,您不需要自定义的AuthenticationProvider
,但可以实现一些协作类,而不是自己完成所有工作。但是,遗憾的是,您的bean与其他bean一样,只是创建一个属性并将其添加到然后我在CustomAuthenticationProvider中做了此更改,并添加了实现PasswordEncoder的a类BCryptPasswordEncoder(如下所示的示例)现在我面临错误java.lang.IllegalArgumentException:在我通知我的客户并尝试登录系统后,salt版本无效。有什么办法解决这个问题吗?好的,然后我开始解决这个特定错误,但我还不能登录系统。在我的数据库中,我的密码用MD5加密,我认为代码没有“不要将密码编码为Md5。我说的对吗?如果是,如何更正?”?