1、无权限时候会报错,对于前后端来说都不是很好的事情,故此我们可以做异常处理,无权限时候可以进行自定义处理,在controller中创建ExceptionController
package com.wxg.springbootshiro.controller;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class ExceptionController {
@ResponseBody
@ExceptionHandler(UnauthorizedException.class)
public String unauthorizedException(Exception ex){
return "无权限";
}
@ResponseBody
@ExceptionHandler(AuthorizationException.class)
public String authorizationException(Exception ex){
return "权限认证失败";
}
}
2、验证

3、前端权限控制需要在pom中引入extras依赖
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
4、在ShiroConfig配置类中,添加以下Bean
@Bean
public ShiroDialect shiroDialect(){
return new ShiroDialect();
}
5、在main.html中添加角色和权限校验
6、验证:期望是张三有所以权限及角色,可以看到所有,李四没有相应的角色和权限,李四登录后看不到该入口

文章介绍了如何在SpringBoot应用中使用Shiro进行异常处理,特别是针对无权限和权限认证失败的情况,通过创建ExceptionController进行自定义响应。同时,文章提到了前端权限控制的实现,需要引入thymeleaf-extras-shiro依赖,并在ShiroConfig配置类中添加ShiroDialectBean。最后,展示了在模板文件中添加角色和权限校验的例子。
1万+

被折叠的 条评论
为什么被折叠?



