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. 【转】操作权限不够?教你开启Win7管理员帐户

    在Win7中进行一些设置,或修改某些文件时,经常会弹出当前帐户没有操作权限的提示,即使已经是管理员账户也不行.事实上,出于安全方面的考虑,默认情况下Win7系统的系统管理员Administrator账 ...

  2. mongodb下载、安装、配置服务启动、及可视化工具下载、使用

    MongoDB: 1.下载地址:http://www.mongodb.org/downloads(32位还是64位自行选择).我下载的是:mongodb-win32-x86_64-3.2.4-sign ...

  3. vc++ basic chapt1

    ______API 和SDK _像c程序可以调用各种函数库一样, windows操作系统提供应用程序编程的接口application programming interface简称API函数. 所以主 ...

  4. js 构造函数

    //构造函数  //使自己的对象多次复制,同时实例根据设置的访问等级可以访问其内部的属性和方法  //当对象被实例化后,构造函数会立即执行它所包含的任何代码  function myObject(ms ...

  5. linux配置的问题

    1 从系统设置-文本设置中把双拼删掉 2 通过sudo passwd root 修改root密码 3 通过su获取root权限 4 通过sudo pppoeconf输入宽带帐号密码 5 把更新源修改成 ...

  6. WordPress建站指南

    WordPress建站指南(1)   写在前面: 3月份用10天零碎时间火速完成了建站,后台95%的工作都交给了WP(WordPress).如果想偷懒的话,WP是一个绝好的选择,估计有个小半天就建完收 ...

  7. Gradle basic

    1. execute default file (build.gradle) gradlew 2. execute another file gradlew -b [filename] 3.  bas ...

  8. 自定义UIPageControl,可设置任意图片image。

    [self.pageControl setValue:[UIImage imageNamed:@"选中图片名称"] forKeyPath:@"_currentPageIm ...

  9. MATLAB - 练习程序,求灰度图像均值、最大、最小数值

    clear all; close all; clc img=imread('lena.bmp'); figure; imshow(uint8(img)); [m n]=size(img); img_m ...

  10. nil、Nil、NULL和NSNull的区别和联系

    一.nil 我们给对象赋值时一般会使用object = nil,表示我想把这个对象释放掉: 或者对象由于某种原因,经过多次release,于是对象引用计数器为0了,系统将这块内存释放掉,这个时候这个对 ...