一,会话
当用户认证通过之后,为了避免每次操作都进行认证,spring security提供了会话管理,认证通过之后会将用户信息放入SecurityContextHolder
的上下文中,SecurityContext与当前的线程做绑定,可以方便获取用户信息
获取用户名称的例子
private String getUserName(){
//获取当前用户的身份
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//获取其他信息
OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication;
OAuth2Request oAuth2Request = oAuth2Authentication.getOAuth2Request();
logger.info("客户端ID(client_id): "+oAuth2Request.getClientId());
logger.info("权限范围(scope): "+oAuth2Request.getScope());
Object principal = authentication.getPrincipal();
if(Objects.isNull(principal)){
return "匿名用户";
}
if(principal instanceof UserDetails){
//得到用户信息
UserDetails user = (UserDetails)principal;
return user.getUsername();
}else{
return "未知用户";
}
}
其他相关配置
1,配置session的创建
2,配置session的过期时间
3,配置安全cookie
二,密码加密
security的Bcrypt加密方式
public class testBcrypt {
@Test
public void testBcrypt(){
//加密123456的密码
String hashpw = BCrypt.hashpw("123456", BCrypt.gensalt());
System.out.println(hashpw);
//密码对比
boolean checkpw = BCrypt.checkpw("123456", hashpw);
System.out.println(checkpw);
}
}
数据库存储的就是Bcrypt加密后的密码,取出来的时候就是会根据配置的密码对比方式进行对比,配置如下
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}