利用自定义的Realm进行Shiro的登录测试
第一步:导入依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
第二步:自定义Realm(MyRealm)
package com.day511.demoshiro.test;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.Realm;
public class MyRealm implements Realm {
@Override
public String getName() {
return "myrealm";
}
@Override
public boolean supports(AuthenticationToken authenticationToken) {
//限制数据源只支持UsernamePasswordToken
return authenticationToken instanceof UsernamePasswordToken;
}
@Override
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//模拟一条数据
String username = (String) authenticationToken.getPrincipal();
String password = new String((char[])authenticationToken.getCredentials());
if (!"test".equals(username)){
System.out.println("用户名不存在");
throw new UnknownAccountException();
}
if (!"123456".equals(password)){
System.out.println("密码错误");
throw new IncorrectCredentialsException();
}
return new SimpleAuthenticationInfo(username,password,getName());
}
}
第三步:编写Shiro测试类
package com.day511.demoshiro.test;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.authz.ModularRealmAuthorizer;
import org.apache.shiro.authz.permission.WildcardPermissionResolver;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
/**
* 一个简单的shiro 无数据库
*/
public class ShiroIniTest {
public static void main(String[] args) {
//启动ini文件时,自动默认创建一个securityManager对象
DefaultSecurityManager securityManager = new DefaultSecurityManager();
//设置身份验证的策略
ModularRealmAuthenticator authenticator = new ModularRealmAuthenticator();
//至少有一个这样的策略
authenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
//将这个策略指定给securityManager
securityManager.setAuthenticator(authenticator);
//设置授权
ModularRealmAuthorizer authorizer = new ModularRealmAuthorizer();
//用于解析对应的字符串
authorizer.setPermissionResolver(new WildcardPermissionResolver());
//授权
securityManager.setAuthorizer(authorizer);
//自定义数据源
securityManager.setRealm(new MyRealm());
//绑定上下文
SecurityUtils.setSecurityManager(securityManager);
//与当前系统进行交互的对象
Subject subject = SecurityUtils.getSubject();
//用户名 密 码 设置
UsernamePasswordToken token = new UsernamePasswordToken("test","123456");
try {
subject.login(token);
System.out.println("登陆成功");
}catch (AuthenticationException e){
// e.printStackTrace();
System.out.println("用户名或密码错误,登陆失败");
}
}
}