网站首页> 博客> shiro简单配置

shiro简单配置

好文 4206
jinjing
jinjing 2017-02-23
收藏

注:这里只介绍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.shirogroupId>  
  3.     <artifactId>shiro-coreartifactId>  
  4.     <version>1.2.0version>  
  5. dependency>  
  6. <dependency>  
  7.     <groupId>org.apache.shirogroupId>  
  8.     <artifactId>shiro-webartifactId>  
  9.     <version>1.2.0version>  
  10. dependency>  
  11. <dependency>  
  12.     <groupId>org.apache.shirogroupId>  
  13.     <artifactId>shiro-ehcacheartifactId>  
  14.     <version>1.2.0version>  
  15. dependency>  
  16. <dependency>  
  17.     <groupId>org.apache.shirogroupId>  
  18.     <artifactId>shiro-springartifactId>  
  19.     <version>1.2.0version>  
  20. dependency>  
  21. <dependency>  
  22.     <groupId>net.sf.ehcachegroupId>  
  23.     <artifactId>ehcache-coreartifactId>  
  24.     <version>2.5.3version>  
  25. dependency>  
  26. <dependency>  
  27.     <groupId>org.slf4jgroupId>  
  28.     <artifactId>slf4j-jdk14artifactId>  
  29.     <version>1.6.4version>  
  30. dependency>  

Spring整合配置

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

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1.     
  2. <filter>   
  3.     <filter-name>shiroFilterfilter-name>   
  4.     <filter-class>   
  5.         org.springframework.web.filter.DelegatingFilterProxy    
  6.     filter-class>    
  7. filter>    
  8. <filter-mapping>    
  9.     <filter-name>shiroFilterfilter-name>    
  10.     <url-pattern>/*url-pattern>    
  11. filter-mapping>    

2.SpringapplicationContext.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] ,其中methodpost,get,delete等。

port:例子/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal://serverName:8081?queryString,其中schmal是协议httphttps等,serverName是你访问的host,8081url配置里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.   
  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默认falseFalse时不会使用permissionsQuerySQL去查询权限资源。设置为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.   
  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:readwrite:aFile.txt的权限才能执行方法someMethod()。否则抛出异常AuthorizationException

.简单扩展

1.自定义realm
[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1.   
  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>

不在登录状态时

用户在没有RememberMe

用户在RememberMe

"abc,123" >

在有abc或者123角色时

"abc">

拥有角色abc

<shiro:lacksRole name="abc">

没有角色abc

"abc">

拥有权限资源abc

"abc">

没有abc权限资源

默认显示用户名称

7.

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

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

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

8.

Springsecurity apache shiro差别:

a)shiro配置更加容易理解,容易上手;security配置相对比较难懂。
b)spring的环境下,security整合性更好。Shiro对很多其他的框架兼容性更好,号称是无缝集成。
c)shiro不仅仅可以使用在web中,它可以工作在任何应用环境中。
d)在集群会话时Shiro最重要的一个好处或许就是它的会话是独立于容器的。
e)Shiro提供的密码加密使用起来非常方便。

9.

控制精度:

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

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

  • 没有任何评论
个评论
jinjing

jinjing (青铜)

455金币 (16)粉丝 (9)源码

一切皆有可能!

 

加入微信群,不定期分享源码和经验
签到活跃榜 连续签到送额外金币
最新博客
校园跑腿系统外卖系统软件平台大学生创业平台搭建 464
壹脉销客智能名片CRM系统小程序可二开源码交付部署 452
为啥没搞了 652
Nginx 的 5 大应用场景,太实用了! 930
CentOS 8-stream 安装Postgresql 详细教程 1095
JAVA智慧校园管理系统小程序源码 电子班牌 Sass 模式 1055
Java智慧校园系统源码 智慧校园源码 智慧学校源码 智慧校园管理系统源码 小程序+电子班牌 800
Java智慧校园系统源码 智慧校园源码 智慧学校源码 智慧校园管理系统源码 小程序+电子班牌 781
致远OA权限 1272
发博客会有金币吗 816