编写代码测试认证
- 创建maven工程,引入shiro和junit依赖
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
package mao.shu.shiro;
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 ShiroTest {
private SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();
@Before
public void before(){
simpleAccountRealm.addAccount("xiemaoshu","123456");
}
@Test
public void testFun(){
// 创建SecurityManager环境
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
defaultSecurityManager.setRealm(simpleAccountRealm);
// 主体发送请求
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("xiemaoshu","123456");
subject.login(usernamePasswordToken);
// 打印验证结果
System.out.println(subject.isAuthenticated());
// 退出登录
subject.logout();
System.out.println(subject.isAuthenticated());
}
}
shiro授权
package mao.shu.shiro;
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 ShiroTestAuthorization {
private SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();
@Before
public void before(){
// 添加账户 并添加对应的角色信息
simpleAccountRealm.addAccount("xiemaoshu","123456","admin","admin1");
}
@Test
public void testFun(){
// 创建SecurityManager环境
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
defaultSecurityManager.setRealm(simpleAccountRealm);
// 主体发送请求
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("xiemaoshu","123456");
subject.login(usernamePasswordToken);
// 打印验证结果
System.out.println(subject.isAuthenticated());
// 检查主体是否具有 "admin"这个角色
subject.checkRole("admin1");
}
}
- 了解shiro的认证过程和shiro的授权过程对于学习shiro非常重要,