第一节将验证信息realm写定在shiro.ini中,这种方法在项目的实际开发中明显是不现实的,这次就要通过简单的案例实现jdbcrealm,即使用jdbc从数据库中读取验证信息。项目的开发环境依然是MAVEN,配置结构如图:
首先是配置pom.xml,添加所需的支持,以下是需要添加的内容:
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.42</version>
</dependency>
下面是重要环节了!!!配置jdbc_realm.ini:
[main]
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/db_shiro
dataSource.user=root
dataSource.password=123456
jdbcRealm.dataSource=$dataSource
securityManager.realms=$jdbcRealm
下图所示即我们需要建立的数据库表,比较简单:
lo4j.properties文件的配置与上节相同,这里就不贴出来了,最后就是验证的过程JdbcRealm.java:
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
public class JdbcRealm {
public static void main(String[] args) {
//读取配置文件,初始化SecurityManager工厂
Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:jdbc_realm.ini");
//获取SecurityManager实例
SecurityManager securityManager=factory.getInstance();
//将SecurityManager实例绑定到SecurityUtils
SecurityUtils.setSecurityManager(securityManager);
//得到当前执行的用户
Subject currentUser=SecurityUtils.getSubject();
//创建token令牌:用户名&密码
UsernamePasswordToken token=new UsernamePasswordToken("xk","123");
try{
//身份认证
currentUser.login(token);
System.out.println("登录成功!");
}catch(AuthenticationException e){
e.printStackTrace();
System.out.println("登录失败!");
}
//退出
currentUser.logout();
}
}
其实整个过程与第一节所述类似,不一样的地方在于realm的数据获取方式,这里配置的事jdbc的获取方法,当然shiro可以整合Spring、Mybatis等框架实现更为复杂的功能,以用于企业级开发。