View Javadoc
1   /*
2    * Copyright 2008 Web Cohesion
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  
17  package org.springframework.security.oauth.consumer.net;
18  
19  import org.springframework.security.oauth.consumer.OAuthConsumerToken;
20  import org.springframework.security.oauth.consumer.ProtectedResourceDetails;
21  import org.springframework.security.oauth.consumer.OAuthConsumerSupport;
22  
23  import java.io.IOException;
24  import java.net.Proxy;
25  import java.net.URL;
26  import java.net.URLConnection;
27  import java.net.HttpURLConnection;
28  import java.util.Map;
29  
30  /**
31   * Stream handler to handle the request stream to a protected resource over HTTP.
32   *
33   * @author Ryan Heaton
34   */
35  @SuppressWarnings("restriction")
36  public class OAuthOverHttpURLStreamHandler extends sun.net.www.protocol.http.Handler {
37  
38    private final ProtectedResourceDetails resourceDetails;
39    private final OAuthConsumerToken accessToken;
40    private final OAuthConsumerSupport support;
41    private final String httpMethod;
42    private final Map<String, String> additionalParameters;
43  
44    public OAuthOverHttpURLStreamHandler(ProtectedResourceDetails resourceDetails, OAuthConsumerToken accessToken, OAuthConsumerSupport support, String httpMethod, Map<String, String> additionalParameters) {
45      this.resourceDetails = resourceDetails;
46      this.accessToken = accessToken;
47      this.support = support;
48      this.httpMethod = httpMethod;
49      this.additionalParameters = additionalParameters;
50    }
51  
52    @Override
53    protected URLConnection openConnection(URL url, Proxy proxy) throws IOException {
54      HttpURLConnection connection = (HttpURLConnection) super.openConnection(url, proxy);
55      connection.setRequestMethod(this.httpMethod);
56      if (resourceDetails.isAcceptsAuthorizationHeader()) {
57        String authHeader = support.getAuthorizationHeader(resourceDetails, accessToken, url, httpMethod, additionalParameters);
58        connection.setRequestProperty("Authorization", authHeader);
59      }
60      return connection;
61    }
62  
63  }