Skip to content

Commit 13abb3e

Browse files
Dmitriy Dubsonddubson
Dmitriy Dubson
authored andcommitted
Add OAuth2TokenEndpointAuthenticationSuccessHandler
Fixes gh-925
1 parent 68d1691 commit 13abb3e

File tree

4 files changed

+290
-41
lines changed

4 files changed

+290
-41
lines changed

docs/modules/ROOT/pages/protocol-endpoints.adoc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,7 @@ The supported https://datatracker.ietf.org/doc/html/rfc6749#section-1.3[authoriz
263263

264264
* `*AuthenticationConverter*` -- A `DelegatingAuthenticationConverter` composed of `OAuth2AuthorizationCodeAuthenticationConverter`, `OAuth2RefreshTokenAuthenticationConverter`, `OAuth2ClientCredentialsAuthenticationConverter`, and `OAuth2DeviceCodeAuthenticationConverter`.
265265
* `*AuthenticationManager*` -- An `AuthenticationManager` composed of `OAuth2AuthorizationCodeAuthenticationProvider`, `OAuth2RefreshTokenAuthenticationProvider`, `OAuth2ClientCredentialsAuthenticationProvider`, and `OAuth2DeviceCodeAuthenticationProvider`.
266-
* `*AuthenticationSuccessHandler*` -- An internal implementation that handles an `OAuth2AccessTokenAuthenticationToken` and returns the `OAuth2AccessTokenResponse`.
266+
* `*AuthenticationSuccessHandler*` -- An `OAuth2AccessTokenResponseAuthenticationSuccessHandler`.
267267
* `*AuthenticationFailureHandler*` -- An `OAuth2ErrorAuthenticationFailureHandler`.
268268

269269
[[oauth2-token-introspection-endpoint]]

oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenEndpointFilter.java

Lines changed: 2 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -16,32 +16,24 @@
1616
package org.springframework.security.oauth2.server.authorization.web;
1717

1818
import java.io.IOException;
19-
import java.time.temporal.ChronoUnit;
2019
import java.util.Arrays;
21-
import java.util.Map;
2220

2321
import jakarta.servlet.FilterChain;
2422
import jakarta.servlet.ServletException;
2523
import jakarta.servlet.http.HttpServletRequest;
2624
import jakarta.servlet.http.HttpServletResponse;
27-
2825
import org.springframework.core.log.LogMessage;
2926
import org.springframework.http.HttpMethod;
30-
import org.springframework.http.converter.HttpMessageConverter;
31-
import org.springframework.http.server.ServletServerHttpResponse;
3227
import org.springframework.security.authentication.AbstractAuthenticationToken;
3328
import org.springframework.security.authentication.AuthenticationDetailsSource;
3429
import org.springframework.security.authentication.AuthenticationManager;
3530
import org.springframework.security.core.Authentication;
3631
import org.springframework.security.core.context.SecurityContextHolder;
37-
import org.springframework.security.oauth2.core.OAuth2AccessToken;
3832
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
3933
import org.springframework.security.oauth2.core.OAuth2Error;
4034
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
41-
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
4235
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
4336
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
44-
import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter;
4537
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken;
4638
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeAuthenticationProvider;
4739
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationGrantAuthenticationToken;
@@ -54,14 +46,14 @@
5446
import org.springframework.security.oauth2.server.authorization.web.authentication.OAuth2DeviceCodeAuthenticationConverter;
5547
import org.springframework.security.oauth2.server.authorization.web.authentication.OAuth2ErrorAuthenticationFailureHandler;
5648
import org.springframework.security.oauth2.server.authorization.web.authentication.OAuth2RefreshTokenAuthenticationConverter;
49+
import org.springframework.security.oauth2.server.authorization.web.authentication.OAuth2AccessTokenResponseAuthenticationSuccessHandler;
5750
import org.springframework.security.web.authentication.AuthenticationConverter;
5851
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
5952
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
6053
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
6154
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
6255
import org.springframework.security.web.util.matcher.RequestMatcher;
6356
import org.springframework.util.Assert;
64-
import org.springframework.util.CollectionUtils;
6557
import org.springframework.web.filter.OncePerRequestFilter;
6658

6759
/**
@@ -103,12 +95,10 @@ public final class OAuth2TokenEndpointFilter extends OncePerRequestFilter {
10395
private static final String DEFAULT_ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2";
10496
private final AuthenticationManager authenticationManager;
10597
private final RequestMatcher tokenEndpointMatcher;
106-
private final HttpMessageConverter<OAuth2AccessTokenResponse> accessTokenHttpResponseConverter =
107-
new OAuth2AccessTokenResponseHttpMessageConverter();
10898
private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource =
10999
new WebAuthenticationDetailsSource();
110100
private AuthenticationConverter authenticationConverter;
111-
private AuthenticationSuccessHandler authenticationSuccessHandler = this::sendAccessTokenResponse;
101+
private AuthenticationSuccessHandler authenticationSuccessHandler = new OAuth2AccessTokenResponseAuthenticationSuccessHandler();
112102
private AuthenticationFailureHandler authenticationFailureHandler = new OAuth2ErrorAuthenticationFailureHandler();
113103

114104
/**
@@ -218,34 +208,6 @@ public void setAuthenticationFailureHandler(AuthenticationFailureHandler authent
218208
this.authenticationFailureHandler = authenticationFailureHandler;
219209
}
220210

221-
private void sendAccessTokenResponse(HttpServletRequest request, HttpServletResponse response,
222-
Authentication authentication) throws IOException {
223-
224-
OAuth2AccessTokenAuthenticationToken accessTokenAuthentication =
225-
(OAuth2AccessTokenAuthenticationToken) authentication;
226-
227-
OAuth2AccessToken accessToken = accessTokenAuthentication.getAccessToken();
228-
OAuth2RefreshToken refreshToken = accessTokenAuthentication.getRefreshToken();
229-
Map<String, Object> additionalParameters = accessTokenAuthentication.getAdditionalParameters();
230-
231-
OAuth2AccessTokenResponse.Builder builder =
232-
OAuth2AccessTokenResponse.withToken(accessToken.getTokenValue())
233-
.tokenType(accessToken.getTokenType())
234-
.scopes(accessToken.getScopes());
235-
if (accessToken.getIssuedAt() != null && accessToken.getExpiresAt() != null) {
236-
builder.expiresIn(ChronoUnit.SECONDS.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()));
237-
}
238-
if (refreshToken != null) {
239-
builder.refreshToken(refreshToken.getTokenValue());
240-
}
241-
if (!CollectionUtils.isEmpty(additionalParameters)) {
242-
builder.additionalParameters(additionalParameters);
243-
}
244-
OAuth2AccessTokenResponse accessTokenResponse = builder.build();
245-
ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
246-
this.accessTokenHttpResponseConverter.write(accessTokenResponse, null, httpResponse);
247-
}
248-
249211
private static void throwError(String errorCode, String parameterName) {
250212
OAuth2Error error = new OAuth2Error(errorCode, "OAuth 2.0 Parameter: " + parameterName, DEFAULT_ERROR_URI);
251213
throw new OAuth2AuthenticationException(error);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
/*
2+
* Copyright 2020-2023 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.security.oauth2.server.authorization.web.authentication;
17+
18+
import java.io.IOException;
19+
import java.time.temporal.ChronoUnit;
20+
import java.util.Map;
21+
22+
import jakarta.servlet.ServletException;
23+
import jakarta.servlet.http.HttpServletRequest;
24+
import jakarta.servlet.http.HttpServletResponse;
25+
import org.apache.commons.logging.Log;
26+
import org.apache.commons.logging.LogFactory;
27+
import org.springframework.http.converter.HttpMessageConverter;
28+
import org.springframework.http.server.ServletServerHttpResponse;
29+
import org.springframework.security.core.Authentication;
30+
import org.springframework.security.oauth2.core.*;
31+
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
32+
import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter;
33+
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken;
34+
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
35+
import org.springframework.util.Assert;
36+
import org.springframework.util.CollectionUtils;
37+
38+
/**
39+
* An implementation of an {@link AuthenticationSuccessHandler} used for handling an {@link OAuth2AccessTokenAuthenticationToken}
40+
* and returning the {@link OAuth2AccessTokenResponse Access Token Response}.
41+
*
42+
* @author Dmitriy Dubson
43+
* @see AuthenticationSuccessHandler
44+
* @see OAuth2AccessTokenResponseHttpMessageConverter
45+
* @since 1.3
46+
*/
47+
public final class OAuth2AccessTokenResponseAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
48+
private final Log logger = LogFactory.getLog(getClass());
49+
50+
private HttpMessageConverter<OAuth2AccessTokenResponse> accessTokenResponseConverter =
51+
new OAuth2AccessTokenResponseHttpMessageConverter();
52+
53+
@Override
54+
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
55+
if (!(authentication instanceof OAuth2AccessTokenAuthenticationToken accessTokenAuthentication)) {
56+
if (this.logger.isErrorEnabled()) {
57+
this.logger.error(Authentication.class.getSimpleName() + " must be of type " +
58+
OAuth2AccessTokenAuthenticationToken.class.getName() +
59+
" but was " + authentication.getClass().getName());
60+
}
61+
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, "Unable to process the access token response.", null);
62+
throw new OAuth2AuthenticationException(error);
63+
}
64+
65+
OAuth2AccessToken accessToken = accessTokenAuthentication.getAccessToken();
66+
OAuth2RefreshToken refreshToken = accessTokenAuthentication.getRefreshToken();
67+
Map<String, Object> additionalParameters = accessTokenAuthentication.getAdditionalParameters();
68+
69+
OAuth2AccessTokenResponse.Builder builder =
70+
OAuth2AccessTokenResponse.withToken(accessToken.getTokenValue())
71+
.tokenType(accessToken.getTokenType())
72+
.scopes(accessToken.getScopes());
73+
if (accessToken.getIssuedAt() != null && accessToken.getExpiresAt() != null) {
74+
builder.expiresIn(ChronoUnit.SECONDS.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()));
75+
}
76+
if (refreshToken != null) {
77+
builder.refreshToken(refreshToken.getTokenValue());
78+
}
79+
if (!CollectionUtils.isEmpty(additionalParameters)) {
80+
builder.additionalParameters(additionalParameters);
81+
}
82+
83+
OAuth2AccessTokenResponse accessTokenResponse = builder.build();
84+
ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
85+
this.accessTokenResponseConverter.write(accessTokenResponse, null, httpResponse);
86+
}
87+
88+
/**
89+
* Sets the {@link HttpMessageConverter} used for converting an {@link OAuth2AccessTokenResponse} to an HTTP response.
90+
*
91+
* @param accessTokenResponseConverter the {@link HttpMessageConverter} used for converting an {@link OAuth2AccessTokenResponse} to an HTTP response
92+
*/
93+
public void setAccessTokenResponseConverter(HttpMessageConverter<OAuth2AccessTokenResponse> accessTokenResponseConverter) {
94+
Assert.notNull(accessTokenResponseConverter, "accessTokenHttpResponseConverter cannot be null");
95+
this.accessTokenResponseConverter = accessTokenResponseConverter;
96+
}
97+
}

0 commit comments

Comments
 (0)