菜鸟从零开始编程
shiro自定义realm
我们知道shiro这个框架提供了信息认证和授权的功能性接口,但是shiro是不会帮我们维护数据的,shiro中的用户信息以及用户所对应的权限都是需要我们从数据库查询出来然后传给shiro相对应的接口,因此单单一个jdbcRealm已经无法满足我们的需求了,因为jdbcRealm是写死了的,里面查询的只能是users表。所以,为了满足我们的需求,我们必须自定义realm,从而才能不局限于一张表的数据查询,还能加自己的一些判断逻辑。下面讲讲怎么实现自定义realm。
自定义realm首先我们就要写一个realm,而这个realm我们一般要继承AuthorizingRealm类,因为这个类里面就有实现接收用户认证信息和接收用户权限信息的两个方法,而realm就是用来从数据库查询这些数据的。下面是我自定义的realm:
我的代码如下
package com.zc.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 extends AuthorizingRealm {
@Override
public String getName() {
// TODO Auto-generated method stub
return “userRealm”;
}
@Override
//身份认证信息(从数据库里面拿数据),返回认证信息 信息失败返回空
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// TODO Auto-generated method stub
String username=(String)token.getPrincipal();//获取身份信息
System.out.println("用户输入的用户名="+username);
//根据用户名查询用户信息
//假定数据库中密码为1111
String pwd ="1111";
SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(username,pwd,getName());
return info;
}
@Override
//获取权限信息,授权信息
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
// TODO Auto-generated method stub
return null;
}
}
验证信息:
package com.zc.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;
//shiro 中使用的数据需要程序员将数据源传递给shiro相应的realm
//本质是你传给用户名我给你验证密码
public class UserRealmDemo {
public static void main(String[] args) {
Factory factory=new IniSecurityManagerFactory(“classpath:shiro.ini”);
SecurityManager securitymanager=factory.getInstance();
SecurityUtils.setSecurityManager(securitymanager);
Subject subject=SecurityUtils.getSubject();
UsernamePasswordToken token=new UsernamePasswordToken(“张三”,“1111”);
try {
subject.login(token);
if(subject.isAuthenticated()) {
System.out.println(“验证通过”);
}
} catch (AuthenticationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("验证失败 ");
}
}
}
配置文件:
[main]
userRealm=com.zc.realm.UserRealm
securityManager.realm=$userRealm
运行结果入下
加入数据库的操作自己适当添加
搞定 完美!!!!