1. 程式人生 > >Shiro(二)——Shiro授權

Shiro(二)——Shiro授權

一、程式碼

package first.ShiroTest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Before;
import org.junit.Test;

public class AuthenticationTest {

	SimpleAccountRealm simpleAccountRealm =new SimpleAccountRealm();
	
	@Before
	public void addUser() {
		simpleAccountRealm.addAccount("mark", "123456","admin","user");
	}
	
	//Shiro授權
	@Test
	public void testAuthentication2() {
		//1、構建SecurityManager環境
		//安全管理器。即所有與安全有關的操作都會與SecurityManager互動
		DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
		defaultSecurityManager.setRealm(simpleAccountRealm);
		
		//2、主體提交認證請求
		SecurityUtils.setSecurityManager(defaultSecurityManager);
		Subject subject = SecurityUtils.getSubject();//獲取主體
		UsernamePasswordToken token = new UsernamePasswordToken("mark", "123456");//提交認證
		subject.login(token);
		System.out.println("是否認證:"+subject.isAuthenticated());
		
		subject.checkRoles("admin","user");
	}
	
}

二、過程

開始add使用者的時候,系統增加了admin和user兩個角色

simpleAccountRealm.addAccount("mark", "123456","admin","user");

後面通過checkRole驗證授權是否成功

三、授權常用方法

  1. subject.checkRole("admin");
  2. subject.checkRoles("admin","user");

 

資源下載:https://gitee.com/luozh6/ShiroTest.git