View Javadoc
1   /*
2    * Copyright 2013-2018 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
5    * the License. You may obtain a copy of the License at
6    *
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
10   * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11   * specific language governing permissions and limitations under the License.
12   */
13  
14  package org.springframework.security.oauth2.client;
15  
16  import org.springframework.http.client.ClientHttpRequest;
17  import org.springframework.security.oauth2.client.http.AccessTokenRequiredException;
18  import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
19  import org.springframework.security.oauth2.common.OAuth2AccessToken;
20  import org.springframework.util.StringUtils;
21  
22  /**
23   * @author Dave Syer
24   *
25   */
26  public class DefaultOAuth2RequestAuthenticator implements OAuth2RequestAuthenticator {
27  
28  	@Override
29  	public void authenticate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext clientContext,
30  			ClientHttpRequest request) {
31  		OAuth2AccessToken accessToken = clientContext.getAccessToken();
32  		if (accessToken == null) {
33  			throw new AccessTokenRequiredException(resource);
34  		}
35  		String tokenType = accessToken.getTokenType();
36  		if (!StringUtils.hasText(tokenType)) {
37  			tokenType = OAuth2AccessToken.BEARER_TYPE; // we'll assume basic bearer token type if none is specified.
38  		} else if (tokenType.equalsIgnoreCase(OAuth2AccessToken.BEARER_TYPE)) {
39  			// gh-1346
40  			tokenType = OAuth2AccessToken.BEARER_TYPE; // Ensure we use the correct syntax for the "Bearer" authentication scheme
41  		}
42  		request.getHeaders().set("Authorization", String.format("%s %s", tokenType, accessToken.getValue()));
43  	}
44  
45  }