Shrio許可權驗證-簡單案例
阿新 • • 發佈:2018-12-14
建立maven專案,配置pom如下:
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.4.0</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency>
簡單驗證案例:
public class AuthenticationTest { private SimpleAccountRealm simpleAccountRealm= new SimpleAccountRealm(); @Before public void addUser(){ //simpleAccountRealm.addAccount("link","123456",); //新增角色、可同時新增多個角色 simpleAccountRealm.addAccount("link","123456","admin"); } @Test public void testAuthentication(){ //1、構建SecurityManger環境 DefaultSecurityManager defaultSecurityManager= new DefaultSecurityManager(); defaultSecurityManager.setRealm(simpleAccountRealm); //2、主體提交認證請求 SecurityUtils.setSecurityManager(defaultSecurityManager); Subject subject= SecurityUtils.getSubject(); UsernamePasswordToken token= new UsernamePasswordToken("link","123456"); subject.login(token); System.out.println("Authenticated:"+subject.isAuthenticated()); //角色驗證 subject.checkRole("admin"); //退出 subject.logout(); System.out.println("Authenticated:"+subject.isAuthenticated()); } }