使用 test 完成最基本简单的认证流程。
1、认证流程
1、创建 securityManager
2、主体(subject) 提交请求
3、securityManager 认证
4、Authenticator 认证
5、Realm 验证
2、引入依赖
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
3、 编写测试代码
package ch.shiro.test;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
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;
/**
* 认证测试类.
*
* @author ch
* @version 1.0.0
* @since 1.0.0
* <p>
* Created at 2020/8/19 4:52 下午
*/
public class AuthenticationTest {
// realm
SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();
@Before
public void addUser() {
// 给realm 赋值 account
simpleAccountRealm.addAccount("ch", "123");
}
@Test
public void testAuthentication() {
// 1、构建 securityManager(提供安全服务) 环境
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
defaultSecurityManager.setRealm(simpleAccountRealm);
// 2、主体 subject 提交认证请求
SecurityUtils.setSecurityManager(defaultSecurityManager); // 配置环境
Subject subject = SecurityUtils.getSubject();
// 配置自定的token
UsernamePasswordToken token = new UsernamePasswordToken("ch", "123");
// 登录
subject.login(token);
System.out.println("isAuthenticated: " + subject.isAuthenticated());
// 登出
subject.logout();
System.out.println("isAuthenticated: " + subject.isAuthenticated());
}
}
console :
如果修改账号,则会报错:
如果修改密码,则会报错: