Shiro身份认证、Realm&JDBC Reaml

一、Subject认证主题


Subject认证主题包含两个信息:

1、Principals:身份,可以是用户名,邮件,手机号码等等,用来标识一个登录主体身份;

2、Credentials:凭证,常见有密码,数字证书等等;


二、身份认证流程

Shiro身份认证、Realm&JDBC Reaml_第1张图片

三、Realm&JDBC Reaml

Realm:意思是域,Shiro 从 Realm 中获取验证数据;

Realm 有很多种类,例如常见的 jdbc realm,jndi realm,text realm

1、shiro配置文件

[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


2、POM配置文件

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.java.shiro
Shiro
0.0.1-SNAPSHOT


org.apache.shiro
shiro-core
1.2.4


org.slf4j
slf4j-log4j12
1.7.12


c3p0
c3p0
0.9.1.2


commons-logging
commons-logging
1.2


mysql
mysql-connector-java
5.1.37



 3、源码

package com.java.shiro;
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 JdbcRealmTest {
public static void main(String[] args) {
// 读取配置文件,初始化SecurityManager工厂
Factory 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("Steven","123456");
try {
// 身份认证
currentUser.login(token);
System.out.println("身份认证成功!");
} catch (AuthenticationException e) {
e.printStackTrace();
System.out.println("身份认证失败!");
}
// 退出
currentUser.logout();
}
}

你可能感兴趣的:(Shiro)