matrix.business.oauth2.core.ExcludeRequestMatcher Maven / Gradle / Ivy
package matrix.business.oauth2.core;
import matrix.boot.common.utils.StringUtil;
import matrix.business.oauth2.service.OAuthFilterService;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.CollectionUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
* 排除连接匹配类
* @author 36509
* 2023/6/23
**/
public class ExcludeRequestMatcher implements RequestMatcher {
/**
* 默认不用Auth认证的链接
*/
private static final List NOT_AUTH_VALIDATE_URLS = Arrays.asList("/actuator/health", "/error");
/**
* 忽略验证的链接
*/
private final List ignoreAuthMatchers = new ArrayList<>();
/**
* 必须走认证服务器的链接
*/
private final List requiredAuthMatchers = new ArrayList<>();
/**
* 认证过滤器
*/
private final OAuthFilterService oAuthFilterService;
public ExcludeRequestMatcher(Set ignoreAuthUris, Set requiredAuthUris, OAuthFilterService oAuthFilterService) {
Set useIgnoreAuthUris = ignoreAuthUris == null ? new HashSet<>() : ignoreAuthUris;
//加入默认忽略头验证的urls
if (!CollectionUtils.isEmpty(NOT_AUTH_VALIDATE_URLS)) {
useIgnoreAuthUris.addAll(NOT_AUTH_VALIDATE_URLS);
}
//转换成AntMatcher
if (!CollectionUtils.isEmpty(useIgnoreAuthUris)) {
useIgnoreAuthUris.forEach(url -> ignoreAuthMatchers.add(new AntPathRequestMatcher(url)));
}
if (!CollectionUtils.isEmpty(requiredAuthUris)) {
requiredAuthUris.forEach(url -> requiredAuthMatchers.add(new AntPathRequestMatcher(url)));
}
this.oAuthFilterService = oAuthFilterService;
}
@Override
public boolean matches(HttpServletRequest request) {
//判断是否存在验证头
String authorization = request.getHeader("Authorization");
if (!StringUtil.isEmpty(authorization)) {
return true;
}
//校验必须走认证的链接
for (AntPathRequestMatcher requiredAuthMatcher : requiredAuthMatchers) {
//存在必须走认证的链接返回true
if (requiredAuthMatcher.matches(request)) {
return true;
}
}
//校验黑白名单
if (oAuthFilterService.blackMatcher(request)) {
//黑名单用户,即使无须验证接口,也必须要认证
return true;
}
//校验是否存在需要忽略的链接
for (AntPathRequestMatcher ignoreAuthMatcher : ignoreAuthMatchers) {
//存在忽略的链接返回false
if (ignoreAuthMatcher.matches(request)) {
return false;
}
}
//白名单用户,无须做认证,直接放过,否则需要认证
return !oAuthFilterService.whiteMatcher(request);
}
}