自定义Realm来实现身份认证
1.jdbcRealm已经实现了从数据库获取用户的验证信息,但是灵活性太差必须按照shiro命名规则建表建字段,如果要实现自己的一些特殊应用时将无法支持,这个时候可以通过自定义Realm来实现。
2.Realm是一个接口,在接口中定义了根据token获得认证信息的方法,shiro内容实现了一些列的Realm,这些不同Realm实现类提供了不同的功能。
AuthenticatingRealm
实现了获取身份信息的功能。
AuthorizingRealm
实现了获取权限信息的功能。
通常自定义Realm需要继承AuthorizingRealm,这样既可以提供身份认证的自定义方法,也可以实现授权的自定义方法。
3.实现自定义Realm
ini配置文件:
[main]
UserRealm=com.lyh.UserRealm_demo
securityManager.realms=$UserRealm
[users]
自定义Realm类代码:
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
public class UserRealm_demo extends AuthorizingRealm{
@Override
public String getName() {
return "UserRealm";
}
//授权方法
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
//完成身份认证(我们只是取数据),并且返回身份信息,如果失败返回null
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//获取身份信息,获取用户输入的用户名
String username = (String)authenticationToken.getPrincipal();
System.out.println("username==========="+username);
//根据用户名到数据库查询密码
//模拟从数据库获得密码123
String pwd="123";
//将从数据库中查询的信息,封装到SimpleAuthenticationInfo中
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username,pwd,getName());
return info;
}
}
shiro测试代码:
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;
import org.apache.shiro.util.Factory;
public class TestUserRealm_demo {
public static void main(String[] args) {
//1、获取SecurityManager工厂,此处使用Ini配置文件初始化SecurityManager
Factory<SecurityManager> factory= new IniSecurityManagerFactory("classpath:zidingyiRealm.ini");
//2、得到SecurityManager实例 并绑定给SecurityUtils
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
//3、得到Subject及创建用户名/密码身份验证Token(即用户身份/凭证)
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("wangwu", "123");
try {
subject.login(token);
if(subject.isAuthenticated()){
System.out.println("验证通过");
}
} catch (AuthenticationException e) {
e.printStackTrace();
System.out.println("验证失败");
}
}
}
网友评论