1. 程式人生 > >shiro之SimpleAccountRealm

shiro之SimpleAccountRealm

我使用的是maven構建的工程,junit測試

Shiro認證過程
建立SecurityManager---》主體提交認證---》SecurityManager認證---》Authenticsto認證---》Realm驗證

Shiro授權過程
建立SecurityManager---》主體授權---》ecurityManager授權---》Authorizer授權---》Realm獲取角色許可權資料

 

1.匯入依賴

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>ylht-shiro</artifactId> <groupId>com.ylht</groupId> <version>
1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>shiro-test</artifactId> <dependencies> <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core --> <dependency> <groupId
>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.4.0</version> </dependency> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.7</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.45</version> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.6</version> </dependency> </dependencies> </project>

 

2.測試類

 
 
package com.ylht.shiro.test;

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 AuthenticateTest {

//定義realm
SimpleAccountRealm realm = new SimpleAccountRealm();

@Before
public void addUser(){
//realm定義多個角色
//username,password,roles(後面用逗號隔開)
realm.addAccount("admin","admin","admin","user");
}

@Test
public void testAuthenticate() {
//1.建立SecurityManager
DefaultSecurityManager securityManager = new DefaultSecurityManager();
securityManager.setRealm(realm);

//2.主題提交認證
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();

UsernamePasswordToken token = new UsernamePasswordToken("admin", "admin");
subject.login(token);

System.out.println(subject.isAuthenticated());

//subject.logout();

//System.out.println(subject.isAuthenticated());
//驗證多個授權
subject.checkRoles("admin","user");

}
}