Shiro-JdbcRealm

结构:

Shiro-JdbcRealm_第1张图片

依赖:

Shiro-JdbcRealm_第2张图片

jdbc_realm.ini:

[main]
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm

dataSource=com.mchange.v2.c3p0.ComboPooledDataSource
dataSource.driverClass=com.microsoft.sqlserver.jdbc.SQLServerDriver
dataSource.jdbcUrl=jdbc:sqlserver://localhost:1433;DatabaseName=xiaonei
dataSource.user=sa
dataSource.password=hyj84884824

jdbcRealm.dataSource=$dataSource

securityManager.realms=$jdbcRealm

JdbcRealmTest:

package com.java1234.shiro;

import org.apache.shiro.SecurityUtils;
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) {
		// TODO Auto-generated method stub
		//读取配置文件,初始化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("Aro","123456");
		try{
			//身份认证
			currentUser.login(token);
			System.out.println("身份认证成功");
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("身份认证失败");
		}
		//退出
		currentUser.logout();
	}

}

你可能感兴趣的:(shiro)