1、项目目录结构java
2、pom文件web
<!-- shiro --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.2.3</version> </dependency>
3、spring-shiro.xml文件spring
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- Shiro's main business-tier object for web-enabled applications --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="myShiroRealm" /> <property name="cacheManager" ref="cacheManager" /> </bean> <!-- 項目自定义的Realm --> <bean id="myShiroRealm" class="com.shiro.realm.MyShiroRealm"> <property name="cacheManager" ref="cacheManager" /> </bean> <!-- shiro-all.jar filterChainDefinitions:apache shiro经过filterChainDefinitions参数来分配连接的过滤, 资源过滤有经常使用的如下几个参数: authc 表示须要认证的连接 perms[/url] 表示该连接须要拥有对应的资源/权限才能访问 roles[admin] 表示须要对应的角色才能访问 perms[admin:url] 表示须要对应角色的资源才能访问 --> <!-- Shiro Filter --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!-- 安全管理器 --> <property name="securityManager" ref="securityManager" /> <!-- 未认证,跳转到哪一个页面 --> <property name="loginUrl" value="/views/shiro/login.jsp" /> <!-- 登陆成功跳转页面 --> <property name="successUrl" value="/views/shiro/success.jsp" /> <!-- 认证后,没有权限跳转页面 --> <property name="unauthorizedUrl" value="/views/shiro/error.jsp" /> <!-- shiro URL控制过滤器规则 anon未认证能够访问 authc认证后能够访问 perms须要特定权限才能访问 roles须要特定角色才能访问 user须要特定用户才能访问 port须要特定端口才能访问(不经常使用) rest根据指定HTTP请求才能访问(不经常使用) *文件夹中的所有文件 ** 文件夹中的所有文件(含子文件夹) --> <property name="filterChainDefinitions"> <value> <!-- 对静态资源设置匿名访问 --> /static/** = anon /shiro/login.jsp = anon /shiro/checkLogin** = anon /shiro/success.jsp = anon /** = authc </value> </property> </bean> <!-- 用户受权信息Cache --> <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" /> <!-- 保证明现了Shiro内部lifecycle函数的bean执行 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" /> <!-- AOP式方法级权限检查 --> <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"> <property name="proxyTargetClass" value="true" /> </bean> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager" /> </bean> </beans>
4、将spring-shiro.xml引入application里sql
5、web.xml里加入shiro过滤器(注意:shiro过滤器要放在springmvc的前面!!!)数据库
<!-- shiro-start --> <!-- 读取spring和shiro配置文件 shiro过滤器要放在springmvc前面--> <!-- shiro过滤器 --> <filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--shiro end-->
6、编写控制层(前台登录时 提交给checkLogin进行登录操做)apache
package com.shiro.controller; import com.shiro.pojo.User; import com.shiro.service.AccountService; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.annotation.Resource; @Controller @RequestMapping(value = "/shiro") public class shiroController { @Autowired private AccountService accountService; @RequestMapping(value = "/checkLogin",method = RequestMethod.POST) @ResponseBody public ModelAndView checkLogin(String username, String password) { ModelAndView mav = new ModelAndView(); User user = accountService.getUserByName(username); if (user == null) { mav.setViewName("/shiro/login"); mav.addObject("msg", "用户不存在"); return mav; } if (!user.getPassword().equals(password)) { mav.setViewName("/shiro/error"); mav.addObject("msg", "账号密码错误"); return mav; } SecurityUtils.getSecurityManager().logout(SecurityUtils.getSubject()); // 登陆后存放进shiro token UsernamePasswordToken token = new UsernamePasswordToken( user.getUsername(), user.getPassword()); Subject subject = SecurityUtils.getSubject(); subject.login(token); // 登陆成功后会跳转到successUrl配置的连接,不用管下面返回的连接。 mav.setViewName("/shiro/success"); return mav; } @RequestMapping(value = "/logout",method = RequestMethod.POST) public String logout(RedirectAttributes redirectAttributes) { SecurityUtils.getSubject().logout(); redirectAttributes.addFlashAttribute("message","已安全退出"); return "redirect:/shiro/login"; } }
7、编写(自定义)shiroRealm安全
package com.shiro.realm; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.shiro.pojo.Role; import com.shiro.pojo.User; import com.shiro.service.AccountService; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.beans.factory.annotation.Autowired; import javax.annotation.Resource; public class MyShiroRealm extends AuthorizingRealm { @Resource private AccountService accountService; /* * 权限 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { //获取登陆时输入的用户名 String loginName=(String) principals.fromRealm(getName()).iterator().next(); //到数据库查是否有此对象 User user=accountService.getUserByName(loginName); List<String> roleList =accountService.getRoleByUserName(loginName); List<String> permList = new ArrayList<String>(); System.out.println("对当前用户:["+loginName+"]进行受权!"); if (user!=null) { //权限信息对象info,用来存放查出的用户的全部的角色(role)及权限(permission) SimpleAuthorizationInfo info=new SimpleAuthorizationInfo(); //用户的角色集合 info.addRoles(roleList); } return null; } /* * 登陆验证 */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; String username=token.getUsername(); if (username!=null && !"".equals(username)){ User user=accountService.getUserByName(username); if(user!=null) { return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName()); } } return null; } }
8、dao层和service层省略mvc
getUserByName的sql:app
from User where username='"+username+"'
getRoleByUsernaem的sql:jsp
SELECT t_role.rolename from t_role,t_user,t_user_role where t_role.id = t_user_role.role_id and t_user.id = t_user_role.user_id AND t_user.username='"+loginName+"'
9、login.jsp