feat: 实现排除鉴权的地址即使参数带 access_token 也不会进行鉴权

This commit is contained in:
zlt2000
2023-12-05 17:27:15 +08:00
parent b604e4665a
commit 1d8757c58e
5 changed files with 171 additions and 39 deletions
@@ -1,7 +1,8 @@
package com.central.oauth2.common.service.impl;
package com.central.oauth2.common.component;
import com.central.oauth2.common.properties.PermitProperties;
import com.central.oauth2.common.properties.SecurityProperties;
import com.central.oauth2.common.util.AuthUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.http.HttpHeaders;
@@ -13,11 +14,8 @@ import org.springframework.security.oauth2.server.resource.web.BearerTokenResolv
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author: zlt
@@ -29,9 +27,6 @@ import java.util.regex.Pattern;
@ConditionalOnClass(HttpServletRequest.class)
@Component
public class CustomBearerTokenResolver implements BearerTokenResolver {
private static final Pattern authorizationPattern = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-:._~+/]+=*)$",
Pattern.CASE_INSENSITIVE);
private final boolean allowFormEncodedBodyParameter = false;
private final boolean allowUriQueryParameter = true;
@@ -55,7 +50,7 @@ public class CustomBearerTokenResolver implements BearerTokenResolver {
return null;
}
final String authorizationHeaderToken = resolveFromAuthorizationHeader(request);
final String authorizationHeaderToken = AuthUtils.extractHeaderToken(request);
final String parameterToken = isParameterTokenSupportedForRequest(request)
? resolveFromRequestParameters(request) : null;
if (authorizationHeaderToken != null) {
@@ -72,19 +67,6 @@ public class CustomBearerTokenResolver implements BearerTokenResolver {
return null;
}
private String resolveFromAuthorizationHeader(HttpServletRequest request) {
String authorization = request.getHeader(this.bearerTokenHeaderName);
if (!StringUtils.startsWithIgnoreCase(authorization, "bearer")) {
return null;
}
Matcher matcher = authorizationPattern.matcher(authorization);
if (!matcher.matches()) {
BearerTokenError error = BearerTokenErrors.invalidToken("Bearer token is malformed");
throw new OAuth2AuthenticationException(error);
}
return matcher.group("token");
}
private static String resolveFromRequestParameters(HttpServletRequest request) {
String[] values = request.getParameterValues("access_token");
if (values == null || values.length == 0) {
@@ -0,0 +1,147 @@
package com.central.oauth2.common.component;
import com.central.oauth2.common.properties.PermitProperties;
import com.central.oauth2.common.properties.SecurityProperties;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.server.resource.BearerTokenError;
import org.springframework.security.oauth2.server.resource.BearerTokenErrors;
import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthenticationToken;
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 实现排除鉴权的地址即使参数带 access_token 也不会进行鉴权
*
* @author zlt
* @version 1.0
* @date 2023/12/5
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
public class CustomServerBearerTokenAuthConverter implements ServerAuthenticationConverter {
private final PathMatcher pathMatcher = new AntPathMatcher();
private static final Pattern authorizationPattern = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-._~+/]+=*)$",
Pattern.CASE_INSENSITIVE);
private boolean allowUriQueryParameter = false;
private String bearerTokenHeaderName = HttpHeaders.AUTHORIZATION;
private final PermitProperties permitProperties;
public CustomServerBearerTokenAuthConverter(SecurityProperties securityProperties) {
this.permitProperties = securityProperties.getIgnore();
}
@Override
public Mono<Authentication> convert(ServerWebExchange exchange) {
return Mono.fromCallable(() -> token(exchange.getRequest())).map((token) -> {
if (token.isEmpty()) {
BearerTokenError error = invalidTokenError();
throw new OAuth2AuthenticationException(error);
}
return new BearerTokenAuthenticationToken(token);
});
}
private String token(ServerHttpRequest request) {
boolean match = Arrays.stream(permitProperties.getUrls())
.anyMatch(url -> pathMatcher.match(url, request.getURI().getPath()));
if (match) {
return null;
}
String authorizationHeaderToken = resolveFromAuthorizationHeader(request.getHeaders());
String parameterToken = resolveAccessTokenFromRequest(request);
if (authorizationHeaderToken != null) {
if (parameterToken != null) {
BearerTokenError error = BearerTokenErrors
.invalidRequest("Found multiple bearer tokens in the request");
throw new OAuth2AuthenticationException(error);
}
return authorizationHeaderToken;
}
if (parameterToken != null && isParameterTokenSupportedForRequest(request)) {
return parameterToken;
}
return null;
}
private static String resolveAccessTokenFromRequest(ServerHttpRequest request) {
List<String> parameterTokens = request.getQueryParams().get("access_token");
if (CollectionUtils.isEmpty(parameterTokens)) {
return null;
}
if (parameterTokens.size() == 1) {
return parameterTokens.get(0);
}
BearerTokenError error = BearerTokenErrors.invalidRequest("Found multiple bearer tokens in the request");
throw new OAuth2AuthenticationException(error);
}
/**
* Set if transport of access token using URI query parameter is supported. Defaults
* to {@code false}.
*
* The spec recommends against using this mechanism for sending bearer tokens, and
* even goes as far as stating that it was only included for completeness.
* @param allowUriQueryParameter if the URI query parameter is supported
*/
public void setAllowUriQueryParameter(boolean allowUriQueryParameter) {
this.allowUriQueryParameter = allowUriQueryParameter;
}
/**
* Set this value to configure what header is checked when resolving a Bearer Token.
* This value is defaulted to {@link HttpHeaders#AUTHORIZATION}.
*
* This allows other headers to be used as the Bearer Token source such as
* {@link HttpHeaders#PROXY_AUTHORIZATION}
* @param bearerTokenHeaderName the header to check when retrieving the Bearer Token.
* @since 5.4
*/
public void setBearerTokenHeaderName(String bearerTokenHeaderName) {
this.bearerTokenHeaderName = bearerTokenHeaderName;
}
private String resolveFromAuthorizationHeader(HttpHeaders headers) {
String authorization = headers.getFirst(this.bearerTokenHeaderName);
if (!StringUtils.startsWithIgnoreCase(authorization, "bearer")) {
return null;
}
Matcher matcher = authorizationPattern.matcher(authorization);
if (!matcher.matches()) {
BearerTokenError error = invalidTokenError();
throw new OAuth2AuthenticationException(error);
}
return matcher.group("token");
}
private static BearerTokenError invalidTokenError() {
return BearerTokenErrors.invalidToken("Bearer token is malformed");
}
private boolean isParameterTokenSupportedForRequest(ServerHttpRequest request) {
return this.allowUriQueryParameter && HttpMethod.GET.equals(request.getMethod());
}
}
@@ -9,7 +9,6 @@ import com.central.oauth2.common.exception.CustomOAuth2AuthenticationException;
import com.central.oauth2.common.token.BaseAuthenticationToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import jakarta.servlet.http.HttpServletRequest;
@@ -17,10 +16,13 @@ import org.springframework.security.oauth2.server.authorization.OAuth2Authorizat
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionException;
import org.springframework.util.StringUtils;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 认证授权相关工具类
@@ -39,6 +41,9 @@ public class AuthUtils {
private static final String BASIC_ = "Basic ";
private static final Pattern authorizationPattern = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-:._~+/]+=*)$",
Pattern.CASE_INSENSITIVE);
/**
* 获取requet(head/param)中的token
* @param request
@@ -60,18 +65,14 @@ public class AuthUtils {
* @param request
* @return
*/
private static String extractHeaderToken(HttpServletRequest request) {
Enumeration<String> headers = request.getHeaders(CommonConstant.TOKEN_HEADER);
while (headers.hasMoreElements()) {
String value = headers.nextElement();
if ((value.startsWith(OAuth2AccessToken.TokenType.BEARER.getValue()))) {
String authHeaderValue = value.substring(OAuth2AccessToken.TokenType.BEARER.getValue().length()).trim();
int commaIndex = authHeaderValue.indexOf(',');
if (commaIndex > 0) {
authHeaderValue = authHeaderValue.substring(0, commaIndex);
}
return authHeaderValue;
}
public static String extractHeaderToken(HttpServletRequest request) {
String authorization = request.getHeader(CommonConstant.TOKEN_HEADER);
if (!StringUtils.startsWithIgnoreCase(authorization, "bearer")) {
return null;
}
Matcher matcher = authorizationPattern.matcher(authorization);
if (matcher.matches()) {
return matcher.group("token");
}
return null;
}
@@ -198,7 +198,7 @@ public interface SecurityConstants {
/**
* 客户端ID
*/
String CLIENT_ID = "clientId";
String CLIENT_ID = "client_id";
/**
* 用户信息