shiro(1)

注:这里只介绍spring配置模式。

因为官方例子虽然中有更加简洁的ini配置形式,但是使用ini配置无法与spring整合。而且两种配置方法一样,只是格式不一样。

涉及的jar包

Jar包名称

版本

核心包shiro-core

1.2.0

Web相关包shiro-web

1.2.0

缓存包shiro-ehcache

1.2.0

与spring整合包shiro-spring

1.2.0

Ehcache缓存核心包ehcache-core

2.5.3

Shiro自身日志包slf4j-jdk14

1.6.4

使用maven时,在pom中添加依赖包

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. <dependency>
  2. <groupId>org.apache.shiro</groupId>
  3. <artifactId>shiro-core</artifactId>
  4. <version>1.2.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.shiro</groupId>
  8. <artifactId>shiro-web</artifactId>
  9. <version>1.2.0</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.apache.shiro</groupId>
  13. <artifactId>shiro-ehcache</artifactId>
  14. <version>1.2.0</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.apache.shiro</groupId>
  18. <artifactId>shiro-spring</artifactId>
  19. <version>1.2.0</version>
  20. </dependency>
  21. <dependency>
  22. <groupId>net.sf.ehcache</groupId>
  23. <artifactId>ehcache-core</artifactId>
  24. <version>2.5.3</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.slf4j</groupId>
  28. <artifactId>slf4j-jdk14</artifactId>
  29. <version>1.6.4</version>
  30. </dependency>

Spring整合配置

1.在web.xml中配置shiro的过滤器

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. <!-- Shiro filter-->
  2. <filter>
  3. <filter-name>shiroFilter</filter-name>
  4. <filter-class>
  5. org.springframework.web.filter.DelegatingFilterProxy
  6. </filter-class>
  7. </filter>
  8. <filter-mapping>
  9. <filter-name>shiroFilter</filter-name>
  10. <url-pattern>/*</url-pattern>
  11. </filter-mapping>

2.在Spring的applicationContext.xml中添加shiro配置

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  2. <property name="securityManager" ref="securityManager" />
  3. <property name="loginUrl" value="/login" />
  4. <property name="successUrl" value="/login/loginSuccessFull" />
  5. <property name="unauthorizedUrl" value="/login/unauthorized" />
  6. <property name="filterChainDefinitions">
  7. <value>
  8. /home* = anon
  9. / = anon
  10. /logout = logout
  11. /role/** = roles[admin]
  12. /permission/** = perms[permssion:look]
  13. /** = authc
  14. </value>
  15. </property>
  16. </bean>

securityManager:这个属性是必须的。

loginUrl:没有登录的用户请求需要登录的页面时自动跳转到登录页面,不是必须的属性,不输入地址的话会自动寻找项目web项目的根目录下的”/login.jsp”页面。

successUrl:登录成功默认跳转页面,不配置则跳转至”/”。如果登陆前点击的一个需要登录的页面,则在登录自动跳转到那个需要登录的页面。不跳转到此。

unauthorizedUrl:没有权限默认跳转的页面。

过滤器简称

过滤器简称

对应的java类

anon

org.apache.shiro.web.filter.authc.AnonymousFilter

authc

org.apache.shiro.web.filter.authc.FormAuthenticationFilter

authcBasic

org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter

perms

org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter

port

org.apache.shiro.web.filter.authz.PortFilter

rest

org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter

roles

org.apache.shiro.web.filter.authz.RolesAuthorizationFilter

ssl

org.apache.shiro.web.filter.authz.SslFilter

user

org.apache.shiro.web.filter.authc.UserFilter

logout

org.apache.shiro.web.filter.authc.LogoutFilter

anon:例子/admins/**=anon 没有参数,表示可以匿名使用。

authc:例如/admins/user/**=authc表示需要认证(登录)才能使用,没有参数

roles:例子/admins/user/=roles[admin],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,当有多个参数时,例如admins/user/=roles["admin,guest"],每个参数通过才算通过,相当于hasAllRoles()方法。

perms:例子/admins/user/=perms[user:add:*],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,例如/admins/user/=perms["user:add:,user:modify:"],当有多个参数时必须每个参数都通过才通过,想当于isPermitedAll()方法。

rest:例子/admins/user/=rest[user],根据请求的方法,相当于/admins/user/=perms[user:method] ,其中method为post,get,delete等。

port:例子/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal://serverName:8081?queryString,其中schmal是协议http或https等,serverName是你访问的host,8081是url配置里port的端口,queryString

是你访问的url里的?后面的参数。

authcBasic:例如/admins/user/**=authcBasic没有参数表示httpBasic认证

ssl:例子/admins/user/**=ssl没有参数,表示安全的url请求,协议为https

user:例如/admins/user/**=user没有参数表示必须存在用户,当登入操作时不做检查

注:anon,authcBasic,auchc,user是认证过滤器,

perms,roles,ssl,rest,port是授权过滤器

3.在applicationContext.xml中添加securityManagerper配置

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
  2. <!-- 单realm应用。如果有多个realm,使用‘realms’属性代替 -->
  3. <property name="realm" ref="sampleRealm" />
  4. <property name="cacheManager" ref="cacheManager" />
  5. </bean>

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager" />

4.配置jdbcRealm

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. <bean id="sampleRealm" class="org.apache.shiro.realm.jdbc.JdbcRealm">
  2. <property name="dataSource" ref="dataSource" />
  3. <property name="authenticationQuery"
  4. value="select t.password from my_user t where t.username = ?" />
  5. <property name="userRolesQuery"
  6. value="select a.rolename from my_user_role t left join my_role a on t.roleid = a.id where t.username = ? " />
  7. <property name="permissionsQuery"
  8. value="SELECT B.PERMISSION FROM MY_ROLE T LEFT JOIN MY_ROLE_PERMISSION A ON T.ID = A.ROLE_ID LEFT JOIN MY_PERMISSION B ON A.PERMISSION = B.ID WHERE T.ROLENAME = ? " />
  9. <property name="permissionsLookupEnabled" value="true" />
  10. <property name="saltStyle" value="NO_SALT" />
  11. <property name="credentialsMatcher" ref="hashedCredentialsMatcher" />
  12. </bean>

dataSource数据源,配置不说了。

authenticationQuery登录认证用户的查询SQL,需要用登录用户名作为条件,查询密码字段。

userRolesQuery用户角色查询SQL,需要通过登录用户名去查询。查询角色字段

permissionsQuery用户的权限资源查询SQL,需要用单一角色查询角色下的权限资源,如果存在多个角色,则是遍历每个角色,分别查询出权限资源并添加到集合中。

permissionsLookupEnabled默认false。False时不会使用permissionsQuery的SQL去查询权限资源。设置为true才会去执行。

saltStyle密码是否加盐,默认是NO_SALT不加盐。加盐有三种选择CRYPT,COLUMN,EXTERNAL。详细可以去看文档。这里按照不加盐处理。

credentialsMatcher密码匹配规则。下面简单介绍。

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. <bean id="hashedCredentialsMatcher"
  2. class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
  3. <property name="hashAlgorithmName" value="MD5" />
  4. <property name="storedCredentialsHexEncoded" value="true" />
  5. <property name="hashIterations" value="1" />
  6. </bean>

hashAlgorithmName必须的,没有默认值。可以有MD5或者SHA-1,如果对密码安全有更高要求可以用SHA-256或者更高。这里使用MD5

storedCredentialsHexEncoded默认是true,此时用的是密码加密用的是Hex编码;false时用Base64编码

hashIterations迭代次数,默认值是1。

登录JSP页面

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. <form action="login" method="post">

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. <td>用户名:</td>
  2. <td><input type="text" name="username"></input></td>

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. <td>密码:</td>
  2. <td><input type="password" name="password"></input></td>

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. <td>记住我</td>
  2. <td><input type="checkbox" name="rememberMe" /></td>

注:登录JSP,表单action与提交方式固定,用户名与密码的name也是固定。

5.配置shiro注解模式

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. <!-- 开启Shiro注解的Spring配置方式的beans。在lifecycleBeanPostProcessor之后运行 -->
  2. <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
  3. depends-on="lifecycleBeanPostProcessor" />
  4. <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
  5. <property name="securityManager" ref="securityManager" />
  6. </bean>

注意:在与springMVC整合时必须放在springMVC的配置文件中。

Shiro在注解模式下,登录失败,与没有权限均是通过抛出异常。并且默认并没有去处理或者捕获这些异常。在springMVC下需要配置捕获相应异常来通知用户信息,如果不配置异常会抛出到页面

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. <bean
  2. class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
  3. <property name="exceptionMappings">
  4. <props>
  5. <prop key="org.apache.shiro.authz.UnauthorizedException">
  6. /unauthorized
  7. </prop>
  8. <prop key="org.apache.shiro.authz.UnauthenticatedException">
  9. /unauthenticated
  10. </prop>
  11. </props>
  12. </property>
  13. </bean>

@RequiresAuthentication

验证用户是否登录,等同于方法subject.isAuthenticated() 结果为true时。

@RequiresUser

验证用户是否被记忆,user有两种含义:

一种是成功登录的(subject.isAuthenticated() 结果为true);

另外一种是被记忆的(subject.isRemembered()结果为true)。

@RequiresGuest

验证是否是一个guest的请求,与@RequiresUser完全相反。

换言之,RequiresUser == !RequiresGuest。

此时subject.getPrincipal() 结果为null.

@RequiresRoles

例如:@RequiresRoles("aRoleName");

void someMethod();

如果subject中有aRoleName角色才可以访问方法someMethod。如果没有这个权限则会抛出异常AuthorizationException。

@RequiresPermissions

例如: @RequiresPermissions({"file:read", "write:aFile.txt"} )

void someMethod();

要求subject中必须同时含有file:read和write:aFile.txt的权限才能执行方法someMethod()。否则抛出异常AuthorizationException。

三.简单扩展

1.自定义realm:

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. <!--自定义的myRealm 继承自AuthorizingRealm,也可以选择shiro提供的 -->
  2. <bean id="myRealm" class="com.yada.shiro.MyReam"></bean>

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. //这是授权方法
  2. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  3. String userName = (String) getAvailablePrincipal(principals);
  4. //TODO 通过用户名获得用户的所有资源,并把资源存入info中
  5. …………………….
  6. SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
  7. info.setStringPermissions(set集合);
  8. info.setRoles(set集合);
  9. info.setObjectPermissions(set集合);
  10. return info;
  11. }

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. //这是认证方法
  2. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  3. //token中储存着输入的用户名和密码
  4. UsernamePasswordToken upToken = (UsernamePasswordToken)token;
  5. //获得用户名与密码
  6. String username = upToken.getUsername();
  7. String password = String.valueOf(upToken.getPassword());
  8. //TODO 与数据库中用户名和密码进行比对。比对成功则返回info,比对失败则抛出对应信息的异常AuthenticationException
  9. …………………..
  10. SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password .toCharArray(),getName());
  11. return info;
  12. }

2.自定义登录

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. //创建用户名和密码的令牌
  2. UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),user.getPassWord());
  3. //记录该令牌,如果不记录则类似购物车功能不能使用。
  4. token.setRememberMe(true);
  5. //subject理解成权限对象。类似user
  6. Subject subject = SecurityUtils.getSubject();
  7. try {
  8. subject.login(token);
  9. } catch (UnknownAccountException ex) {//用户名没有找到。
  10. } catch (IncorrectCredentialsException ex) {//用户名密码不匹配。
  11. }catch (AuthenticationException e) {//其他的登录错误
  12. }
  13. //验证是否成功登录的方法
  14. if (subject.isAuthenticated()) {
  15. }

3.自定义登出

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. Subject subject = SecurityUtils.getSubject();
  2. subject.logout();

4.基于编码的角色授权实现

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. Subject currentUser = SecurityUtils.getSubject();
  2. if (currentUser.hasRole("administrator")) {
  3. //拥有角色administrator
  4. } else {
  5. //没有角色处理
  6. }

断言方式控制

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. Subject currentUser = SecurityUtils.getSubject();
  2. //如果没有角色admin,则会抛出异常,someMethod()也不会被执行
  3. currentUser.checkRole(“admin");
  4. someMethod();

5.基于编码的资源授权实现

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. Subject currentUser = SecurityUtils.getSubject();
  2. if (currentUser.isPermitted("permssion:look")) {
  3. //有资源权限
  4. } else {
  5. //没有权限
  6. }

断言方式控制

[html] view plain copy

在CODE上查看代码片派生到我的代码片

  1. Subject currentUser = SecurityUtils.getSubject();
  2. //如果没有资源权限则会抛出异常。
  3. currentUser.checkPermission("permssion:look");
  4. someMethod();

6.在JSP上的TAG实现

标签名称

标签条件(均是显示标签内容)

shiro:authenticated

登录之后

shiro:notAuthenticated

不在登录状态时

shiro:guest

用户在没有RememberMe时

shiro:user

用户在RememberMe时

<shiro:hasAnyRoles name="abc,123" >

在有abc或者123角色时

<shiro:hasRole name="abc">

拥有角色abc

<shiro:lacksRole name="abc">

没有角色abc

<shiro:hasPermission name="abc">

拥有权限资源abc

<shiro:lacksPermission name="abc">

没有abc权限资源

shiro:principal

默认显示用户名称

默认,添加或删除用户的角色 或资源 ,系统不需要重启,但是需要用户重新登录。

即用户的授权是首次登录后第一次访问需要权限页面时进行加载。

但是需要进行控制的权限资源,是在启动时就进行加载,如果要新增一个权限资源需要重启系统。

Springsecurity 与apache shiro差别:

a)shiro配置更加容易理解,容易上手;security配置相对比较难懂。

b)在spring的环境下,security整合性更好。Shiro对很多其他的框架兼容性更好,号称是无缝集成。

c)shiro不仅仅可以使用在web中,它可以工作在任何应用环境中。

d)在集群会话时Shiro最重要的一个好处或许就是它的会话是独立于容器的。

e)Shiro提供的密码加密使用起来非常方便。

控制精度:

注解方式控制权限只能是在方法上控制,无法控制类级别访问。

过滤器方式控制是根据访问的URL进行控制。允许使用*匹配URL,所以可以进行粗粒度,也可以进行细粒度控制。

[转] shiro简单配置的更多相关文章

  1. Shiro简单配置

    注:这里只介绍Spring配置模式. 因为官方例子虽然中有更加简洁的ini配置形式,但是使用ini配置无法与spring整合.而且两种配置方法一样,只是格式不一样. 涉及的jar包 核心包shiro- ...

  2. shiro简单配置 (写的不错 收藏一下)

    抄袭的连接:https://blog.csdn.net/clj198606061111/article/details/24185023 注:这里只介绍spring配置模式. 因为官方例子虽然中有更加 ...

  3. shiro简单配置(转)

    注:这里只介绍spring配置模式. 因为官方例子虽然中有更加简洁的ini配置形式,但是使用ini配置无法与spring整合.而且两种配置方法一样,只是格式不一样. 涉及的jar包 Jar包名称 版本 ...

  4. shiro.ini 配置详解

    引用: [1]开涛的<跟我学shiro> [2]<SpringMVC整合Shiro> [3]<shiro简单配置> [4]Apache shiro集群实现 (一) ...

  5. 简单两步快速实现shiro的配置和使用,包含登录验证、角色验证、权限验证以及shiro登录注销流程(基于spring的方式,使用maven构建)

    前言: shiro因为其简单.可靠.实现方便而成为现在最常用的安全框架,那么这篇文章除了会用简洁明了的方式讲一下基于spring的shiro详细配置和登录注销功能使用之外,也会根据惯例在文章最后总结一 ...

  6. 权限控制框架Shiro简单介绍及配置实例

    Shiro是什么 http://shiro.apache.org/ Apache Shiro是一个非常易用的Java安全框架,它能提供验证.授权.加密和Session控制.Shiro非常轻量级,而且A ...

  7. 跟开涛老师学shiro -- INI配置

    之前章节我们已经接触过一些INI配置规则了,如果大家使用过如spring之类的IoC/DI容器的话,Shiro提供的INI配置也是非常类似的,即可以理解为是一个IoC/DI容器,但是区别在于它从一个根 ...

  8. Spring项目集成ShiroFilter简单配置

    Shiros是我们开发中常用的用来实现权限控制的一种工具包,它主要有认证.授权.加密.会话管理.与Web集成.缓存等功能.我是从事javaweb工作的,我就经常遇到需要实现权限控制的项目,之前我们都是 ...

  9. 基于spring框架的apache shiro简单集成

    关于项目的安全保护,我一直想找一个简单配置就能达到目的的方法,自从接触了shiro,这个目标总算达成了,以下结合我使用shiro的经验,谈谈比较轻便地集成该功能. 首先我们先了解一下shiro是什么. ...

随机推荐

  1. C++-标准输入输出

    1,cout 1) 用来向标准输出打印. 2) 如果参数是char*类型,则直接输出字符串.如果想要输出地址,则需要强制转换: <<static_cast<void*>(con ...

  2. [vijos P1014] 旅行商简化版

    昨天早上上课讲旅行商问题,有点难,这周抽空把3^n的算法码码看.不过这个简化版已经够折腾人了. 其一不看解析不知道这是双进程动态规划,不过我看的解析停留在f[i,j]表示第一个人走到i.第二个人走到j ...

  3. Spring学习笔记之Bean的一些属性设置

    1.beans 里边配置default-init-method="shunge",有这个方法的会执行,没有也不会报错 2.beans 里边配置default-destroy-met ...

  4. Windows 技术预览版 - 传言中的Win 10

    http://windows.microsoft.com/zh-cn/windows/preview-iso Windows Technical Preview 产品密钥: NKJFK-GPHP7-G ...

  5. 模拟iOS系统原生导航条隐藏或显示动画

    借UIView动画,使更改导航条的hidden属性这一过程动起来.悦德财富:https://yuedecaifu.com 代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ...

  6. GoldenGate中使用strcat和strext进行数据转换

    在OGG中可以对源字段的内容进行合并或拆分,从而实现类似于“ETL”的功能.strcat(s1,s2,s3,,,):用于合并字串:strext(str, start, end):用于获取指定位置的字串 ...

  7. (转)UIApplication sharedApplication详细解释-IOS

    iPhone应用程序是由主函数main启动,它负责调用UIApplicationMain函数,该函数的形式如下所示: int UIApplicationMain ( int argc, char *a ...

  8. 虚拟机centos配置ip

    涉及到三个配置文件,分别是: /etc/sysconfig/network /etc/sysconfig/network-scripts/ifcfg-eth0 /etc/resolv.conf /et ...

  9. 关于jquery.bind

      随着现在JQuery这个javascript的越来越强大,在我们平常的前端UI开发,如果不使用JQuery,说明你已经很out了.今天我们来学习一下 JQuery的bind事件.虽然,这个话题被很 ...

  10. jQuery 中 children() 与 find() 用法的区别

    1.children() 与 find() 用法的区别 通过children获取的是该元素的下级元素,而通过find获取的是该元素的下级所有元素.