本文前提:
1、已有使用MAVEN进行项目构建的SpringMVC项目
实现步骤
1、在pom中添加Shiro的依赖
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>1.2.2</version></dependency><dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.2.2</version></dependency>
2、web.xml中进行注册
必须要放在springMVC之前进行注册
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/spring.xml classpath*:/spring-shiro.xml </param-value></context-param>.........<filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class></filter><filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern></filter-mapping>
3、添加spring-shiro.xml文件,在spring中进行Shiro设置
<bean id="myRealm" class="com.test.core.shiro.MyRealm"/><bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="mRealm"/></bean><bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager"/> <property name="loginUrl" value="/login"/> <property name="successUrl" value="/"/> <property name="unauthorizedUrl" value="/401"/> <property name="filterChainDefinitions"> <value> /login=anon /logout=anon /dologin=anon /**=authc </value> </property></bean><!-- Shiro生命周期处理器 --><bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
4、实现MyRealm
public class MyRealm extends AuthorizingRealm { private Logger logger = Logger.getLogger(MyRealm.class); @Autowired private UserManager userManager; //权限认证 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { String username = (String) principals.getPrimaryPrincipal(); User user = userManager.getUser(username); if (user == null) throw new AuthorizationException("用户不存在"); List<String> roleList = new ArrayList<String>(); List<String> permList = new ArrayList<String>(); for (Role role : user.getRoles()) { roleList.add(role.getRolename()); for (Function func : role.getFunctions()) { permList.add(func.getFuncname()); } } SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); authorizationInfo.addRoles(roleList); authorizationInfo.addStringPermissions(permList); return authorizationInfo; } //登陆认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken verifyToken = (UsernamePasswordToken) token; String username = (String) token.getPrincipal(); User user = userManager.getUser(username); if (user == null) throw new UnknownAccountException("用户不存在"); logger.info("用户["+user.getUsername()+"]尝试进行登录操作"); return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName()); } }
5、在Controller类中添加如下代码进行登录验证
UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray());try { SecurityUtils.getSubject().login(token);} catch (UnknownAccountException e) { request.setAttribute("error", "用户不存在");} catch (IncorrectCredentialsException | LockedAccountException | VerifyException e) { request.setAttribute("error", e.getMessage());} catch (ExcessiveAttemptsException e) { request.setAttribute("error", "输入的错误次数过多,用户已锁定");} catch (Exception e) { request.setAttribute("error", "系统繁忙,请稍后再试");}
