1.多Realm验证

  存在这样一种场景,同一个密码可能在MqSQL中存储,也可能在Oracle中存储,有可能MqSQL中使用的是MD5加密算法,而Oracle使用SHA1加密算法。这就需要有多个Realm以及认证策略的问题。

  

  通过查看源码可以看到 ModularRealmAuthenticator.class 中的 doAuthenticate

    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
assertRealmsConfigured();
Collection<Realm> realms = getRealms();
if (realms.size() == 1) {
return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
} else {
return doMultiRealmAuthentication(realms, authenticationToken);
}
}

   即可以看到如果有一个Realm 使用的是 doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);

  如果有多个Realm 使用的是doMultiRealmAuthentication(realms, authenticationToken);

  所以我们可以配置多个Realm 给到 ModularRealmAuthenticator 这个bean,将ModularRealmAuthenticator 单独配置为一个bean,将这个bean 配置给SecurityManager

  1).添加第二个Realm SecondRealm.java

package com.java.shiro.realms;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource; public class SecondRealm extends AuthenticatingRealm { @Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
System.out.println("[SecondRealm] doGetAuthenticationInfo " + token); // 1. 把AuthenticationToken 转换为UsernamePasswordToken
UsernamePasswordToken up = (UsernamePasswordToken) token;
// 2. 从UsernamePasswordToken 中来获取username
String username = up.getUsername();
// 3. 调用数据库的方法,从数据库中查询username对应的用户记录
System.out.println("从数据库中获取userName :" + username + " 所对应的用户信息.");
// 4. 若用户不存在,则可以抛出 UnknownAccoountException 异常
if ("unknown".equals(username)) {
throw new UnknownAccountException("用户不存在");
}
// 5. 根据用户信息的情况,决定是否需要抛出其他的AuthencationException 异常 假设用户被锁定
if ("monster".equals(username)) {
throw new LockedAccountException("用户被锁定");
}
// 6. 根据用户的情况,来构建AuthenticationInfo 对象并返回,通常使用的是
// SimpleAuthenticationInfo
// 以下信息是从数据库获取的. Object principal = username; // principal 认证的实体信息.
// 可以是username,也可以是数据表对应的用户的实体类对象
// String credentials = "fc1709d0a95a6be30bc5926fdb7f22f4"; // credentials:密码
String credentials = null; // credentials:密码
String realmName = getName();
AuthenticationInfo info = null;/*new SimpleAuthenticationInfo(principal, credentials, realmName);*/ if("admin".equals(username)){
credentials = "ce2f6417c7e1d32c1d81a797ee0b499f87c5de06";
}else if("user".equals(username)){
credentials = "073d4c3ae812935f23cb3f2a71943f49e082a718";
} ByteSource credentialsSalt = ByteSource.Util.bytes(username);//这里的参数要给个唯一的; info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName); return info;
} public static void main(String[] args) {
String hashAlgorithmName = "SHA1";
String credentials = "123456";
int hashIterations = 1024;
ByteSource credentialsSalt = ByteSource.Util.bytes("admin");
Object obj = new SimpleHash(hashAlgorithmName, credentials, credentialsSalt, hashIterations);
System.out.println(obj);
}
}

  2). 修改 applicationContext.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"> <!-- 数据源配置,暂时不考虑数据源,做一些静态的数据 -->
<!-- Sample RDBMS data source that would exist in any application - not Shiro related. -->
<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:mem:shiro-spring"/>
<property name="username" value="sa"/>
</bean> -->
<!-- Populates the sample database with sample users and roles. -->
<!-- <bean id="bootstrapDataPopulator" class="org.apache.shiro.samples.spring.BootstrapDataPopulator">
<property name="dataSource" ref="dataSource"/>
</bean> --> <!-- Simulated business-tier "Manager", not Shiro related, just an example -->
<!-- <bean id="sampleManager" class="org.apache.shiro.samples.spring.DefaultSampleManager"/> --> <!-- =========================================================
Shiro Core Components - Not Spring Specific
========================================================= -->
<!-- Shiro's main business-tier object for web-enabled applications
(use DefaultSecurityManager instead when there is no web environment)-->
<!--
1.配置SecurityManager!
-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"/>
<!-- Single realm app. If you have multiple realms, use the 'realms' property instead. -->
<!-- 配置session的管理方式 -->
<!-- <property name="sessionMode" value="native"/> -->
<!-- <property name="realm" ref="jdbcRealm"/> -->
<!-- 配置多个Realm -->
<property name="authenticator" ref="authenticator"></property>
</bean> <!-- 配置多个Realm -->
<bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<property name="realms">
<list>
<ref bean="jdbcRealm"/>
<ref bean="secondRealm"/>
</list>
</property>
</bean>
<!-- Let's use some enterprise caching support for better performance. You can replace this with any enterprise
caching framework implementation that you like (Terracotta+Ehcache, Coherence, GigaSpaces, etc -->
<!--
2.配置CacheManager,实例上可以用企业的缓存产品来提升性能
2.1需要加入ehcache的jar包及配置文件
-->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<!-- Set a net.sf.ehcache.CacheManager instance here if you already have one. If not, a new one
will be creaed with a default config:
<property name="cacheManager" ref="ehCacheManager"/> -->
<!-- If you don't have a pre-built net.sf.ehcache.CacheManager instance to inject, but you want
a specific Ehcache configuration to be used, specify that here. If you don't, a default
will be used.: -->
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean> <!-- Used by the SecurityManager to access security data (users, roles, etc).
Many other realm implementations can be used too (PropertiesRealm,
LdapRealm, etc. -->
<!--
3.配置Realm
3.1 自己写一个Realm,需要实现Realm接口
-->
<bean id="jdbcRealm" class="com.java.shiro.realms.ShiroRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="MD5"></property> <!-- 加密算法的名称 -->
<property name="hashIterations" value="1024"></property> <!-- 配置加密的次数 -->
</bean>
</property>
</bean>
<bean id="secondRealm" class="com.java.shiro.realms.SecondRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="SHA1"></property> <!-- 加密算法的名称 -->
<property name="hashIterations" value="1024"></property> <!-- 配置加密的次数 -->
</bean>
</property>
</bean>
<!-- =========================================================
Shiro Spring-specific integration
========================================================= -->
<!-- Post processor that automatically invokes init() and destroy() methods
for Spring-configured Shiro objects so you don't have to
1) specify an init-method and destroy-method attributes for every bean
definition and
2) even know which Shiro objects require these methods to be
called. --> <!--
4.配置 LifecycleBeanPostProcessor,可以自动的调用配置在spring IOC容器中Shiro bean的声明周期方法
-->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> <!-- Enable Shiro Annotations for Spring-configured beans. Only run after
the lifecycleBeanProcessor has run: -->
<!--
5.启用 IOC 容器中使用 shiro 注解,但必须在配置了LifecycleBeanPostProcessor 之后才可以使用。
-->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean> <!-- Secure Spring remoting: Ensure any Spring Remoting method invocations can be associated
with a Subject for security checks. -->
<!-- 远程调用,暂时不需要 -->
<!-- <bean id="secureRemoteInvocationExecutor" class="org.apache.shiro.spring.remoting.SecureRemoteInvocationExecutor">
<property name="securityManager" ref="securityManager"/>
</bean> --> <!-- Define the Shiro Filter here (as a FactoryBean) instead of directly in web.xml -
web.xml uses the DelegatingFilterProxy to access this bean. This allows us
to wire things with more control as well utilize nice Spring things such as
PropertiesPlaceholderConfigurer and abstract beans or anything else we might need: --> <!--
6.配置ShiroFilter
6.1 id 必须和web.xml 中配置的 DelegatingFilterProxy 的 <filter-name> 一致
若不一致,则会抛出:NoSuchBeanDefinitionException.因为Shiro会来IOC容器中查找和<filter-name> 名字对应的filter bean.
-->
<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="/list.jsp"/><!-- 登录成功页面 -->
<property name="unauthorizedUrl" value="/unauthorized.jsp"/><!-- 没有权限的页面 -->
<!-- The 'filters' property is not necessary since any declared javax.servlet.Filter bean
defined will be automatically acquired and available via its beanName in chain
definitions, but you can perform overrides or parent/child consolidated configuration
here if you like: -->
<!-- <property name="filters">
<util:map>
<entry key="aName" value-ref="someFilterPojo"/>
</util:map>
</property> -->
<!--
配置哪些页面需要受保护
以及访问这些页面需要的权限
1). anon(anonymous) 可以被匿名访问,即不需要登录就可以访问
2). authc(authentication) 必须认证之后,即登录后才可以访问
3). URL 权限采取第一次匹配优先的方式,即从开头使用第一个匹配的url模式对应的拦截器链。
4). logout 登出
-->
<property name="filterChainDefinitions">
<value>
/login.jsp= anon
/shiro/login= anon
/shiro/logout = logout
# everything else requires authentication: /** = authc
</value>
</property>
</bean> </beans>

   3).在UsernamePasswordToken.class 的

public char[] getPassword() {
return password;
}

  处打断点,会看到断点停两次。

  

  由于两种都使用的HashedCredentialsMatcher 时的两种算法:

测试成功:

[FirstRealm] doGetAuthenticationInfo org.apache.shiro.authc.UsernamePasswordToken - admin, rememberMe=true
从数据库中获取userName :admin 所对应的用户信息.
[SecondRealm] doGetAuthenticationInfo org.apache.shiro.authc.UsernamePasswordToken - admin, rememberMe=true
从数据库中获取userName :admin 所对应的用户信息.

  这两个使用顺序的,因为我们在配置文件中的配置,

<!-- 配置多个Realm -->
<bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<property name="realms">
<list>
<ref bean="jdbcRealm"/>
<ref bean="secondRealm"/>
</list>
</property>
</bean>

2. Shiro 认证策略

  1).如果有多个Realm,怎样才算是认证成功,这就需要认证策略。

  认证策略主要使用的是 AuthenticationStrategy 接口

   这个接口由三个实现类:

    •   AuthenticationStrategy接口的默认实现:
    •   FirstSuccessfulStrategy:只要有一个Realm 验证成功即可,只返回第一个Realm 身份验证成功的认证信息,其他的忽略;
    •   AtLeastOneSuccessfulStrategy:只要有一个Realm验证成功即可,和FirstSuccessfulStrategy不同,将返回所有Realm身份验证成功的认证信息;
    •   AllSuccessfulStrategy:所有Realm验证成功才算成功,且返回所有Realm身份验证成功的认证信息,如果有一个失败就失败了。
    •   ModularRealmAuthenticator默认是AtLeastOneSuccessfulStrategy策略

  通过debug 可以看出,默认使用的是AtLeastOneSuccessfulStrategy

  

  为了便于观看,修改SecondRealm中的

    info = new SimpleAuthenticationInfo("seconde", credentials, credentialsSalt, realmName);

  2). 如何切换认证策略

    切换成 AllSuccessfulStrategy 即所有认证策略都通过了,才算认证成功。

    可以看出 认证策略是ModularRealmAuthenticator 类的一个属性 authenticationStrategy

    即在applicationContext.xml中添加配置:

<!-- 配置多个Realm -->
<bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<property name="realms">
<list>
<ref bean="jdbcRealm"/>
<ref bean="secondRealm"/>
</list>
</property>
<property name="authenticationStrategy">
<bean class="org.apache.shiro.authc.pam.AllSuccessfulStrategy"></bean>
</property>

</bean>

    修改其中一个Realm的密码 为一个错误的密码:

    if("admin".equals(username)){
credentials = "ce2f6417c7e1d32c1d81a797ee0b499f87c5de06---";
}else if("user".equals(username)){
credentials = "073d4c3ae812935f23cb3f2a71943f49e082a718---";
}

    则可以看到修改后的验证策略为:

    org.apache.shiro.authc.pam.AllSuccessfulStrategy@72f51247

[FirstRealm] doGetAuthenticationInfo org.apache.shiro.authc.UsernamePasswordToken - admin, rememberMe=true
从数据库中获取userName :admin 所对应的用户信息.
[SecondRealm] doGetAuthenticationInfo org.apache.shiro.authc.UsernamePasswordToken - admin, rememberMe=true
从数据库中获取userName :admin 所对应的用户信息.
登录失败:Unable to acquire account data from realm [com.java.shiro.realms.SecondRealm@349102eb]. The [org.apache.shiro.authc.pam.AllSuccessfulStrategy implementation requires all configured realm(s) to operate successfully for a successful authentication.

Shiro-多Realm验证的更多相关文章

  1. shiro双realm验证

    假设现在有这样一种需求:存在两张表user和admin,分别记录普通用户和管理员的信息.并且现在要实现普通用户和管理员的分开登录,即需要两个Realm——UserRealm和AdminRealm,分别 ...

  2. shiro多realm验证之——shiro实现不同身份使用不同Realm进行验证(转)

    转自: http://blog.csdn.net/xiangwanpeng/article/details/54802509 (使用特定的realm实现特定的验证) 假设现在有这样一种需求:存在两张表 ...

  3. Shiro多Realm验证

    在单Realm的基础上,进行如下内容的修改 原有的ShiroRealm.java: package com.atguigu.shiro.realms; import org.apache.shiro. ...

  4. Shiro自定义realm实现密码验证及登录、密码加密注册、修改密码的验证

    一:先从登录开始,直接看代码 @RequestMapping(value="dologin",method = {RequestMethod.GET, RequestMethod. ...

  5. Shiro固定身份验证

    Shiro基础身份验证 如果要进行shiro的日志信息读取,那么需要使用一个org.apache.shiro.util.Factory接口,在这个接口里面定义有一 取得SecuruityManager ...

  6. 基于权限安全框架Shiro的登录验证功能实现

    目前在企业级项目里做权限安全方面喜欢使用Apache开源的Shiro框架或者Spring框架的子框架Spring Security. Apache Shiro是一个强大且易用的Java安全框架,执行身 ...

  7. Shiro笔记(四)Shiro的realm认证

    认证流程: 1.获取当前Subject.调用SecurityUtils.getSubject(); 2.测试当前用户是否已经被认证,即是否已经登录,调用Subject的isAurhenticated( ...

  8. Shiro中Realm

    6.1 Realm [2.5 Realm]及[3.5 Authorizer]部分都已经详细介绍过Realm了,接下来再来看一下一般真实环境下的Realm如何实现. 1.定义实体及关系   即用户-角色 ...

  9. shiro登陆权限验证

    一>引入shirojar包 <!-- shiro登陆权限控制 -->        <dependency>            <groupId>org. ...

  10. shiro自定义Realm

    1.1 自定义Realm 上边的程序使用的是shiro自带的IniRealm,IniRealm从ini配置文件中读取用户的信息,大部分情况下需要从系统的数据库中读取用户信息,所以需要自定义realm. ...

随机推荐

  1. myeclipse 导入JAVA项目

    说白了.就是别人给你一份写好的文件你不会用是吧?新手都是这样的.很正常..这样.咱们一步一步的来.邮件项目工程栏,选择import,选择General,选择Existing Projects into ...

  2. delphi action学习

    procedure TEditAction.UpdateTarget(Target: TObject); begin if (Self is TEditCut) then Enabled := (Ge ...

  3. 使用Python来对MySQL数据库进行操作

    使用Python对Mysql进行操作,前提是安装了python-Mysql的安装包,安装的方法有多种,可以使用easy_install或者pip  或者是源码进行安装. 下面介绍下如何使用Python ...

  4. Oracle 查询库中所有表名、字段名、字段名说明,查询表的数据条数、表名、中文表名、

    查询所有表名:select t.table_name from user_tables t;查询所有字段名:select t.column_name from user_col_comments t; ...

  5. WPF的图片操作效果(一):RenderTransform

    一.RenderTransform类的成员: 1.TranslateTransform 平移效果 2.RotateTransform 旋转效果 3.ScaleTransform       缩放效果 ...

  6. XidianOJ 1177 Counting Stars

    题目描述 "But baby, I've been, I've been praying hard,     Said, no more counting dollars     We'll ...

  7. Mysql命令行中文乱码的解决方法

    环境:Windows 8 64位,Mysql  5.0.96 for Win64 (x86) 数据库本身安装时默认已经是使用utf8编码的了,但在命令行中执行查询时,查询到的中文依然乱码,解决方法如下 ...

  8. kali 虚拟机开启mysql:3306 供主机访问.

    mysql -u root -p use mysql; update user set host='ip' where user='root'; //更新访问权限 flush privileges; ...

  9. Python学习笔记(二)基本语法

    Class 2 一.交互式编程 交互式编程不需要创建脚本文件,是通过 Python 解释器的交互模式进来编写代码. linux上你只需要在命令行中输入 Python 命令即可启动交互式编程,如下图: ...

  10. Python延迟打印字符

    我想让python打印类似“正在加载...”,每个句号打印出来与它们之间的睡眠时间0.5秒间隔 实现方法: 1 2 3 4 5 6 7 8 9 10 11 #!/bin/env python # -* ...