Shiro内置Realm之IniRealm
2018-12-07 本文已影响0人
jarWorker
Shiro内置Realm
- IniRealm
-
JdbcRealm
happy
IniRealm
主要是将数据存放到相应的xxx.ini
即文件系统中,从文件中查找相应的数据是否存在。
本文中文件放置在系统类路径下
认证userAuthenticator.ini
#用来认证
#============================
#设置用户,可设置多名用户
[users]
jarworker=123
小明=1234
授权userAuthorizer.ini
#用来授权
#===========================
#设置用户及用户角色
[users]
jarworker=123,admin
#设置角色与角色权限
[roles]
admin=user:delete,user:update
tourist=user:query
maven依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
测试用例
package com.jarworker.test;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Before;
import org.junit.Test;
/**
* Shiro的IniRealm
*/
public class IniRealmTest {
IniRealm iniRealm;
IniRealm iniRealm_1;
@Before
public void addIniRealmTestUser() throws Exception {
iniRealm=new IniRealm("classpath:userAuthenticator.ini");//认证
iniRealm_1=new IniRealm("classpath:userAuthorizer.ini");//授权
}
/**
* 认证过程
* @throws Exception
*/
@Test
public void testIniRealmAuthenticator() throws Exception {
//构建DefaultSecurityManager 环境
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
defaultSecurityManager.setRealm(iniRealm);
//主体提交认证请求
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("小明","1234");
subject.login(token);
System.out.println("是否认证:"+subject.isAuthenticated());
}
/**
* 授权过程
* @throws Exception
*/
@Test
public void testIniRealmAuthorizer() throws Exception {
//构建DefaultSecurityManager 环境
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
defaultSecurityManager.setRealm(iniRealm_1);
//主体提交认证请求
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("jarworker","123");
subject.login(token);
System.out.println("是否认证:"+subject.isAuthenticated());
subject.checkRoles("admin");
subject.checkPermission("user:delete");//是否拥有删除的权限
subject.checkPermission("user:update");//是否拥有更新的权限
}
}