shiro基於權限的控制訪問

新建shiro_role_permission.ini文件
[users]
JAVA=123456,role1,role2
PHP=1234567,role1
[roles]
role1=user:select
role2=user:select,user:delete,user:update
/**
 * @author xp
 * @Title: ShiroUtil.java
 * @Package com.xp.shiro.roleshiro
 * @Description: TODO
 * @date 2016年4月24日 下午1:20:35
 * @version V1.0  
 */
package com.xp.shiro.roleshiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
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;

/**
 * @author xp
 * @ClassName: ShiroUtil
 * @Description: 基於角色的訪問控制
 * @date 2016年4月24日 下午1:20:35
 *
 */
public class ShiroUtil {

	public static Subject login(String configFile, String username, String password) {
		//讀取配置文件建立SecurityManager工廠
		Factory<SecurityManager> factory = new IniSecurityManagerFactory(configFile);

		//建立SecurityManager實例
		SecurityManager securityManager = factory.getInstance();

		//將securityManager和SecurityUtils綁定
		SecurityUtils.setSecurityManager(securityManager);

		//獲取當前登陸用戶
		Subject currentSubject = SecurityUtils.getSubject();

		UsernamePasswordToken token = null;
		try {
			//更具當前用戶的用戶名和密碼建立token令牌
			token = new UsernamePasswordToken(username, password);
			currentSubject.login(token);//這句話最好寫在try外面,用戶名密碼不對應當立刻拋異常
		} catch (UnknownAccountException e) {
			e.printStackTrace();
			System.out.println("登陸失敗");//ComboPooledDataSource
		}
		return currentSubject;
	}

}
/**
 * @author xp
 * @Title: PermissionTest.java
 * @Package com.xp.shiro.roleshiro
 * @Description: TODO
 * @date 2016年4月24日 下午2:20:32
 * @version V1.0  
 */
package com.xp.shiro.roleshiro;

import static org.junit.Assert.*;

import org.apache.shiro.subject.Subject;
import org.junit.Test;

/**
 * @author xp
 * @ClassName: PermissionTest
 * @Description: 基於權限的控制訪問
 * @date 2016年4月24日 下午2:20:32
 *
 */
public class PermissionTest {
	
	@Test
	public void testPermission()   {
		Subject subject = ShiroUtil.login("classpath:shiro_role_permission.ini", "JAVA", "123456");
		System.out.println(subject.isPermitted("user:select"));
	}

}
相關文章
相關標籤/搜索