今天调试发现配置了角色管理的Subject在调试的时候没有执行reaml授权的代码,看来网上很多解决方法,均没有解决,最后自己尝试了好久,终于解决,分享一下解决办法。
如果你也遇到了如上问题,请不要在自定义的shiroConfig里面直接添加如下的Bean,而是新建一个java类继承springMvc,代码如下
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.web.WebApplicationInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
@Configuration
public class MySpringMvcConfig implements WebApplicationInitializer {
@Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
return new LifecycleBeanPostProcessor();
}
@Bean
@DependsOn({"lifecycleBeanPostProcessor"})
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
advisorAutoProxyCreator.setProxyTargetClass(true);
return advisorAutoProxyCreator;
}
/**
* 开启Shiro注解通知器
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(
@Qualifier("securityManager") SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
}
}
此时调试发现终于能走授权代码了,但是没有权限前端的报错是这样的
此时需要程序捕获全局异常获取 UnauthorizedException.class ,
@RestControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(value = UnauthorizedException.class)
public ModelAndView processUnauthenticatedException(HttpServletRequest request, UnauthorizedException e) {
ModelAndView mv = new ModelAndView();
mv.addObject("exception", e);
mv.setViewName("error/unauth");//自定义没权限跳转的文件(unauth.html)
return mv;
}
//。。。。其他的异常自己配
}
可见,异常捕获成功