---------- pom.xml 添加 -----------
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-all</artifactId>
<version>1.2.5</version>
</dependency>
------------- web.xml 添加 -----------
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 配置spring.xml和spring-mybatis.xml这两个配置文件的位置,固定写法 -->
<param-value>classpath:conf/spring.xml,classpath:conf/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>
------------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" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans ;
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ;
http://www.springframework.org/schema/context ;
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx ;
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/aop ;
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/mvc ;
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
<!-- 继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户登录的类为自定义的UserRealm.java -->
<bean id="userRealm" class="com.xxx.common.UserRealm"/>
<!-- Shiro默认会使用Servlet容器的Session,可通过sessionMode属性来指定使用Shiro原生Session -->
<!-- 即<property name="sessionMode" value="native"/>,详细说明见官方文档 -->
<!-- 这里主要是设置自定义的单Realm应用,若有多个Realm,可使用'realms'属性代替 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm"/>
</bean>
<!-- Shiro主过滤器本身功能十分强大,其强大之处就在于它支持任何基于URL路径表达式的、自定义的过滤器的执行 -->
<!-- Web应用中,Shiro可控制的Web请求必须经过Shiro主过滤器的拦截,Shiro对基于Spring的Web应用提供了完美的支持 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全接口,这个属性是必须的 -->
<property name="securityManager" ref="securityManager"/>
<!-- 要求登录时的链接(可根据项目的URL进行替换),非必须的属性,默认会自动寻找Web工程根目录下的"/login.html"页面 -->
<property name="loginUrl" value="/login/"/>
<!-- 登录成功后要跳转的连接 -->
<property name="successUrl" value="/index/login"/>
<!-- 用户访问未对其授权的资源时,所显示的连接 -->
<!-- 若想更明显的测试此属性可以修改它的值,如unauthor.jsp,然后用[玄玉]登录后访问/admin/listUser.jsp就看见浏览器会显示unauthor.jsp -->
<!-- <property name="unauthorizedUrl" value="/no_permissions.jsp" /> -->
<!-- Shiro连接约束配置,即过滤链的定义 -->
<!-- 此处可配合我的这篇文章来理解各个过滤连的作用http://blog.csdn.net/jadyer/article/details/12172839 -->
<!-- 下面value值的第一个'/'代表的路径是相对于HttpServletRequest.getContextPath()的值来的 -->
<!-- anon:它对应的过滤器里面是空的,什么都没做,这里.do和.jsp后面的*表示参数,比方说login.jsp?main这种 -->
<!-- authc:该过滤器下的页面必须验证后才能访问,它是Shiro内置的一个拦截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter -->
<property name="filterChainDefinitions">
<value>
<!-- anon表示此地址不需要任何权限即可访问 -->
/js/** = anon
/fonts/** = anon
/img/** = anon
/resources/** = anon
/css/** = anon
/login/login = anon
/login.jsp = anon
/login/** = anon
/** = authc
</value>
</property>
</bean>
<!-- Shiro生命周期处理器 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!-- Shiro的注解配置放在spring-mvc中 -->
</beans>
---------- spring-mvc.xml 添加--------------
<!-- 开启shiro注解-->
<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>
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.apache.shiro.authz.UnauthorizedException">no_permissions</prop>
<prop key="org.apache.shiro.authz.UnauthenticatedException">no_permissions</prop>
</props>
</property>
</bean>
-------- loginController 登录方法, 通过subject.login(token); 访问 UserRealm------
Subject subject = SecurityUtils.getSubject();
// 登录后存放进shiro token
UsernamePasswordToken token=new UsernamePasswordToken(name,psword);
String error = null;
UserInfoBO userinfo = null;
LoginUserInfo<UserInfoBO> user = null;
try {
subject.login(token);
userinfo = (UserInfoBO)subject.getPrincipal();
user= new LoginUserInfo<UserInfoBO>(LoginUserInfo.ROLE_ADV, userinfo);
} catch (UnknownAccountException e) {
error = "用户名或密码错误";
} catch (IncorrectCredentialsException e) {
error = "用户名或密码错误";
} catch (ExcessiveAttemptsException e) {
// TODO: handle exception
error = "登录失败多次,账户锁定10分钟";
} catch (AuthenticationException e) {
// 其他错误,比如锁定,如果想单独处理请单独catch处理
error = "其他错误:" + e.getMessage();
}
if (error != null) {// 出错了,返回登录页面
request.setAttribute("error", error);
result.setErrorCode("1");
result.setMessage(error);
} else {// 登录成功
result.setErrorCode("0");
result.setMessage("登录成功!");
}
session.setAttribute(Constant.LOGIN_USER_INFO, user);
------- UserRealm.java -------
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.shiro.SecurityUtils;
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.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import com.isv.dsp.portal.common.service.pojo.Result;
import com.xxx.model.MenuInfoBO;
import com.xxx.model.RoleInfoBO;
import com.xxx.model.UserInfoBO;
import com.xxx.service.MenuInfoService;
import com.xxx.service.RoleInfoService;
import com.xxx.service.UserInfoService;
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserInfoService userInfoService;
@Autowired
private RoleInfoService roleInfoService;
@Autowired
private MenuInfoService menuInfoService;
/**
* 为当前登录的Subject授予角色和权限
*/
@Override
//权限控制
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// 获取当前登录的用户名,等价于(String)principals.fromRealm(this.getName()).iterator().next()
UserInfoBO userInfoBO = (UserInfoBO) super.getAvailablePrincipal(principals);
List<String> roleList = new ArrayList<String>();
List<String> permissionList = new ArrayList<String>();
// 从数据库中获取当前登录用户的详细信息
if (null != userInfoBO) {
if("超级管理员".equals(userInfoBO.getUserName())) {
permissionList.add("系统管理");
}
// 实体类User中包含有用户角色的实体类信息
if(StringUtils.isNotBlank(userInfoBO.getRoleIds())) {
RoleInfoBO roleResult = roleInfoService.getRoleById(Long.valueOf(userInfoBO.getRoleIds()));
roleList.add(roleResult.getName());
//获取关联菜单
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", Long.valueOf(userInfoBO.getRoleIds()));
List<MenuInfoBO> menuList = menuInfoService.selectMenuList("selectByRoleId", map);
for(MenuInfoBO menuInfoBO: menuList) {
permissionList.add(menuInfoBO.getName());
}
}
}else {
throw new AuthorizationException();
}
// 为当前用户设置角色和权限
SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
simpleAuthorInfo.addRoles(roleList);
simpleAuthorInfo.addStringPermissions(permissionList);
return simpleAuthorInfo;
}
/**
* 验证当前登录的Subject
*
* @see 经测试:本例中该方法的调用时机为LoginController.login()方法中执行Subject.login()时
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
throws AuthenticationException {
Result<String> result=new Result<String>();
// 获取基于用户名和密码的令牌
// 实际上这个authcToken是从AdminController里面currentUser.login(token)传过来的
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
System.err.println(
"验证当前Subject时获取到token为" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));
UserInfoBO queryUser=new UserInfoBO();
queryUser.setUserId(token.getUsername());
UserInfoBO userinfo = userInfoService.selectByUser(queryUser);
if(userinfo==null){
queryUser.setUserId(null);
queryUser.setMail(token.getUsername());
userinfo=userInfoService.selectByUser(queryUser);
}
if(userinfo==null){
throw new UnknownAccountException();
}
if (null != userinfo) {
//最后的比对需要交给安全管理器
//三个参数进行初步的简单认证信息对象的包装
AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(userinfo, userinfo.getPassword(),
getName());
return authcInfo;
} else {
return null;
}
}
/**
* 将一些数据放到ShiroSession中,以便于其它地方使用
*
* @see 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
*/
private void setSession(Object key, Object value) {
Subject currentUser = SecurityUtils.getSubject();
if (null != currentUser) {
Session session = currentUser.getSession();
System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");
if (null != session) {
session.setAttribute(key, value);
}
}
}
}
---------- 页面.jsp ---------
<ul id="titleUl">
<shiro:hasPermission name="人群圈定">
<li id="l1"><a href="../index/login" target="_self" data-localize="data.header_crowd_delineation">人群圈定</a></li>
</shiro:hasPermission>
<shiro:hasPermission name="我的人群">
<li id="l2"><a href="../tagList/myTags" data-localize='data.header_my_crowd'>我的人群</a></li>
</shiro:hasPermission>
<shiro:hasPermission name="系统管理">
<li id="l3" class=""><a href="../mgmtList/mgmt" data-localize="data.header_mgmt" >系统管理</a></li>
</shiro:hasPermission>
</ul>
------- 按钮权限控制,必须写在jsp文件中,写在js文件中无效 ------
<script>
//操作按钮权限控制,只能写在jsp中
function getMenuPermission(value, row, index) {
var edit = '<button type="button" class="btn btn-success btn-sm" onclick="getMenu(\'' + row.id + '\')"><i class="fa fa-pencil fa-fw"></i></button> '
var del = '<button type="button" class="btn btn-danger btn-sm" onclick="deleteMenu(\'' + row.id + '\')"><i class="fa fa-trash-o fa-fw"></i></button>';
var str='';
<shiro:hasPermission name="menu_edit">
str += edit;
</shiro:hasPermission>
<shiro:hasPermission name="menu_del">
str += del;
</shiro:hasPermission>
return str;
}
</script>
--------- js中调用 ---------
return getMenuPermission(value, row, index);