From 1d8757c58e0457336a570722ffcd8a59e651b378 Mon Sep 17 00:00:00 2001 From: zlt2000 Date: Tue, 5 Dec 2023 17:27:15 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=9E=E7=8E=B0=E6=8E=92=E9=99=A4?= =?UTF-8?q?=E9=89=B4=E6=9D=83=E7=9A=84=E5=9C=B0=E5=9D=80=E5=8D=B3=E4=BD=BF?= =?UTF-8?q?=E5=8F=82=E6=95=B0=E5=B8=A6=20access=5Ftoken=20=E4=B9=9F?= =?UTF-8?q?=E4=B8=8D=E4=BC=9A=E8=BF=9B=E8=A1=8C=E9=89=B4=E6=9D=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CustomBearerTokenResolver.java | 24 +-- .../CustomServerBearerTokenAuthConverter.java | 147 ++++++++++++++++++ .../central/oauth2/common/util/AuthUtils.java | 27 ++-- .../common/constant/SecurityConstants.java | 2 +- .../config/ResourceServerConfiguration.java | 10 +- 5 files changed, 171 insertions(+), 39 deletions(-) rename zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/{service/impl => component}/CustomBearerTokenResolver.java (78%) create mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/component/CustomServerBearerTokenAuthConverter.java diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/CustomBearerTokenResolver.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/component/CustomBearerTokenResolver.java similarity index 78% rename from zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/CustomBearerTokenResolver.java rename to zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/component/CustomBearerTokenResolver.java index 833d1ca2..80813ceb 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/CustomBearerTokenResolver.java +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/component/CustomBearerTokenResolver.java @@ -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 (?[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) { diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/component/CustomServerBearerTokenAuthConverter.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/component/CustomServerBearerTokenAuthConverter.java new file mode 100644 index 00000000..b14ce08d --- /dev/null +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/component/CustomServerBearerTokenAuthConverter.java @@ -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 + *

+ * 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 (?[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 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 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()); + } +} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java index fed532c8..75399d9a 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java @@ -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 (?[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 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; } diff --git a/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/SecurityConstants.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/SecurityConstants.java index 4d3888bc..e8e22c02 100644 --- a/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/SecurityConstants.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/SecurityConstants.java @@ -198,7 +198,7 @@ public interface SecurityConstants { /** * 客户端ID */ - String CLIENT_ID = "clientId"; + String CLIENT_ID = "client_id"; /** * 用户信息 diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java index 80dca0be..629d7564 100644 --- a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java @@ -2,6 +2,7 @@ package com.central.gateway.config; import com.central.gateway.auth.*; import com.central.oauth2.common.component.CustomReactiveAuthorizationServiceIntrospector; +import com.central.oauth2.common.component.CustomServerBearerTokenAuthConverter; import com.central.oauth2.common.config.BaseSecurityConfig; import com.central.oauth2.common.properties.SecurityProperties; import lombok.extern.slf4j.Slf4j; @@ -13,7 +14,6 @@ import org.springframework.security.config.annotation.web.reactive.EnableWebFlux import org.springframework.security.config.web.server.SecurityWebFiltersOrder; import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.oauth2.server.resource.authentication.OpaqueTokenReactiveAuthenticationManager; -import org.springframework.security.oauth2.server.resource.web.server.authentication.ServerBearerTokenAuthenticationConverter; import org.springframework.security.web.server.SecurityWebFilterChain; import org.springframework.security.web.server.ServerAuthenticationEntryPoint; import org.springframework.security.web.server.authentication.AuthenticationWebFilter; @@ -58,17 +58,19 @@ public class ResourceServerConfiguration { .anyExchange().access(permissionAuthManager); }); - http.addFilterAt(this.getAuthWebFilter(authenticationEntryPoint) + http.addFilterAt(this.getAuthWebFilter(authenticationEntryPoint, securityProperties) , SecurityWebFiltersOrder.AUTHENTICATION); return http.build(); } - private AuthenticationWebFilter getAuthWebFilter(ServerAuthenticationEntryPoint authenticationEntryPoint) { + private AuthenticationWebFilter getAuthWebFilter(ServerAuthenticationEntryPoint authenticationEntryPoint + , SecurityProperties securityProperties) { OpaqueTokenReactiveAuthenticationManager authenticationManager = new OpaqueTokenReactiveAuthenticationManager( new CustomReactiveAuthorizationServiceIntrospector()); - ServerBearerTokenAuthenticationConverter authenticationConverter = new ServerBearerTokenAuthenticationConverter(); + CustomServerBearerTokenAuthConverter authenticationConverter = + new CustomServerBearerTokenAuthConverter(securityProperties); authenticationConverter.setAllowUriQueryParameter(true); AuthenticationWebFilter oauth2 = new AuthenticationWebFilter(authenticationManager);