加密:可以使用BCryptPasswordEncoder对象的 encode(CharSequence rawPassword) 方法加密CharSequence这个类型是字符串的顶级接口,所以可以直接传递字符串进行加密
可以把获取BCryptPasswordEncoder对象放到工具类中(也可以将这个对象交给ioc容器管理。。。。然后再service层直接注入)
private static BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
public static String encodingPassword(String password){
return bCryptPasswordEncoder.encode(password);
}
}
然后在service层进行对应加密
@Override
public void save(UserInfo userInfo) {
userInfo.setPassword(BCryptPasswordEncodingUtil.encodingPassword(userInfo.getPassword()));
userDao.save(userInfo);
}
登陆1: 在登陆时候将数据库获取的加密的密码和输入的密码进行对比,对应的方法
public boolean matches(CharSequence rawPassword, String encodedPassword)
这里就不做操作了。。
//登陆 @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserInfo userInfo = userDao.findByUsername(username); //需要把userinfo转化为UserDetails,实现类User构造如下 //public User(String username, String password, // 权限:Collection<? extends GrantedAuthority > authorities) // 权限对象可以使用GrantedAuthority的子类 SimpleGrantedAuthority //将权限名(roles.getRoleName())传给SimpleGrantedAuthority的构造器返回对应的对象。详细看下面的getAuthority方法 List<Role> roles = userInfo.getRoles(); List<SimpleGrantedAuthority> grantedAuthority = getAuthority(roles); // User(String username, String password, boolean enabled, // boolean accountNonExpired, boolean credentialsNonExpired, // boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) //下面这个参数较少的构造,其实也是调用上面这个构造 //return new User(userInfo.getUsername(), "{noop}"+userInfo.getPassword(), grantedAuthority); return new User(userInfo.getUsername(), userInfo.getPassword(), userInfo.getStatus()==1, true, true, true, grantedAuthority//角色权限,根据角色的名字获取 ); } private List<SimpleGrantedAuthority> getAuthority(List<Role> roles) { List<SimpleGrantedAuthority> authoritys = new ArrayList(); for (Role role : roles) { authoritys.add(new SimpleGrantedAuthority(role.getRoleName())); } return authoritys; }
security提供了controller,我们不需要写controlle层,只需要service接口继承UserDetailsService,然后再实现类实现以上方法即可
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- azee.cn 版权所有 赣ICP备2024042794号-5
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务