1、新建Maven项目
2、在原有的项目上新建一个module
3、在新的module模块下pom文件添加依赖
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
</dependency>
</dependencies>
4、在test目录下面创建一个AuthenticationTest类
package com.zjc.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 AuthenticationTest {
SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();
@Before
public void addUser(){
simpleAccountRealm.addAccount("jiangcheng","123456");
simpleAccountRealm.addAccount("jiangcheng1","1234567");
}
@Test
public void testAuthentication(){
//构建SecurityManager环境
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
defaultSecurityManager.setRealm(simpleAccountRealm);
//主体提交认证系统
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject = SecurityUtils.getSubject();
//若账户输入出错 会出现 未知账户异常
//org.apache.shiro.authc.UnknownAccountException:
// Realm [org.apache.shiro.realm.SimpleAccountRealm@7a92922]
// was unable to find account data for the submitted AuthenticationToken
// [org.apache.shiro.authc.UsernamePasswordToken - jiangcheng1, rememberMe=false].
//若密码输入出错 会出现 不正确的凭证异常
// org.apache.shiro.authc.IncorrectCredentialsException:
// Submitted credentials for token
// [org.apache.shiro.authc.UsernamePasswordToken - jiangcheng, rememberMe=false]
// did not match the expected credentials.
UsernamePasswordToken token = new UsernamePasswordToken("jiangcheng1","1234567");
//登陆
subject.login(token);
//验证是否成功
System.out.println("isAuthenticated:"+subject.isAuthenticated());
//登出
subject.logout();
System.out.println("isAuthenticated:"+subject.isAuthenticated());
}
}
网友评论