SpringSecurity(4-security入门-会话和密码加密的学习)

一,会话

当用户认证通过之后,为了避免每次操作都进行认证,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();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值