密码加密

一、在用户对象的密码显示设置为下面的方式User user = new User(sysUser.getUsername(), sysUser.getPassword(), collection);

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 根据用户名获取用户对象
SysUser sysUser = sysUserDao.findByUsername(username);
if(sysUser!=null){
// 创建角色集合对象
Collection<GrantedAuthority> collection = new ArrayList<>();
// 创建临时角色对象
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_USER");
// 对象添加到集合中
collection.add(grantedAuthority);
User user = new User(sysUser.getUsername(), sysUser.getPassword(), collection);
return user;
}
return null;
}

二、在添加用户的service实现类中添加密码加密

//安全框架SpringSeurity加密
@Override
public void save(SysUser sysUser) {
// 获取明文密码
String password = sysUser.getPassword();
// 对明文密码加密
String encode = passwordEncoder.encode(password);
sysUser.setPassword(encode);
sysUserDao.save(sysUser);
}
三、修改spring-security.xml配置文件
    <!--  配置认证登录信息 认证管理器自带账户密码-->
<security:authentication-manager>
<!--提供服务类 去数据库查询账户密码-->
<security:authentication-provider user-service-ref="sysUserServiceImpl">
<security:password-encoder ref="passwordEncoder"/>
<!-- <security:user-service>-->
<!--临时账户密码
authorities:指定用户的认证角色
{noop}不加密-->
<!-- <security:user name="admin" password="{noop}admin" authorities="ROLE_USER"></security:user>-->

<!-- </security:user-service>-->
</security:authentication-provider>
</security:authentication-manager>
<bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"></bean>
四、加密后登录不上问题解决方式---用BCryptPasswordEncoderUtils加密工具类进行密码加密,然后把加密后的密码存入数据库,就可以用加密前的密码登录了
package cn.kgc.utils;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
//加密工具类
public class BCryptPasswordEncoderUtils {
private static BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
public static String encodePassword(String password){
return bCryptPasswordEncoder.encode(password);
}

public static void main(String[] args) {
String password="要加密的密码";
String pwd=encodePassword(password);
     //输出加密后的密码存入数据库
System.out.println(pwd);
}
}
posted @ 2019-07-25 15:39  怕黑,可是却恋上了夜  阅读(386)  评论(0编辑  收藏  举报