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

猜你喜欢

转载自blog.csdn.net/qq_37436998/article/details/85331566