本案例使用maven去实验,以下是maven所需的坐标
<dependencies>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-all</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
对应的shiro.ini(放在src下面),使用账号为test,密码是test
[users]
test=test
[main]
userRealm=test.mylo.UserRealm
securityManager.realms=$userRealm
案例:
TestShiro
package test.mylo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
public class TestShiro {
public static void main(String[] args) {
//加载配置文件
IniSecurityManagerFactory ini = new IniSecurityManagerFactory("classpath:shiro.ini");
//获取securityManagers实例对象
SecurityManager securityManager = ini.getInstance();
//获取 SecurityManager 并绑定到 SecurityUtils
SecurityUtils.setSecurityManager(securityManager);
//获取当前主体对象
Subject subject = SecurityUtils.getSubject();
//设置当前的TOKEN
UsernamePasswordToken token = new UsernamePasswordToken("test", "test");
try {
System.out.println(1);
subject.login(token);
System.out.println("验证成功");
} catch (AuthenticationException e) {
//验证失败
e.printStackTrace();
System.out.println("验证失败");
}
}
}
自定义Realm
Realm:域,Shiro 从从 Realm 获取安全数据(如用户、角色、权限),就是说 SecurityManager 要验证用户身份,那么它需要从 Realm 获取相应的用户进行比较以确定用户身份是否合法;也需要从 Realm 得到用户相应的角色 / 权限进行验证用户是否能进行操作;可以把 Realm 看成 DataSource,即安全数据源。如我们之前的 ini 配置方式将使用 org.apache.shiro.realm.text.IniRealm。
package test.mylo;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.Realm;
public class UserRealm implements Realm{
@Override
//返回一个唯一的Realm名字
public String getName() {
return "userRealm";
}
@Override
//判断此Realm是否支持此Token
public boolean supports(AuthenticationToken token) {
return token instanceof UsernamePasswordToken;
}
//根据Token获取认证信息
@Override
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String)token.getPrincipal();
String password = new String((char[])token.getCredentials());
if("test".equals(username)){
if("test".equals(password)){
return new SimpleAuthenticationInfo(username,password,getName());
}else {
//用户密码错误
throw new IncorrectCredentialsException();
}
}else {
//用户账号错误
throw new UnknownAccountException();
}
}
} |
|