shiro权限架作战

时间:2021-02-07 14:49:00

shiro框架作为一种特权的开源框架,通过身份验证和授权从具体的业务逻辑分离极大地提高了我们的发展速度,它的易用性使得它越来越受到人们的青睐。上一页ACL架相比,shiro能更easy的实现权限控制,并且作为基于RBAC的权限管理框架通过与shiro标签结合使用。可以让开发者在更加细粒度的层面上进行控制。

举个样例来讲,之前我们使用基于ACL的权限控制大多是控制到连接(这里的连接大家可以简单的觉得是页面。下同)层面,也就是通过给用户授权让这个用户对某些连接拥有权限。这样的情况显然不太适合详细的项目开发,由于在某些情况下。某个用户可能仅仅对某个连接的某个部分有权限。比方这个连接的页面上有增删改查四个button。而当前登录用户对这个页面有查看的权限。可是没有增删改的权限,假设用之前的基于ACL的权限管理。我们手动控制某个button的显示。某些button的不显示是十分麻烦的,shiro通过标签就非常好的攻克了这个问题。shiro不但能细化控制粒度。并且通过加密算法可以更加安全的保证用户password的安全性。以下结合实例介绍一下shiro的详细使用。

1.spring集成shiro

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list> <!-- 载入spring的配置****begin -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/spring/appCtx-*.xml</param-value>
</context-param>
<!-- 载入spring的配置****end --> <!-- 载入Log4j的配置****begin -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- 载入Log4j的配置****end --> <!--
解决Hibernate的Session的关闭与开启问题
功能是用来把一个Hibernate Session和一次完整的请求过程相应的线程相绑定。目的是为了实现"Open Session in View"的模式。 比如: 它同意在事务提交之后延迟载入显示所须要的对象
-->
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- 载入shiro的配置*********begin***** -->
<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***** --> <!-- 载入struts2的配置******begin****** -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 载入struts2的配置*******end********* -->
</web-app>

2.shiro的主要配置文件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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
">
<!-- 自己主动扫描载入spring的bean*****begin********* -->
<context:annotation-config />
<context:component-scan base-package="com" />
<!-- 自己主动扫描载入spring的bean*****end********* --> <!-- 载入spring的properties文件*****begin********* -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="fileEncoding" value="utf-8" />
<property name="locations">
<list>
<value>classpath*:/config/properties/deploy.properties</value>
</list>
</property>
</bean>
<!-- 载入spring的properties文件*****end******** --> <!-- 载入数据库的相关连接****************begin********** -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="${datasource.url}" />
<property name="username" value="${datasource.username}" />
<property name="password" value="${datasource.password}" />
<property name="driverClassName" value="${datasource.driverClassName}"></property> <!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="${druid.initialPoolSize}" />
<property name="minIdle" value="${druid.minPoolSize}" />
<property name="maxActive" value="${druid.maxPoolSize}" /> <!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="${druid.maxWait}" /> <!-- 配置间隔多久才进行一次检測。检測须要关闭的空暇连接。单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}" /> <!-- 配置一个连接在池中最小生存的时间。单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}" /> <property name="validationQuery" value="${druid.validationQuery}" />
<property name="testWhileIdle" value="${druid.testWhileIdle}" />
<property name="testOnBorrow" value="${druid.testOnBorrow}" />
<property name="testOnReturn" value="${druid.testOnReturn}" /> <!-- 打开PSCache,而且指定每一个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="${druid.poolPreparedStatements}" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="${druid.maxPoolPreparedStatementPerConnectionSize}" /> <!-- 配置监控统计拦截的filters,如需防御SQL注入则增加wall -->
<property name="filters" value="${druid.filters}" />
<property name="connectionProperties" value="${druid.connectionProperties}" />
</bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- <property name="packagesToScan">-->
<!-- <list>-->
<!-- <value>com.wenc.*.po</value>-->
<!-- </list>-->
<!-- </property>-->
<property name="packagesToScan"
value="com.wenc.core.po" />
<!-- <property name="mappingLocations"> 此处加入Java类和数据库表的映射关系|mappingLocations取代mappingResources -->
<!-- <list>-->
<!-- <value>classpath:/com/wec/po/**/*.hbm.xml</value> -->
<!-- </list>-->
<!-- </property>-->
<property name="hibernateProperties">
<props>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.query.substitutions">${hibernate.query.substitutions}</prop>
<prop key="hibernate.default_batch_fetch_size">${hibernate.default_batch_fetch_size}</prop>
<prop key="hibernate.max_fetch_depth">${hibernate.max_fetch_depth}</prop>
<prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
<prop key="hibernate.bytecode.use_reflection_optimizer">${hibernate.bytecode.use_reflection_optimizer}</prop>
<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
<prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
<prop key="net.sf.ehcache.configurationResourceName">${net.sf.ehcache.configurationResourceName}</prop>
<prop key="hibernate.cache.use_structured_entries">${hibernate.cache.use_structured_entries}</prop>
</props>
</property>
</bean>
<!-- 载入数据库的相关连接****************end********** --> <!-- spring的事务控制****************begin********** -->
<!-- 开启AOP监听 仅仅对当前配置文件有效 -->
<aop:aspectj-autoproxy expose-proxy="true"/> <!-- 开启注解事务 仅仅对当前配置文件有效 -->
<tx:annotation-driven transaction-manager="transactionManager"/> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
<property name="globalRollbackOnParticipationFailure" value="true" />
</bean> <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="do*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="up*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="sear*" propagation="REQUIRED" read-only="true" />
<tx:method name="search*" propagation="REQUIRED" read-only="true" />
<tx:method name="find*" propagation="REQUIRED" read-only="true" />
<tx:method name="get*" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config expose-proxy="true" proxy-target-class="true">
<aop:pointcut id="txPointcut" expression="execution(* com.wenc.*.service.*.*(..))" />
<aop:advisor advice-ref="transactionAdvice" pointcut-ref="txPointcut" order="1"/>
</aop:config>
<!-- spring的事务控制****************end********** --> <!-- shiro的配置*************************begin********** -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!-- 自己定义的realm -->
<property name="realm" ref="sampleRealmService"/>
</bean> <!-- 保证实现了Shiro内部lifecycle函数的bean运行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<!-- 登陆页面的连接 -->
<property name="loginUrl" value="/login.jsp"/>
<!-- 身份验证后跳转的连接 -->
<property name="successUrl" value="/loginAction.action"/>
<property name="unauthorizedUrl" value="/unauthorized.jsp"/>
<property name="filters">
<util:map>
<entry key="authc">
<bean class="org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter"/>
</entry>
</util:map>
</property>
<!-- 指定过滤器
Anon:不指定过滤器,不错是这个过滤器是空的。什么都没做,跟没有一样。
Authc:验证,这些页面必须验证后才干訪问,也就是我们说的登录后才干訪问。 这里还有其它的过滤器,我没用。比方说授权
-->
<property name="filterChainDefinitions">
<value>
/loginAction.action=anon
/** = authc
</value>
</property>
</bean>
<!-- shiro的配置*************************end********** -->
</beans>

3.基本的实现类有三个各自是PersonAction,UserPermissionInterceptor,SampleRealmService,这三个之间的相互协作完毕了shiro的整个认证和授权过程。以下我们来看各个类的作用:

package com.wenc.test.service.web;

@Controller
public class PersonAction extends BaseAction implements ModelDriven<User> { private static Logger logger =Logger.getLogger(SampleRealmService.class); @Autowired
private PersonService personService; public String login()throws Exception{
//对用户输入的password进行MD5加密
String newPassword = CipherUtil.MD5Encode(info.getPassword());
logger.info(info.getUsername()+"="+info.getPassword());
Subject currentUser = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken( info.getUsername(), newPassword);
//token.setRememberMe(true); //是否记住我
try {
/**currentUser.login(token) 提交申请,验证能不能通过,也就是交给shiro。 这里会回调reaml(或自己定义的realm)里的一个方法
protected AuthenticationInfo doGetAuthenticationInfo() */
currentUser.login(token);
} catch (AuthenticationException e) { //验证身份失败
logger.info("验证登陆客户身份失败!");
this.addActionError("username或password错误,请又一次输入!");
return "fail";
} /**Shiro验证后,跳转到此处,这里推断验证是否通过 */
if(currentUser.isAuthenticated()){ //验证身份通过
return SUCCESS;
}else{
this.addActionError("username或password错误。请又一次输入! ");
return "fail";
} } }

这个类的login方法是当我们输入username和password之后,点击登录button所运行的方法,因为在数据库中用户的password是密文形式。所以在进行用户身份验证,我们必须以相同的加密方式来加密用户在页面上输入的password,然后将username和加密后的password放入令牌(也就是token中),之后shiro会通过比对token中的username和password是否与数据库中存放的真正的username和password来确定用户是否为合法用户,而这个验证过程是shiro为我们完毕的,当运行currentUser.login(token)方法的时候会触发验证过程,可是通常情况下这个验证过程是通过我们来自己定义完毕的,为此我们必须自己写一个realm类来继承shiro的AuthorizingRealm类并覆盖其AuthenticationInfo
doGetAuthenticationInfo(AuthenticationToken authcToken)方法,来看SampleRealmService类。这个就是继承AuthorizingRealm并覆盖其方法后的类:

package com.wenc.core.service;

@Component
public class SampleRealmService extends AuthorizingRealm { private static Logger logger =Logger.getLogger(SampleRealmService.class);
@Autowired
private PersonDAO personDAO; public SampleRealmService() {
logger.info("-------AAA1------------------");
setName("sampleRealmService");
// setCredentialsMatcher(new Sha256CredentialsMatcher());
} /**
* 身份验证
* @param authcToken 登陆Action封装的令牌
*/
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
/**查询相应的用户是否存在*/
User user =personDAO.getUser(token.getUsername(), token.getPassword().toString());
logger.info(user);
if( user != null ) {
return new SimpleAuthenticationInfo(user.getId(), user.getPassword(), getName());
} else {
return null;
}
}
/**
* 授权
* 注意:统一在struts的拦截器中处理,见UserPermissionInterceptor.java
*/
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
Integer userId = (Integer) principals.fromRealm(getName()).iterator().next();
logger.info("用户ID:"+userId);
User user = personDAO.getUser(userId);
if( user != null ) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
for( Role role : user.getRoles() ) {
info.addRole(role.getName());
Set<Perms> set= role.getPermissions();
logger.info(set);
for(Perms perm:set){
info.addStringPermission(perm.getActionName());
}
}
return info;
} else {
return null;
}
} }

如同上面介绍的那样运行验证的过程就进入了身份认证方法体中。也就是在这里讲数据库中查询出来的真实的用户信息和token中的用户信息进行比对,当验证成功后跳转至strut.xml中配置的index.jsp页面,截图例如以下:

shiro权限架作战

至此我们完毕了用户身份验证过程,接下来我们介绍授权过程和通过shiro标签来介绍细粒度的权限控制。当我们点击“主页2”这个超链接的时候会被struts.xml文件里定义的拦截器拦截。拦截器UserPermissionInterceptor代码例如以下:

package com.wenc.core.web.interceptor;

public class UserPermissionInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = -2185920708747626659L;
private static final Log logger = LogFactory.getLog(UserPermissionInterceptor.class); @Override
public String intercept(ActionInvocation invocation) throws Exception {
ActionContext ac = invocation.getInvocationContext();
Map map = ac.getParameters(); String actionName = ac.getName();
String methodName = "";
String[] _methodName = (String[]) map.get("method");
if (_methodName != null) {
methodName = _methodName[0];
}
logger.info("actionName:"+actionName+",方法名:"+methodName); Subject currentUser = SecurityUtils.getSubject();
/**推断是否已经授权*/
if(!currentUser.isPermitted(actionName)){
logger.info("没有有权限");
}
return invocation.invoke();
}
}

当点击“主页2”之后会首先被该拦截器拦截。拦截的过程中会将当前请求(即点击“主页2”相应的action)的action名称取出。我们要验证的就是该用户是否享有对该action的权限,运行到currentUser.isPermitted(actionName)方法的时候就触发了shiro的授权认证功能,相同我们也对这种方法进行了重写,进入的是SampleRealmService类中的授权方法AuthorizationInfo
doGetAuthorizationInfo(PrincipalCollection principals)。在这个函数中我们取出了数据库中配置的该用户的权限,并将用户的全部权限增加到info中,然后返回请求页面,当载入请求页面的时候运行到shiro标签的时候会再次触发授权(注意这次将不被拦截),相当于再次从数据库中将该用户的权限载入了一遍,而且放入到info中,然后shiro标签会依据shiro:hasPermission或者是shiro:hasRole进行比对,假设存在则显示,否则不显示。当然shiro标签除了这两种方式外还有非常多种其它的方式,大家能够自行探索。

至此整个shiro身份认证和授权介绍完成。谢谢阅读,请指正。

版权声明:本文博主原创文章,博客,未经同意不得转载。

随机推荐

  1. 让不支持h5新标签的浏览器支持新标签

    把这段js加到页面的头部就可以了,创建想让浏览器支持的标签即可 //条件判断是否支持 h5 if(window.applicationCache){ alert("支持h5") } ...

  2. k8s入门系列之guestbook快速部署

    k8s集群以及一些扩展插件已经安装完毕,本篇文章介绍一下如何在k8s集群上快速部署guestbook应用. •实验环境为集群:master(1)+node(4),详细内容参考<k8s入门系列之集 ...

  3. 【C&num;学习笔记】LinkedList容器使用

    using System; using System.Collections.Generic; namespace ConsoleApplication { class Program { stati ...

  4. vs 行数

    工具->选项->文本编辑器->选择你用的语言,选中行号,即可!

  5. 福利 城市名的python list

    ["上海","北京","北京市","朝阳","朝阳区","海淀","元 ...

  6. &lbrack;html&rsqb; 学习笔记--Web存储

    HTML5 提供了两种在客户端存储数据的新方法之前,这些都是由 cookie 完成的.但是 cookie 不适合大量数据的存储,因为它们由每个对服务器的请求来传递,这使得 cookie 速度很慢而且效 ...

  7. 1625&colon; &lbrack;Usaco2007 Dec&rsqb;宝石手镯

    1625: [Usaco2007 Dec]宝石手镯 Time Limit: 5 Sec  Memory Limit: 64 MB Submit: 919  Solved: 618 [Submit][S ...

  8. 非关系型数据库之Redis

    一.Redis简介     REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统. Redis是一个开源的使用 ...

  9. hdu4622(hash解法)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4622 Now you are back,and have a task to do:Given you ...

  10. day7-python打开文件方式

    文件操作 对文件操作流程 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件 基本操作 import codecs #主要用来解决乱码问题 f = codecs.open('1. ...