shiro身份验证实例
个人博客
一、最简单shiro实例
1、需要导入的依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.9</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.2</version>
</dependency>
</dependencies>
2、新建配置文件shiro.ini
[users]
sumu=123456
sm=123456
;其中sumu表示用户名,123456 表示密码
3、使用测试
@Test
public void testFirstShiro(){
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("sumu", "123456");
try {
subject.login(token);
} catch (AuthenticationException e) {
}
Assert.assertEquals(true, subject.isAuthenticated());
subject.logout();
}
二、自定义realm
1、自定义myrealm01
public class myRealm01 implements Realm {
@Override
public String getName() {
return "myRealm01";
}
@Override
public boolean supports(AuthenticationToken authenticationToken) {
return authenticationToken instanceof UsernamePasswordToken;
}
@Override
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String username = (String)authenticationToken.getPrincipal();
String password = new String((char[])authenticationToken.getCredentials());
System.out.println(username);
System.out.println(password);
if(!"sumu".equals(username)) {
throw new UnknownAccountException();
}
if(!"123456".equals(password)) {
throw new IncorrectCredentialsException();
}
return new SimpleAuthenticationInfo(username, password, getName());
}
}
2、修改配置文件
;声明一个realm
myrealm01=feng.com.reaml.myRealm01
; 指定securityManager的realm实现
securityManager.realm=$myrealm01
3、使用测试
public void testFirstShiro(){
//1、获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-realm.ini");
//2、得到SecurityManager实例 并绑定给SecurityUtils
org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
//3、得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证)
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("sumu", "123456");
System.out.println(token.getPassword());
try {
//4、登录,即身份验证
subject.login(token);
} catch (AuthenticationException e) {
//5、身份验证失败
}
Assert.assertEquals(true, subject.isAuthenticated()); //断言用户已经登录
//6、退出
subject.logout();
}