org.apache.shiro.authz.AuthorizationException: Not authorized to invoke method报错解决方案
踩坑日记:
在springboot+shiro 权限认证时报错
方案1(不行的话就用方案2):
用户在没有权限的情况下,访问页面,shiro根据没有权限本抛出Subject does not have permission [xxxxx]错误,可以在拦截器一个错误处理方式,统一异常处理,没有权限就进入统一页面
shiroFilterFactoryBean.setUnauthorizedUrl("url");
方案2:在unauthorizedUrl 不起作用的情况下
2.1、设置自定义的异常解析器
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;public class DiyExceptionHandler implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
if (e instanceof UnauthorizedException) { // 未授权 : 403页面
ModelAndView mv = new ModelAndView("/403");
return mv;
} else if (e instanceof UnauthenticatedException) { // 未登录 : 401登录页面
ModelAndView mv = new ModelAndView("/login");
return mv;
}
return null;
}
}
2.2、在启动类注册统一处理异常bean
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;import com.***.***.config.DiyExceptionHandler;
@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
// 注册统一异常处理bean
@Bean
public DiyExceptionHandler diyExceptionHandler() {
return new DiyExceptionHandler ();
}
}