Shiro学习笔记(三)权限验证的两种方式

一般来说,项目中能用两种方式进行权限验证:手动调用shrio提供的login方法并捕捉异常或者由shrio自己验证并返回验证的异常信息。网上对于shrio的验证流程已经有很多这里不再具体说明。

手动调用shrio提供的login方法

    @RequestMapping("/login")
    public String login(HttpServletRequest request, Map map) throws Exception{
        // 登录失败从request中获取shiro处理的异常信息。
        // shiroLoginFailure:就是shiro异常类的全类名.
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()){
            UsernamePasswordToken token = new UsernamePasswordToken("admin","1234567");
            try{
                subject.login(token);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return "/login";
    }

这种方法会直接进入login方法然后执行login方法,若验证不成功则抛出异常。

由shrio验证

    @RequestMapping("/login")
    public String login(HttpServletRequest request, Map map) throws Exception{
        String exception = (String) request.getAttribute("shiroLoginFailure");
        String msg = "";
        if (exception != null) {
            if (UnknownAccountException.class.getName().equals(exception)) {
                System.out.println("UnknownAccountException -- > 账号不存在:");
                msg = "UnknownAccountException -- > 账号不存在:";
            } else if (IncorrectCredentialsException.class.getName().equals(exception)) {
                System.out.println("IncorrectCredentialsException -- > 密码不正确:");
                msg = "IncorrectCredentialsException -- > 密码不正确:";
            } else if ("kaptchaValidateFailed".equals(exception)) {
                System.out.println("kaptchaValidateFailed -- > 验证码错误");
                msg = "kaptchaValidateFailed -- > 验证码错误";
            } else {
                msg = "else >> "+exception;
                System.out.println("else -- >" + exception);
            }
        }
        map.put("msg", msg);
        return "/login";
    }

这种方式shrio首先会去验证,验证结束后会将验证结果存入request中key值为shrioLoginFailure然后再进入login方法之后再对验证结果进行处理。

你可能感兴趣的:(java开发,Shiro,shrio,验证)