public interface SecurityService {
/**
* @Description 查找用户密码
* @param loginName 用户名称
* @return 密码
*/
Map<String,String> findPasswordByLoginName(String loginName);
}
public class SecurityServiceImpl implements SecurityService {
@Override
public Map<String,String> findPasswordByLoginName(String loginName) {
return DigestsUtil.entryptPassword("123");
}
}
public class DefinitionRealm extends AuthorizingRealm {
public DefinitionRealm() {
//指定密码匹配方式sha1
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(DigestsUtil.SHA1);
//指定密码迭代次数
hashedCredentialsMatcher.setHashIterations(DigestsUtil.ITERATIONS);
//使用父层方法是匹配方式生效
setCredentialsMatcher(hashedCredentialsMatcher);
}
/**
* @Description 认证方法
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//获取登录名
String loginName = (String) authenticationToken.getPrincipal();
SecurityService securityService = new SecurityServiceImpl();
Map<String, String> map = securityService.findPasswordByLoginName(loginName);
if(map.isEmpty()){
throw new UnknownAccountException("账户不存在");
}
String salt = map.get("salt");
String password = map.get("password");
return new SimpleAuthenticationInfo(loginName, password, ByteSource.Util.bytes(salt), getName());
}
/**
* @Description 鉴权方法
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
}
public class HelloShiro {
@Test
public void shiroLogin(){
//导入INI配置创建工厂
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
//工厂构建安全管理器
SecurityManager securityManager = factory.getInstance();
//使用工具生效安全管理器
SecurityUtils.setSecurityManager(securityManager);
//使用工具获得subject主体
Subject subject = SecurityUtils.getSubject();
//构建账户密码
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("jay","123");
//使用subject主体去登录
subject.login(usernamePasswordToken);
//打印登录信息
System.out.println("登录结果:"+subject.isAuthenticated());
}
}
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
登录结果:true