第二章 身份验证 (二) Realm + Authenticator及AuthenticationStrategy

Realm:域,Shiro 从从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法;也需要从Realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把Realm看成DataSource , 即安全数据源。如我们之前的ini 配置方式将使用org.apache.shiro.realm.text.IniRealm。

org.apache.shiro.realm.Realm接口如下:

String getName(); //返回一个唯一的Realm名字
boolean supports(AuthenticationToken token); //判断此Realm是否支持此Token
AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException; //根据Token获取认证信息

一、单Ream配置

1. 自定义Realm实现

public class MyRealm1 implements Realm{
	/*
	 * 返回一个唯一的Realm名字
	 */
	public String getName() {
		return "myrealm1";
	}
	/*
	 * 判断此Realm是否支持此Token
	 */
	public boolean supports(AuthenticationToken token) {
		//仅支持UsernamePasswordToken类型的Token
		return token instanceof UsernamePasswordToken;
	}
	/*
	 * 根据Token获取认证信息
	 */
	public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) {
		String username = (String) token.getPrincipal();//得到用户名
		String password = new String((char[])token.getCredentials());//得到密码
		if(!"zhang".equals(username)){
			throw new UnknownAccountException();//如果用户名错误
		}
		if(!"123".equals(password)){
			throw new IncorrectCredentialsException();//如果密码错误
		}
		//如果身份认证验证成功,返回一个AuthenticationInfo实现
		return new SimpleAuthenticationInfo(username,password,getName());
	}
}

2. ini配置文件指定自定义Realm实现(shiro-realm.ini)

#声明一个realm
myRealm1=chapter2.realm.MyRealm1
#指定securityManager的realms实现
securityManager.realms=$myRealm1
3. 测试

public class LoginLogoutTest {
	@Test
	public void testHelloworld(){
		//1. 获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager
		Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-realm.ini");
		//2. 得到SecurityManager实例,并绑定给SecurityUtils
		SecurityManager securityManager = factory.getInstance();
		SecurityUtils.setSecurityManager(securityManager);
		//3. 得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证),会自动绑定到当前线程。
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken("zhang","123");
		try {
			//4. 登录,即身份验证
			subject.login(token);
		} catch (AuthenticationException e) {
			//5. 身份验证失败
		}
		Assert.assertEquals(true, subject.isAuthenticated());
		//6. 退出
		subject.logout();
	}
}
二、多Realm配置

1. ini配置文件(shiro-multi-realm.ini)

#声明一个realm
myRealm1=chapter2.realm.MyRealm1
myRealm2=chapter2.realm.MyRealm2
#指定securityManager的realms实现
securityManager.realms=$myRealm1,$myRealm2
securityManager会按照realms指定的顺序进行身份认证。如果设置“securityManager.realms=$myRealm1”,那么myRealm2 不会被自动设置进去。

三、Shiro默认提供的Realm

一般继承AuthorizingRealm(授权)即可;其继承了AuthenticatingRealm(即身份验证),而且也间接继承了CachingRealm(带有缓存实现)

主要默认实现如下:

org.apache.shiro.realm.text.IniRealm:IniRealm:[users]部分指定用户名/密码及其角色;[roles]部分指定角色即权限信息;

org.apache.shiro.realm.text.PropertiesRealm:user.username=password,role1,role2指定用户名/密码及其角色;role.role1=permission1,permission2指定角色及权限信息

org.apache.shiro.realm.jdbc.JdbcRealm:通过sql查询相应的信息,如“select password from users where username = ?”获取用户密码,“select password, password_salt from users where username = ?”获取用户密码及盐;“select role_name from user_roles where username = ?” 获取用户角色;“select permission from roles_permissions where role_name = ?”获取角色对应的权限信息;也可以调用相应的api进行自定义sql;

四、JDBC Realm使用

材料:MySql + C3P0

1. 数据准备

到数据库shiro 下建三张表:users(用户名/密码)、user_roles(用户/角色)、roles_permissions(角色/权限),并添加一个用户记录,用户名/密码为zhang/123;

drop database if exists shiro;
create database shiro;
use shiro;

create table users (
  id bigint auto_increment,
  username varchar(100),
  password varchar(100),
  password_salt varchar(100),
  constraint pk_users primary key(id)
) charset=utf8 ENGINE=InnoDB;
create unique index idx_users_username on users(username);

create table user_roles(
  id bigint auto_increment,
  username varchar(100),
  role_name varchar(100),
  constraint pk_user_roles primary key(id)
) charset=utf8 ENGINE=InnoDB;
create unique index idx_user_roles on user_roles(username, role_name);

create table roles_permissions(
  id bigint auto_increment,
  role_name varchar(100),
  permission varchar(100),
  constraint pk_roles_permissions primary key(id)
) charset=utf8 ENGINE=InnoDB;
create unique index idx_roles_permissions on roles_permissions(role_name, permission);

insert into users(username,password)values('zhang','123');

2. shiro-jdbc-realm.ini

jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
dataSource=com.mchange.v2.c3p0.ComboPooledDataSource
dataSource.driverClass=com.mysql.jdbc.Driver
dataSource.jdbcUrl=jdbc:mysql://localhost:3306/shiro
dataSource.user=root
dataSource.password=123456
jdbcRealm.dataSource=$dataSource
securityManager.realms=$jdbcRealm
3. 测试代码和上例相同,只用修改对应的realm.ini文件即可。


五、Authenticator及AuthenticationStrategy

Authenticator的职责是验证用户帐号,是Shiro API中身份验证核心的入口点:

public AuthenticationInfo authenticate(AuthenticationToken authenticationToken) throws AuthenticationException;

如果验证成功,将返回AuthenticationInfo 验证信息;此信息中包含了身份及凭证;如果验证失败将抛出相应的AuthenticationException实现。

SecurityManager接口继承了Authenticator,另外还有一个ModularRealmAuthenticator实现其委托给多个Realm 进行验证,验证规则通过AuthenticationStrategy 接口指定,默认提供的实现:

FirstSuccessfulStrategy:只要有一个Realm验证成功即可,只返回第一个Realm身份验证成功的认证信息,其他的忽略;

AtLeastOneSuccessfulStrategy:只要有一个Realm验证成功即可,和FirstSuccessfulStrategy不同,返回所有Realm身份验证成功的认证信息;

AllSuccessfulStrategy:所有Realm验证成功才算成功,且返回所有Realm身份验证成功的认证信息,如果有一个失败就失败了。

ModularRealmAuthenticator默认使用AtLeastOneSuccessfulStrategy策略。

1. realm

假设我们有三个realm:

myRealm1: 用户名/密码为zhang/123时成功,且返回身份/凭据为zhang/123;(如下)

myRealm2: 用户名/密码为wang/123 时成功,且返回身份/凭据为wang/123;(和myRealm1相似)

myRealm3: 用户名/密码为zhang/123 时成功,且返回身份/凭据为zhang@163.com/123,和myRealm1 不同的是返回时的身份变了;(和myRealm1相似)

public class MyRealm1 implements Realm{
	/*
	 * 返回一个唯一的Realm名字
	 */
	public String getName() {
		return "myrealm1";
	}
	/*
	 * 判断此Realm是否支持此Token
	 */
	public boolean supports(AuthenticationToken token) {
		//仅支持UsernamePasswordToken类型的Token
		return token instanceof UsernamePasswordToken;
	}
	/*
	 * 根据Token获取认证信息
	 */
	public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) {
		String username = (String) token.getPrincipal();//得到用户名
		String password = new String((char[])token.getCredentials());//得到密码
		if(!"zhang".equals(username)){
			throw new UnknownAccountException();//如果用户名错误
		}
		if(!"123".equals(password)){
			throw new IncorrectCredentialsException();//如果密码错误
		}
		//如果身份认证验证成功,返回一个AuthenticationInfo实现
		return new SimpleAuthenticationInfo(username,password,getName());
	}
}

2. ini配置文件(shiro-authenticator-all-success.ini)

#指定securityManager的authenticator实现
authenticator=org.apache.shiro.authc.pam.ModularRealmAuthenticator
securityManager.authenticator=$authenticator

#指定securityManager.authenticator的authenticationStrategy
allSuccessfulStrategy=org.apache.shiro.authc.pam.AllSuccessfulStrategy
securityManager.authenticator.authenticationStrategy=$allSuccessfulStrategy

myRealm1=chapter2.realm.MyRealm1
myRealm2=chapter2.realm.MyRealm2
myRealm3=chapter2.realm.MyRealm3
securityManager.realms=$myRealm1,$myRealm3
3. 测试代码

public class AuthenticatorTest {
	/*
	 * 测试AllSuccessfulStrategy成功
	 */
	@Test
	public void testAllSuccessfulStrategyWithSuccess(){
		login("classpath:shiro-authenticator-all-success.ini");
		Subject subject = SecurityUtils.getSubject();
		//得到一个身份集合,其包含了Realm验证成功的身份信息
		PrincipalCollection principalCollection = subject.getPrincipals();
		Assert.assertEquals(2, principalCollection.asList().size());
	}
	/*
	 * 测试AllSuccessfulStrategy失败
	 */
	@Test
	public void testAllSuccessfulStrategyWithFail(){
		login("classpath:shiro-authenticator-all-fail.ini");
		Subject subject = SecurityUtils.getSubject();
		//得到一个身份集合,其包含了Realm验证成功的身份信息
		PrincipalCollection principalCollection = subject.getPrincipals();
		Assert.assertEquals(2, principalCollection.asList().size());
	}
	public void login(String configFile){
		//1. 获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager
		Factory<SecurityManager> factory = new IniSecurityManagerFactory(configFile);
		//2. 得到SecurityManager实例,并绑定给SecurityUtils
		SecurityManager securityManager = factory.getInstance();
		SecurityUtils.setSecurityManager(securityManager);
		//3. 得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证)
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken("zhang","123");
		
		subject.login(token);
	}
}
上面是 securityManager.authenticator.authenticationStrategy中对于 AllSuccessfulStrategy的实现。但对于 AtLeastOneSuccessfulStrategy FirstSuccessfulStrategy的唯一不同点一个是返回所有验证成功的Realm 的认证信息;另一个是只返回第一个验证成功的Realm的认证信息。

4. 自定义AuthenticationStrategy实现,首先看其API:

//在所有Realm验证之前调用
AuthenticationInfo beforeAllAttempts(Collection<? extends Realm> realms, AuthenticationToken token);
//在每个Realm之前调用
AuthenticationInfo beforeAttempt(Realm realm, AuthenticationToken token, AuthenticationInfo aggregate);
//在每个Realm之后调用
AuthenticationInfo afterAttempt(Realm realm, AuthenticationToken token,AuthenticationInfo singleRealmInfo, AuthenticationInfo aggregateInfo, Throwable t);
//在所有Realm之后调用
AuthenticationInfo afterAllAttempts(AuthenticationToken token, AuthenticationInfo aggregate);
因为每个AuthenticationStrategy 实例都是无状态的,所有每次都通过接口将相应的认证信息传入下一次流程;通过如上接口可以进行如合并/返回第一个验证成功的认证信息。自定义实现时一般继承org.apache.shiro.authc.pam.AbstractAuthenticationStrategy即可,具体可以参考代码com.github.zhangkaitao.shiro.chapter2.authenticator.strategy 包下OnlyOneAuthenticatorStrategy 和AtLeastTwoAuthenticatorStrategy。

到此基本的身份验证就搞定了,对于AuthenticationToken 、AuthenticationInfo和Realm的详细使用后续章节再陆续介绍

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值