|
15 | 15 | */
|
16 | 16 | package org.springframework.security.oauth2.server.authorization.web;
|
17 | 17 |
|
| 18 | +import com.fasterxml.jackson.annotation.JsonInclude; |
| 19 | +import com.fasterxml.jackson.databind.ObjectMapper; |
18 | 20 | import org.springframework.core.convert.converter.Converter;
|
| 21 | +import org.springframework.http.HttpHeaders; |
| 22 | +import org.springframework.http.HttpMethod; |
| 23 | +import org.springframework.http.HttpStatus; |
| 24 | +import org.springframework.http.MediaType; |
19 | 25 | import org.springframework.security.authentication.AuthenticationManager;
|
20 | 26 | import org.springframework.security.core.Authentication;
|
| 27 | +import org.springframework.security.core.context.SecurityContextHolder; |
| 28 | +import org.springframework.security.oauth2.core.AuthorizationGrantType; |
| 29 | +import org.springframework.security.oauth2.core.OAuth2AccessToken; |
| 30 | +import org.springframework.security.oauth2.core.OAuth2AuthenticationException; |
| 31 | +import org.springframework.security.oauth2.core.OAuth2Error; |
| 32 | +import org.springframework.security.oauth2.core.OAuth2ErrorCodes; |
| 33 | +import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; |
| 34 | +import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; |
21 | 35 | import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
|
| 36 | +import org.springframework.security.oauth2.server.authorization.TokenType; |
| 37 | +import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken; |
| 38 | +import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeAuthenticationToken; |
| 39 | +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; |
| 40 | +import org.springframework.security.web.util.matcher.RequestMatcher; |
| 41 | +import org.springframework.util.Assert; |
| 42 | +import org.springframework.util.StringUtils; |
22 | 43 | import org.springframework.web.filter.OncePerRequestFilter;
|
23 | 44 |
|
24 | 45 | import javax.servlet.FilterChain;
|
25 | 46 | import javax.servlet.ServletException;
|
26 | 47 | import javax.servlet.http.HttpServletRequest;
|
27 | 48 | import javax.servlet.http.HttpServletResponse;
|
28 | 49 | import java.io.IOException;
|
| 50 | +import java.io.Writer; |
29 | 51 |
|
30 | 52 | /**
|
| 53 | + * This {@code Filter} is used by the client to obtain an access token by presenting |
| 54 | + * its authorization grant. |
| 55 | + * |
| 56 | + * <p> |
| 57 | + * It converts the OAuth 2.0 Access Token Request to {@link OAuth2AuthorizationCodeAuthenticationToken}, |
| 58 | + * which is then authenticated by the {@link AuthenticationManager} and gets back |
| 59 | + * {@link OAuth2AccessTokenAuthenticationToken} which has the {@link OAuth2AccessToken} if the request |
| 60 | + * was successfully authenticated. The {@link OAuth2AccessToken} is then updated in the in-flight {@link OAuth2Authorization} |
| 61 | + * and sent back to the client. In case the authentication fails, an HTTP 401 (Unauthorized) response is returned. |
| 62 | + * |
| 63 | + * <p> |
| 64 | + * By default, this {@code Filter} responds to access token requests |
| 65 | + * at the {@code URI} {@code /oauth2/token} and {@code HttpMethod} {@code POST} |
| 66 | + * using the default {@link AntPathRequestMatcher}. |
| 67 | + * |
| 68 | + * <p> |
| 69 | + * The default base {@code URI} {@code /oauth2/token} may be overridden |
| 70 | + * via the constructor {@link #OAuth2TokenEndpointFilter(OAuth2AuthorizationService, AuthenticationManager, String)}. |
| 71 | + * |
31 | 72 | * @author Joe Grandja
|
| 73 | + * @author Madhu Bhat |
32 | 74 | */
|
33 | 75 | public class OAuth2TokenEndpointFilter extends OncePerRequestFilter {
|
34 |
| - private Converter<HttpServletRequest, Authentication> authorizationGrantConverter; |
| 76 | + /** |
| 77 | + * The default endpoint {@code URI} for access token requests. |
| 78 | + */ |
| 79 | + private static final String DEFAULT_TOKEN_ENDPOINT_URI = "/oauth2/token"; |
| 80 | + |
| 81 | + private Converter<HttpServletRequest, Authentication> authorizationGrantConverter = this::convert; |
35 | 82 | private AuthenticationManager authenticationManager;
|
36 | 83 | private OAuth2AuthorizationService authorizationService;
|
| 84 | + private RequestMatcher uriMatcher; |
| 85 | + private ObjectMapper objectMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL); |
| 86 | + |
| 87 | + /** |
| 88 | + * Constructs an {@code OAuth2TokenEndpointFilter} using the provided parameters. |
| 89 | + * |
| 90 | + * @param authorizationService the authorization service implementation |
| 91 | + * @param authenticationManager the authentication manager implementation |
| 92 | + */ |
| 93 | + public OAuth2TokenEndpointFilter(OAuth2AuthorizationService authorizationService, AuthenticationManager authenticationManager) { |
| 94 | + Assert.notNull(authorizationService, "authorizationService cannot be null"); |
| 95 | + Assert.notNull(authenticationManager, "authenticationManager cannot be null"); |
| 96 | + this.authenticationManager = authenticationManager; |
| 97 | + this.authorizationService = authorizationService; |
| 98 | + this.uriMatcher = new AntPathRequestMatcher(DEFAULT_TOKEN_ENDPOINT_URI, HttpMethod.POST.name()); |
| 99 | + } |
| 100 | + |
| 101 | + /** |
| 102 | + * Constructs an {@code OAuth2TokenEndpointFilter} using the provided parameters. |
| 103 | + * |
| 104 | + * @param authorizationService the authorization service implementation |
| 105 | + * @param authenticationManager the authentication manager implementation |
| 106 | + * @param tokenEndpointUri the token endpoint's uri |
| 107 | + */ |
| 108 | + public OAuth2TokenEndpointFilter(OAuth2AuthorizationService authorizationService, AuthenticationManager authenticationManager, |
| 109 | + String tokenEndpointUri) { |
| 110 | + Assert.notNull(authorizationService, "authorizationService cannot be null"); |
| 111 | + Assert.notNull(authenticationManager, "authenticationManager cannot be null"); |
| 112 | + Assert.hasText(tokenEndpointUri, "tokenEndpointUri cannot be empty"); |
| 113 | + this.authenticationManager = authenticationManager; |
| 114 | + this.authorizationService = authorizationService; |
| 115 | + this.uriMatcher = new AntPathRequestMatcher(tokenEndpointUri, HttpMethod.POST.name()); |
| 116 | + } |
37 | 117 |
|
38 | 118 | @Override
|
39 | 119 | protected void doFilterInternal(HttpServletRequest request,
|
40 | 120 | HttpServletResponse response, FilterChain filterChain)
|
41 | 121 | throws ServletException, IOException {
|
| 122 | + if (uriMatcher.matches(request)) { |
| 123 | + try { |
| 124 | + if (validateAccessTokenRequest(request)) { |
| 125 | + OAuth2AuthorizationCodeAuthenticationToken authCodeAuthToken = |
| 126 | + (OAuth2AuthorizationCodeAuthenticationToken) authorizationGrantConverter.convert(request); |
| 127 | + OAuth2AccessTokenAuthenticationToken accessTokenAuthenticationToken = |
| 128 | + (OAuth2AccessTokenAuthenticationToken) authenticationManager.authenticate(authCodeAuthToken); |
| 129 | + if (accessTokenAuthenticationToken.isAuthenticated()) { |
| 130 | + OAuth2Authorization authorization = authorizationService |
| 131 | + .findByTokenAndTokenType(authCodeAuthToken.getCode(), TokenType.AUTHORIZATION_CODE); |
| 132 | + authorization.setAccessToken(accessTokenAuthenticationToken.getAccessToken()); |
| 133 | + authorizationService.save(authorization); |
| 134 | + writeSuccessResponse(response, accessTokenAuthenticationToken.getAccessToken()); |
| 135 | + } else { |
| 136 | + throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT)); |
| 137 | + } |
| 138 | + } |
| 139 | + } catch (OAuth2AuthenticationException exception) { |
| 140 | + SecurityContextHolder.clearContext(); |
| 141 | + writeFailureResponse(response, exception.getError()); |
| 142 | + } |
| 143 | + } else { |
| 144 | + filterChain.doFilter(request, response); |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + private boolean validateAccessTokenRequest(HttpServletRequest request) { |
| 149 | + if (StringUtils.isEmpty(request.getParameter(OAuth2ParameterNames.CODE)) |
| 150 | + || StringUtils.isEmpty(request.getParameter(OAuth2ParameterNames.REDIRECT_URI)) |
| 151 | + || StringUtils.isEmpty(request.getParameter(OAuth2ParameterNames.GRANT_TYPE))) { |
| 152 | + throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST)); |
| 153 | + } else if (!AuthorizationGrantType.AUTHORIZATION_CODE.getValue().equals(request.getParameter(OAuth2ParameterNames.GRANT_TYPE))) { |
| 154 | + throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.UNSUPPORTED_GRANT_TYPE)); |
| 155 | + } |
| 156 | + return true; |
| 157 | + } |
| 158 | + |
| 159 | + private OAuth2AuthorizationCodeAuthenticationToken convert(HttpServletRequest request) { |
| 160 | + Authentication clientPrincipal = SecurityContextHolder.getContext().getAuthentication(); |
| 161 | + return new OAuth2AuthorizationCodeAuthenticationToken( |
| 162 | + request.getParameter(OAuth2ParameterNames.CODE), |
| 163 | + clientPrincipal, |
| 164 | + request.getParameter(OAuth2ParameterNames.REDIRECT_URI) |
| 165 | + ); |
| 166 | + } |
| 167 | + |
| 168 | + private void writeSuccessResponse(HttpServletResponse response, OAuth2AccessToken body) throws IOException { |
| 169 | + try (Writer out = response.getWriter()) { |
| 170 | + response.setStatus(HttpStatus.OK.value()); |
| 171 | + response.setContentType(MediaType.APPLICATION_JSON_VALUE); |
| 172 | + response.setCharacterEncoding("UTF-8"); |
| 173 | + response.setHeader(HttpHeaders.CACHE_CONTROL, "no-store"); |
| 174 | + response.setHeader(HttpHeaders.PRAGMA, "no-cache"); |
| 175 | + out.write(objectMapper.writeValueAsString(body)); |
| 176 | + } |
| 177 | + } |
42 | 178 |
|
| 179 | + private void writeFailureResponse(HttpServletResponse response, OAuth2Error error) throws IOException { |
| 180 | + try (Writer out = response.getWriter()) { |
| 181 | + if (error.getErrorCode().equals(OAuth2ErrorCodes.INVALID_CLIENT)) { |
| 182 | + response.setStatus(HttpStatus.UNAUTHORIZED.value()); |
| 183 | + } else { |
| 184 | + response.setStatus(HttpStatus.BAD_REQUEST.value()); |
| 185 | + } |
| 186 | + response.setContentType(MediaType.APPLICATION_JSON_VALUE); |
| 187 | + response.setCharacterEncoding("UTF-8"); |
| 188 | + out.write(objectMapper.writeValueAsString(error)); |
| 189 | + } |
43 | 190 | }
|
44 | 191 | }
|
0 commit comments