第一步MD5加密
public class MD5Test {
@Test
public void test01(){
String password ="666";
Md5Hash md5Hash = new Md5Hash(password);
System.out.println(md5Hash);
Md5Hash zhangsan = new Md5Hash(password, "zhangsan");
System.out.println(zhangsan);
Md5Hash zhangsan1 = new Md5Hash(password, "zhangsan", 3);
System.out.println(zhangsan1);
}
}
自定义Realm,重写认证方法
public class PasswordRealm extends AuthorizingRealm {
public String getName(){
return "PasswordRealm";
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = (String)token.getPrincipal();
if (!username.equals("zhangsan")){
return null;
}
String password = "cd757bae8bd31da92c6b14c235668091";
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password, ByteSource.Util.bytes("zhangsan"), getName());
return info;
}
}
建立一个shiro-cryptography.ini的配置文件
[main]
#定义凭证匹配器
credentialsMatcher=org.apache.shiro.authc.credential.HashedCredentialsMatcher
#散列算法
credentialsMatcher.hashAlgorithmName=md5
#散列次数
credentialsMatcher.hashIterations=3
#将凭证匹配器设置到realm
myRealm= com.feng.realm.PasswordRealm
myRealm.credentialsMatcher=$credentialsMatcher
securityManager.realms=$myRealm
编写测试程序
public class MyTest {
@Test
public void test01(){
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-cryptography.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "666");
try {
subject.login(token);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("登入是否成功"+subject.isAuthenticated());
subject.logout();
System.out.println("登入是否成功"+subject.isAuthenticated());
}
}