1 自定义Realm类
在项目中新建com.bjsxt.realm.MyRealm
public class MyRealm extends AuthenticatingRealm { @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { System.out.println("执行认证"); //用户名 String username = token.getPrincipal().toString(); //密码 String pwd = new String((char[])token.getCredentials()); System.out.println(username+" "+pwd); //先从数据库查询select * from user where username=? 查看用户名是否存在 if(username.equals("admin")){//假设用户名为admin时能从数据库中查询出来 //根据之前查询出来的用户信息获取密码。假设查询出来的密码是pwd String password= "pwd"; //此处需要注意,第二个参数是从数据库查询出来的密码,而不是传递过来的密码。 //第三个参数自定义。但是尽量不重复了。常直接使用用户名当做realname名字。 AuthenticationInfo info = new SimpleAuthenticationInfo(token.getPrincipal(),password,"realmname"); //shiro会判断从数据库查询出来的密码和客户端传递过来的密码是否一致。 return info; } //返回null说明用户名不存在。 return null; } }
1 修改配置文件
在配置文件中添加下面内容
[main] myrealm=com.bjsxt.realm.MyRealm securityManager.realms=$myrealm
1 测试结果
在ShiroRun中修改用户名和密码,当用户名和密码为admin、pwd时可以正常登录。
此时无论shiro.ini是否配置了[users],都按照Realm中配置的逻辑进行比较用户名和密码。
一、 凭证匹配器
在实际应用中数据库密码都是加密的。Shiro内置了凭证匹配器,通过简单配置就可以实现明文数据和数据库中加密数据匹配的效果。
1 修改自定义Realm
AuthenticationInfo 的构造方法由三个参数变成四个参数的。新增第三个参数表示加盐。
一般都是拿用户数据的id作为盐。
//密码必须是MD5加密后的密码 String password= "7614fd642608ca0755b78d2b2c352e19"; //假设id是从数据库中取出的id Long id = 123L; //第三个参数是加密的盐 AuthenticationInfo info = new SimpleAuthenticationInfo(token.getPrincipal(), password, ByteSource.Util.bytes(id+"") ,token.getPrincipal().toString());
1 修改配置文件
在配置文件中配置凭证匹配器配置。
[main] md5CredentialsMatcher=org.apache.shiro.authc.credential.Md5CredentialsMatcher md5CredentialsMatcher.hashIterations=2 myrealm=com.bjsxt.shiro.MyRealm myrealm.credentialsMatcher=$md5CredentialsMatcher securityManager.realms=$myrealm