From cc96bf843458cd9a93752af3ea038e36825ffa8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=86=B7=E5=86=B7?= <2270033969@qq.com> Date: Sat, 11 May 2024 09:13:19 +0800 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20=E4=BC=98=E5=8C=96=20OAuth?= =?UTF-8?q?=202.0=20=E7=99=BB=E5=BD=95=E8=BF=87=E7=A8=8B=E4=B8=AD=E7=9A=84?= =?UTF-8?q?=E5=BC=82=E5=B8=B8=E8=BE=93=E5=87=BA=EF=BC=8C=E6=96=B9=E4=BE=BF?= =?UTF-8?q?=E5=BC=80=E5=8F=91=E8=BF=87=E7=A8=8B=E4=B8=AD=E8=B0=83=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...sourceOwnerBaseAuthenticationProvider.java | 472 +++++++++--------- 1 file changed, 237 insertions(+), 235 deletions(-) diff --git a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/support/base/OAuth2ResourceOwnerBaseAuthenticationProvider.java b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/support/base/OAuth2ResourceOwnerBaseAuthenticationProvider.java index 2423a52a9..0e05e2b10 100644 --- a/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/support/base/OAuth2ResourceOwnerBaseAuthenticationProvider.java +++ b/pigx-auth/src/main/java/com/pig4cloud/pigx/auth/support/base/OAuth2ResourceOwnerBaseAuthenticationProvider.java @@ -36,154 +36,157 @@ import java.util.function.Supplier; /** * @author jumuning - * @description - * - * 处理自定义授权 + * @description 处理自定义授权 */ @Slf4j public abstract class OAuth2ResourceOwnerBaseAuthenticationProvider - implements AuthenticationProvider { + implements AuthenticationProvider { - private static final Logger LOGGER = LogManager.getLogger(OAuth2ResourceOwnerBaseAuthenticationProvider.class); + private static final Logger LOGGER = LogManager.getLogger(OAuth2ResourceOwnerBaseAuthenticationProvider.class); - private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2.1"; + private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2.1"; - private final OAuth2AuthorizationService authorizationService; + private final OAuth2AuthorizationService authorizationService; - private final OAuth2TokenGenerator tokenGenerator; + private final OAuth2TokenGenerator tokenGenerator; - private final AuthenticationManager authenticationManager; + private final AuthenticationManager authenticationManager; - private final MessageSourceAccessor messages; + private final MessageSourceAccessor messages; - @Deprecated - private Supplier refreshTokenGenerator; + @Deprecated + private Supplier refreshTokenGenerator; - /** - * Constructs an {@code OAuth2AuthorizationCodeAuthenticationProvider} using the - * provided parameters. - * @param authorizationService the authorization service - * @param tokenGenerator the token generator - * @since 0.2.3 - */ - public OAuth2ResourceOwnerBaseAuthenticationProvider(AuthenticationManager authenticationManager, - OAuth2AuthorizationService authorizationService, - OAuth2TokenGenerator tokenGenerator) { - Assert.notNull(authorizationService, "authorizationService cannot be null"); - Assert.notNull(tokenGenerator, "tokenGenerator cannot be null"); - this.authenticationManager = authenticationManager; - this.authorizationService = authorizationService; - this.tokenGenerator = tokenGenerator; + /** + * Constructs an {@code OAuth2AuthorizationCodeAuthenticationProvider} using the + * provided parameters. + * + * @param authorizationService the authorization service + * @param tokenGenerator the token generator + * @since 0.2.3 + */ + public OAuth2ResourceOwnerBaseAuthenticationProvider(AuthenticationManager authenticationManager, + OAuth2AuthorizationService authorizationService, + OAuth2TokenGenerator tokenGenerator) { + Assert.notNull(authorizationService, "authorizationService cannot be null"); + Assert.notNull(tokenGenerator, "tokenGenerator cannot be null"); + this.authenticationManager = authenticationManager; + this.authorizationService = authorizationService; + this.tokenGenerator = tokenGenerator; - // 国际化配置 - this.messages = new MessageSourceAccessor(SpringUtil.getBean("securityMessageSource"), Locale.CHINA); - } + // 国际化配置 + this.messages = new MessageSourceAccessor(SpringUtil.getBean("securityMessageSource"), Locale.CHINA); + } - @Deprecated - public void setRefreshTokenGenerator(Supplier refreshTokenGenerator) { - Assert.notNull(refreshTokenGenerator, "refreshTokenGenerator cannot be null"); - this.refreshTokenGenerator = refreshTokenGenerator; - } + @Deprecated + public void setRefreshTokenGenerator(Supplier refreshTokenGenerator) { + Assert.notNull(refreshTokenGenerator, "refreshTokenGenerator cannot be null"); + this.refreshTokenGenerator = refreshTokenGenerator; + } - public abstract UsernamePasswordAuthenticationToken buildToken(Map reqParameters); + public abstract UsernamePasswordAuthenticationToken buildToken(Map reqParameters); - /** - * 当前provider是否支持此令牌类型 - * @param authentication - * @return - */ - @Override - public abstract boolean supports(Class authentication); + /** + * 当前provider是否支持此令牌类型 + * + * @param authentication + * @return + */ + @Override + public abstract boolean supports(Class authentication); - /** - * 当前的请求客户端是否支持此模式 - * @param registeredClient - */ - public abstract void checkClient(RegisteredClient registeredClient); + /** + * 当前的请求客户端是否支持此模式 + * + * @param registeredClient + */ + public abstract void checkClient(RegisteredClient registeredClient); - /** - * Performs authentication with the same contract as - * {@link AuthenticationManager#authenticate(Authentication)} . - * @param authentication the authentication request object. - * @return a fully authenticated object including credentials. May return - * null if the AuthenticationProvider is unable to support - * authentication of the passed Authentication object. In such a case, - * the next AuthenticationProvider that supports the presented - * Authentication class will be tried. - * @throws AuthenticationException if authentication fails. - */ - @Override - public Authentication authenticate(Authentication authentication) throws AuthenticationException { + /** + * Performs authentication with the same contract as + * {@link AuthenticationManager#authenticate(Authentication)} . + * + * @param authentication the authentication request object. + * @return a fully authenticated object including credentials. May return + * null if the AuthenticationProvider is unable to support + * authentication of the passed Authentication object. In such a case, + * the next AuthenticationProvider that supports the presented + * Authentication class will be tried. + * @throws AuthenticationException if authentication fails. + */ + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { - T resouceOwnerBaseAuthentication = (T) authentication; + T resouceOwnerBaseAuthentication = (T) authentication; - OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient( - resouceOwnerBaseAuthentication); + OAuth2ClientAuthenticationToken clientPrincipal = getAuthenticatedClientElseThrowInvalidClient( + resouceOwnerBaseAuthentication); - RegisteredClient registeredClient = clientPrincipal.getRegisteredClient(); - checkClient(registeredClient); + RegisteredClient registeredClient = clientPrincipal.getRegisteredClient(); + checkClient(registeredClient); - Set authorizedScopes; - // Default to configured scopes - if (!CollectionUtils.isEmpty(resouceOwnerBaseAuthentication.getScopes())) { - for (String requestedScope : resouceOwnerBaseAuthentication.getScopes()) { - if (!registeredClient.getScopes().contains(requestedScope)) { - throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_SCOPE); - } - } - authorizedScopes = new LinkedHashSet<>(resouceOwnerBaseAuthentication.getScopes()); - } - else { - authorizedScopes = new LinkedHashSet<>(); - } + Set authorizedScopes; + // Default to configured scopes + if (!CollectionUtils.isEmpty(resouceOwnerBaseAuthentication.getScopes())) { + for (String requestedScope : resouceOwnerBaseAuthentication.getScopes()) { + if (!registeredClient.getScopes().contains(requestedScope)) { + throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_SCOPE); + } + } + authorizedScopes = new LinkedHashSet<>(resouceOwnerBaseAuthentication.getScopes()); + } else { + authorizedScopes = new LinkedHashSet<>(); + } - Map reqParameters = resouceOwnerBaseAuthentication.getAdditionalParameters(); - try { + Map reqParameters = resouceOwnerBaseAuthentication.getAdditionalParameters(); + try { - UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = buildToken(reqParameters); + UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = buildToken(reqParameters); - LOGGER.debug("got usernamePasswordAuthenticationToken=" + usernamePasswordAuthenticationToken); + LOGGER.debug("got usernamePasswordAuthenticationToken=" + usernamePasswordAuthenticationToken); - Authentication usernamePasswordAuthentication = authenticationManager - .authenticate(usernamePasswordAuthenticationToken); + Authentication usernamePasswordAuthentication = authenticationManager + .authenticate(usernamePasswordAuthenticationToken); - Object onlineQuantity = registeredClient.getClientSettings() - .getSettings() - .get(CommonConstants.ONLINE_QUANTITY); - // 没有设置并发控制走原有逻辑生成 || 设置同时在线为 true - if (Objects.isNull(onlineQuantity) || BooleanUtil.toBooleanObject((String) onlineQuantity)) { - return generatAuthenticationToken(resouceOwnerBaseAuthentication, clientPrincipal, registeredClient, - authorizedScopes, usernamePasswordAuthentication); - } + Object onlineQuantity = registeredClient.getClientSettings() + .getSettings() + .get(CommonConstants.ONLINE_QUANTITY); + // 没有设置并发控制走原有逻辑生成 || 设置同时在线为 true + if (Objects.isNull(onlineQuantity) || BooleanUtil.toBooleanObject((String) onlineQuantity)) { + return generatAuthenticationToken(resouceOwnerBaseAuthentication, clientPrincipal, registeredClient, + authorizedScopes, usernamePasswordAuthentication); + } - // 不允许同时在线,删除原有username 关联的所有token - PigxRedisOAuth2AuthorizationService redisOAuth2AuthorizationService = (PigxRedisOAuth2AuthorizationService) this.authorizationService; - redisOAuth2AuthorizationService.removeByUsername(usernamePasswordAuthentication); + // 不允许同时在线,删除原有username 关联的所有token + PigxRedisOAuth2AuthorizationService redisOAuth2AuthorizationService = (PigxRedisOAuth2AuthorizationService) this.authorizationService; + redisOAuth2AuthorizationService.removeByUsername(usernamePasswordAuthentication); - return generatAuthenticationToken(resouceOwnerBaseAuthentication, clientPrincipal, registeredClient, - authorizedScopes, usernamePasswordAuthentication); + return generatAuthenticationToken(resouceOwnerBaseAuthentication, clientPrincipal, registeredClient, + authorizedScopes, usernamePasswordAuthentication); - } - catch (Exception ex) { - throw oAuth2AuthenticationException(authentication, (AuthenticationException) ex); - } + } catch (AuthenticationException ex) { + throw oAuth2AuthenticationException(authentication, ex); + } catch (Exception e) { + log.error("登录异常:", e); + throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR)); + } + } - } - - /** - * 生成新的令牌 - * @param resouceOwnerBaseAuthentication - * @param clientPrincipal - * @param registeredClient - * @param authorizedScopes - * @param usernamePasswordAuthentication - * @return OAuth2AccessTokenAuthenticationToken - */ - @NotNull - private OAuth2AccessTokenAuthenticationToken generatAuthenticationToken(T resouceOwnerBaseAuthentication, - OAuth2ClientAuthenticationToken clientPrincipal, RegisteredClient registeredClient, - Set authorizedScopes, Authentication usernamePasswordAuthentication) { - // @formatter:off + /** + * 生成新的令牌 + * + * @param resouceOwnerBaseAuthentication + * @param clientPrincipal + * @param registeredClient + * @param authorizedScopes + * @param usernamePasswordAuthentication + * @return OAuth2AccessTokenAuthenticationToken + */ + @NotNull + private OAuth2AccessTokenAuthenticationToken generatAuthenticationToken(T resouceOwnerBaseAuthentication, + OAuth2ClientAuthenticationToken clientPrincipal, RegisteredClient registeredClient, + Set authorizedScopes, Authentication usernamePasswordAuthentication) { + // @formatter:off DefaultOAuth2TokenContext.Builder tokenContextBuilder = DefaultOAuth2TokenContext.builder() .registeredClient(registeredClient) .principal(usernamePasswordAuthentication) @@ -193,138 +196,137 @@ public abstract class OAuth2ResourceOwnerBaseAuthenticationProvider metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, - ((ClaimAccessor) generatedAccessToken).getClaims())) - // 0.4.0 新增的方法 - .authorizedScopes(authorizedScopes) - .attribute(Principal.class.getName(), usernamePasswordAuthentication); - } - else { - authorizationBuilder.id(accessToken.getTokenValue()).accessToken(accessToken); - } + // ----- Access token ----- + OAuth2TokenContext tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.ACCESS_TOKEN).build(); + OAuth2Token generatedAccessToken = this.tokenGenerator.generate(tokenContext); + if (generatedAccessToken == null) { + OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, + "The token generator failed to generate the access token.", ERROR_URI); + throw new OAuth2AuthenticationException(error); + } + OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, + generatedAccessToken.getTokenValue(), generatedAccessToken.getIssuedAt(), + generatedAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes()); + if (generatedAccessToken instanceof ClaimAccessor) { + authorizationBuilder.id(accessToken.getTokenValue()) + .token(accessToken, + (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, + ((ClaimAccessor) generatedAccessToken).getClaims())) + // 0.4.0 新增的方法 + .authorizedScopes(authorizedScopes) + .attribute(Principal.class.getName(), usernamePasswordAuthentication); + } else { + authorizationBuilder.id(accessToken.getTokenValue()).accessToken(accessToken); + } - // ----- Refresh token ----- - OAuth2RefreshToken refreshToken = null; - if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN) && - // Do not issue refresh token to public client - !clientPrincipal.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.NONE)) { + // ----- Refresh token ----- + OAuth2RefreshToken refreshToken = null; + if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN) && + // Do not issue refresh token to public client + !clientPrincipal.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.NONE)) { - if (this.refreshTokenGenerator != null) { - Instant issuedAt = Instant.now(); - Instant expiresAt = issuedAt.plus(registeredClient.getTokenSettings().getRefreshTokenTimeToLive()); - refreshToken = new OAuth2RefreshToken(this.refreshTokenGenerator.get(), issuedAt, expiresAt); - } - else { - tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.REFRESH_TOKEN).build(); - OAuth2Token generatedRefreshToken = this.tokenGenerator.generate(tokenContext); - if (!(generatedRefreshToken instanceof OAuth2RefreshToken)) { - OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, - "The token generator failed to generate the refresh token.", ERROR_URI); - throw new OAuth2AuthenticationException(error); - } - refreshToken = (OAuth2RefreshToken) generatedRefreshToken; - } - authorizationBuilder.refreshToken(refreshToken); - } + if (this.refreshTokenGenerator != null) { + Instant issuedAt = Instant.now(); + Instant expiresAt = issuedAt.plus(registeredClient.getTokenSettings().getRefreshTokenTimeToLive()); + refreshToken = new OAuth2RefreshToken(this.refreshTokenGenerator.get(), issuedAt, expiresAt); + } else { + tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.REFRESH_TOKEN).build(); + OAuth2Token generatedRefreshToken = this.tokenGenerator.generate(tokenContext); + if (!(generatedRefreshToken instanceof OAuth2RefreshToken)) { + OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, + "The token generator failed to generate the refresh token.", ERROR_URI); + throw new OAuth2AuthenticationException(error); + } + refreshToken = (OAuth2RefreshToken) generatedRefreshToken; + } + authorizationBuilder.refreshToken(refreshToken); + } - OAuth2Authorization authorization = authorizationBuilder.build(); + OAuth2Authorization authorization = authorizationBuilder.build(); - this.authorizationService.save(authorization); + this.authorizationService.save(authorization); - LOGGER.debug("returning OAuth2AccessTokenAuthenticationToken"); + LOGGER.debug("returning OAuth2AccessTokenAuthenticationToken"); - return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, accessToken, refreshToken, - Objects.requireNonNull(authorization.getAccessToken().getClaims())); - } + return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, accessToken, refreshToken, + Objects.requireNonNull(authorization.getAccessToken().getClaims())); + } - /** - * 登录异常转换为oauth2异常 - * @param authentication 身份验证 - * @param authenticationException 身份验证异常 - * @return {@link OAuth2AuthenticationException} - */ - private OAuth2AuthenticationException oAuth2AuthenticationException(Authentication authentication, - AuthenticationException authenticationException) { + /** + * 登录异常转换为oauth2异常 + * + * @param authentication 身份验证 + * @param authenticationException 身份验证异常 + * @return {@link OAuth2AuthenticationException} + */ + private OAuth2AuthenticationException oAuth2AuthenticationException(Authentication authentication, + AuthenticationException authenticationException) { - // OAuth2AuthenticationException 直接返回 - if (authenticationException instanceof OAuth2AuthenticationException) { - return (OAuth2AuthenticationException) authenticationException; - } + // OAuth2AuthenticationException 直接返回 + if (authenticationException instanceof OAuth2AuthenticationException) { + return (OAuth2AuthenticationException) authenticationException; + } - if (authenticationException instanceof UsernameNotFoundException) { - return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodesExpand.USERNAME_NOT_FOUND, - this.messages.getMessage("JdbcDaoImpl.notFound", new Object[] { authentication.getName() }, - "Username {0} not found"), - "")); - } - if (authenticationException instanceof BadCredentialsException) { - return new OAuth2AuthenticationException( - new OAuth2Error(OAuth2ErrorCodesExpand.BAD_CREDENTIALS, this.messages.getMessage( - "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), "")); - } - if (authenticationException instanceof LockedException) { - return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodesExpand.USER_LOCKED, this.messages - .getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked"), "")); - } - if (authenticationException instanceof DisabledException) { - return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodesExpand.USER_DISABLE, - this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"), - "")); - } - if (authenticationException instanceof AccountExpiredException) { - return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodesExpand.USER_EXPIRED, this.messages - .getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired"), "")); - } - if (authenticationException instanceof CredentialsExpiredException) { - return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodesExpand.CREDENTIALS_EXPIRED, - this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired", - "User credentials have expired"), - "")); - } - if (authenticationException instanceof ScopeException) { - return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_SCOPE, - this.messages.getMessage("AbstractAccessDecisionManager.accessDenied", "invalid_scope"), "")); - } + if (authenticationException instanceof UsernameNotFoundException) { + return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodesExpand.USERNAME_NOT_FOUND, + this.messages.getMessage("JdbcDaoImpl.notFound", new Object[]{authentication.getName()}, + "Username {0} not found"), + "")); + } + if (authenticationException instanceof BadCredentialsException) { + return new OAuth2AuthenticationException( + new OAuth2Error(OAuth2ErrorCodesExpand.BAD_CREDENTIALS, this.messages.getMessage( + "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), "")); + } + if (authenticationException instanceof LockedException) { + return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodesExpand.USER_LOCKED, this.messages + .getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked"), "")); + } + if (authenticationException instanceof DisabledException) { + return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodesExpand.USER_DISABLE, + this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"), + "")); + } + if (authenticationException instanceof AccountExpiredException) { + return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodesExpand.USER_EXPIRED, this.messages + .getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired"), "")); + } + if (authenticationException instanceof CredentialsExpiredException) { + return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodesExpand.CREDENTIALS_EXPIRED, + this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired", + "User credentials have expired"), + "")); + } + if (authenticationException instanceof ScopeException) { + return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_SCOPE, + this.messages.getMessage("AbstractAccessDecisionManager.accessDenied", "invalid_scope"), "")); + } - log.error(authenticationException.getLocalizedMessage()); - return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR), - authenticationException.getLocalizedMessage(), authenticationException); - } + log.error(authenticationException.getLocalizedMessage()); + return new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR), + authenticationException.getLocalizedMessage(), authenticationException); + } - private OAuth2ClientAuthenticationToken getAuthenticatedClientElseThrowInvalidClient( - Authentication authentication) { + private OAuth2ClientAuthenticationToken getAuthenticatedClientElseThrowInvalidClient( + Authentication authentication) { - OAuth2ClientAuthenticationToken clientPrincipal = null; + OAuth2ClientAuthenticationToken clientPrincipal = null; - if (OAuth2ClientAuthenticationToken.class.isAssignableFrom(authentication.getPrincipal().getClass())) { - clientPrincipal = (OAuth2ClientAuthenticationToken) authentication.getPrincipal(); - } + if (OAuth2ClientAuthenticationToken.class.isAssignableFrom(authentication.getPrincipal().getClass())) { + clientPrincipal = (OAuth2ClientAuthenticationToken) authentication.getPrincipal(); + } - if (clientPrincipal != null && clientPrincipal.isAuthenticated()) { - return clientPrincipal; - } + if (clientPrincipal != null && clientPrincipal.isAuthenticated()) { + return clientPrincipal; + } - throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT); - } + throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT); + } }