一、项目目录结构
二、pom文件
<!-- 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>
三、spring-shiro.xml文件
<?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>
四、将spring-shiro.xml引入application里
五、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-->
六、编写控制层(前台登陆时 提交给checkLogin进行登陆操作)
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";
}
}
七、编写(自定义)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;
}
}
八、dao层和service层省略
getUserByName的sql:
from User where username='"+username+"'
getRoleByUsernaem的sql:
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+"'
九、login.jsp