shiro

本文详细介绍Spring整合Shiro自定义数据库的步骤,包括Shiro的配置、自定义Realm的实现,以及如何利用Redis进行角色和权限数据的缓存,提高系统效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、controller层

/*
spring整合shiro自定义数据库的步骤:
1. 导入包,除了之前ssm框架所需要包以外,还需要导入shiro-core,shiro-web,shiro-spring,common-logging
2. 在web。xml中添加shiro的过滤器
3. 在spring-mvc.xml中添加对shiro注解的支持
4. 在spring.xml中添加对shiro的支持
5. 添加自定义的realm去实现两个方法
 */

@Controller
public class UserController {
    @Resource
    private UserService userService;

    @Autowired
    private RolesDAO rolesDAO;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;



    @RequestMapping("/login")
    @ResponseBody
    public Object login(String username, String password, Model model){

        AjaxResult ajaxResult = new AjaxResult();
        // 可以理解为用户对象
        Subject subject = SecurityUtils.getSubject();

        // 登录失败会以异常的形式表示
        try {
            // 创建一个使用用户名密码登录的方式
            AuthenticationToken token = new UsernamePasswordToken(username, password);
            // 尝试登录,将用户对象具体化
            subject.login(token);
            subject.hasRole("admin");
            ajaxResult.setCode(0);
        }catch (UnknownAccountException ex){
            ex.printStackTrace();
            ajaxResult.setCode(1);
            ajaxResult.setMsg("用户名错误");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            ajaxResult.setCode(1);
            ajaxResult.setMsg("密码错误");
        }catch (Exception e){
            e.printStackTrace();
            ajaxResult.setCode(1);
            ajaxResult.setMsg("登录失败:系统异常,请联系管理管");
        }
        return ajaxResult;
    }

    @RequestMapping("test")
    @ResponseBody
    public String demo(){
        //查询数据之前先查询缓存
        BoundListOperations<String, String> listOperations = redisTemplate.boundListOps("roles");
        Long size = listOperations.size();
        //1、查询缓存
        List<String> roles = redisTemplate.boundListOps("roles").range(0, size);
        //2、判断缓存中是否存在需要的数据
        if (roles == null || roles.isEmpty()) {
            //避免缓存穿透,所以加锁,排队访问
            System.out.println("---排队----");
            synchronized (this) {
                //双重缓存检测机制
                roles = redisTemplate.boundListOps(ApplicationConstant.REDIS.KEY_ROLES).range(0, size);
                if (roles == null || roles.isEmpty()) {
                    System.out.println("---------------");
                    //不存在,则查询数据库
                    roles = rolesDAO.queryRolesByUsername("001");
                    //数据库中的数据查到之后,再写入缓存,方便下次查询的时候直接从缓冲中取数据
                    //1、此处不论数据库查询出来的数据是否为空,都写入缓存,避免故意使用无效数据进行恶意攻击导致穿透
                    //如果上一条不停再缓存中存储无效key,会导致缓存不断增加,从而内存耗尽。导致正常数据无处安身。
                    if (roles == null || roles.isEmpty()) {
                        //如果数据库没有此数据,则先存入数据库,然后设置过期时间
                        redisTemplate.boundValueOps(ApplicationConstant.REDIS.KEY_ROLES).set("",5,TimeUnit.SECONDS);
                    } else {
                        redisTemplate.opsForList().leftPushAll(ApplicationConstant.REDIS.KEY_ROLES, roles);
                    }

                }
            }

        } else {
            System.out.println(">>>>>>>>>>>>>>>>>>>");
        }
        return "redis";
    }
}

2、realm

/**
 * 1、登录逻辑
 * 2、角色和权限查询
 */
public class AuthsMySQLRealm extends AuthorizingRealm {
    @Resource
    private UserDAO userDAO;
    @Autowired
    private RolesDAO rolesDAO;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public String getName() {
        return "authsMySQLRealm";
    }

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //进行权限和角色查询(数据库)。
        String username = principals.getPrimaryPrincipal().toString();

        //查询数据之前先查询缓存
        BoundListOperations<String, String> listOperations = redisTemplate.boundListOps("roles");
        Long size = listOperations.size();
        //1、查询缓存

        List<String> roles = redisTemplate.boundListOps("roles").range(0, size);
        //2、判断缓存中是否存在需要的数据
        if (roles == null || roles.isEmpty()) {
            System.out.println("---------------");
            //不存在,则查询数据库
            roles = rolesDAO.queryRolesByUsername(username);
            //数据库中的数据查到之后,再写入缓存,方便下次查询的时候直接从缓冲中取数据
            redisTemplate.opsForList().leftPushAll("roles",roles);
        } else {
            System.out.println(">>>>>>>>>>>>>>>>>>>");
        }
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roles);

        return simpleAuthorizationInfo;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken)token;
        String username = upToken.getUsername();
        String password = new String(upToken.getPassword());

        if (username == null || password == null) {
            throw new AuthenticationException("username or password must be not null");
        }

        User user = userDAO.findUserByUsernameAndPwd(username);
        if (user == null){
            throw new UnknownAccountException("username is not found:" + username);
        }

        String pwd = user.getPwd();
        if (!password.equals(pwd)) {
            throw new IncorrectCredentialsException("password is error");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(), user.getPwd(), getName());
        return info;

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值