IniRealm验证:
在resource目录下配置:user.ini文件
[users]
link=123456,admin
[roles]
admin=user:delete,user:update
public class IniRealmTest {
//ini文件验证
IniRealm iniRealm=new IniRealm("classpath:user.ini");
@Test
public void testAuthentication(){
//1、构建SecurityManger环境
DefaultSecurityManager defaultSecurityManager=new DefaultSecurityManager();
defaultSecurityManager.setRealm(iniRealm);
//2、主体提交认证请求
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject= SecurityUtils.getSubject();
UsernamePasswordToken token=new UsernamePasswordToken("link","123456");
subject.login(token);
System.out.println("Authenticated:"+subject.isAuthenticated());
//subject.checkRole("admin");
subject.checkPermission("user:delete");
subject.checkPermission("user:update");
}
}
JdbcRealm验证:
配置pom:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
建立数据库test,创建权限表users
public class JdbcRealmTest{
DruidDataSource dataSource=new DruidDataSource();
@Before
public void JDBCRealmSet(){
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("123456");
}
@Test
public void testAuthentication(){
JdbcRealm jdbcRealm=new JdbcRealm();
jdbcRealm.setDataSource(dataSource);
jdbcRealm.setPermissionsLookupEnabled(true);
String sql="select password from user where username=?";
jdbcRealm.setAuthenticationQuery(sql);
//1、构建SecurityManger环境
DefaultSecurityManager defaultSecurityManager=
new DefaultSecurityManager();
defaultSecurityManager.setRealm(jdbcRealm);
//2、主体提交认证请求
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject= SecurityUtils.getSubject();
UsernamePasswordToken token=
new UsernamePasswordToken("link","123456");
subject.login(token);
System.out.println("Authenticated:"+subject.isAuthenticated());
}
}