springboot中使用shiro时AuthorizationException异常抛出的三种处理方法

5 篇文章 0 订阅
1 篇文章 0 订阅

在使用注解的方式来验证角色和权限时,如:

     //注解验角色和权限
    @RequiresRoles("admin")
    @RequiresPermissions("add")
    @RequestMapping(value="/index",produces = "application/json;charset=UTF-8")
    public String index() {
        return "you get it!";
    }

可以通过几种方法来获取异常抛出的情况,即没有权限被阻挡的情况。

一、添加error.html

当权限认证不通过时,默认会跳转到error.html,所以只要创建一个error.html,就可以实现正常跳转了。

二、在shiro的配置文件中配置simpleMappingExceptionResolver

我的shiro的配置文件命名为shiroConfig.java,在里面添加这样一部分内容。可以实现自定义异常抛出的界面文件命名。

    /**
     * shiro中如果使用注释来注入角色和权限的话,无法抛出UnauthorizedException的异常
     * 需要添加以下内容,当出现异常时,跳转至UnauthenticatedException.html。
     * 下面部分也可以不添加,就会跳转至默认的error.html界面。
     * 添加了下面的内容,可以指定跳转的页面。
     * @return
     */
    @Bean
    public SimpleMappingExceptionResolver simpleMappingExceptionResolver() {
        SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
        Properties properties = new Properties();
        //未授权的网页跳转至error.html
        properties.setProperty("org.apache.shiro.authz.UnauthorizedException", "/UnauthenticatedException");
        resolver.setExceptionMappings(properties);
        return resolver;
    }

三、新建一个统一异常处理类HandlerExceptionResolver

这部分是别人的做法,我没试过,为了文章的完整性,也写在这里了。可以实现自定义异常抛出的界面文件命名。
新建一个异常处理类。

public class MyExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        if (e instanceof UnauthorizedException) {
            ModelAndView mv = new ModelAndView("/error");
            return mv;
        }
        return null;
    }
}

在启动界面中注册这个异常处理类。

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    // 注册统一异常处理bean
    @Bean
    public MyExceptionResolver myExceptionResolver() {
        return new MyExceptionResolver();
    }
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鱼月半

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值