基于【shiro集成spring】项目改造
<!--AOP的jar包--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency>
在SpringMVC的配置文件中增加以下配置
<!--shiro注解配置--> <!--调用工程中的组件--> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"></bean> <!--如果发现此配置,会在当前工厂中多创建一个后处理器--> <aop:config></aop:config> <!--提供shiro注解组件--> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager"></property> </bean>
可以注解在controller类上或者方法上,可以叠加使用
@RequiresGuest #游客身份 @RequiresAuthentication #必须登录 @RequiresRoles(value = {"admin","manager"},logical = Logical.OR) #必须是admin或者mannager的角色 @RequiresPermissions("user:query") #必须有user:query的权限
com/shiro/resolver/MyExceptionResolver.java
package com.shiro.resolver; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authz.UnauthenticatedException; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyExceptionResolver implements HandlerExceptionResolver { public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) { System.out.println(e.getClass()); ModelAndView mv = new ModelAndView(); if(e instanceof IncorrectCredentialsException || e instanceof UnknownAccountException || e instanceof UnauthenticatedException){ //跳转到登录界面 mv.setViewName("redirect:/user/login"); } return mv; } }
resources/springmvc-servlet.xml
<bean class="com.shiro.resolver.MyExceptionResolver"></bean>
shiroFilter bean标签只保留以下内容 其他的内容删掉
resources/spring-shiro.xml
<!--shiroFilter 角色权限校验--> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!--注入核心对象:securityManager--> <property name="securityManager" ref="securityManager" /> </bean>
@RequestMapping("/logout") public String logout(){ SecurityUtils.getSubject().logout(); return "login"; }