source: josm/trunk/src/oauth/signpost/AbstractOAuthConsumer.java@ 10831

Last change on this file since 10831 was 10831, checked in by Don-vip, 8 years ago

see #13232 - cleanup OAuth signpost code:

  • remove classes unused by JOSM
  • add missing @Override annotations
File size: 9.2 KB
Line 
1/* Copyright (c) 2009 Matthias Kaeppler
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15package oauth.signpost;
16
17import java.io.IOException;
18import java.io.InputStream;
19import java.util.Random;
20
21import oauth.signpost.basic.UrlStringRequestAdapter;
22import oauth.signpost.exception.OAuthCommunicationException;
23import oauth.signpost.exception.OAuthExpectationFailedException;
24import oauth.signpost.exception.OAuthMessageSignerException;
25import oauth.signpost.http.HttpParameters;
26import oauth.signpost.http.HttpRequest;
27import oauth.signpost.signature.AuthorizationHeaderSigningStrategy;
28import oauth.signpost.signature.HmacSha1MessageSigner;
29import oauth.signpost.signature.OAuthMessageSigner;
30import oauth.signpost.signature.QueryStringSigningStrategy;
31import oauth.signpost.signature.SigningStrategy;
32
33/**
34 * ABC for consumer implementations. If you're developing a custom consumer you
35 * will probably inherit from this class to save you a lot of work.
36 *
37 * @author Matthias Kaeppler
38 */
39public abstract class AbstractOAuthConsumer implements OAuthConsumer {
40
41 private static final long serialVersionUID = 1L;
42
43 private String consumerKey, consumerSecret;
44
45 private String token;
46
47 private OAuthMessageSigner messageSigner;
48
49 private SigningStrategy signingStrategy;
50
51 // these are params that may be passed to the consumer directly (i.e.
52 // without going through the request object)
53 private HttpParameters additionalParameters;
54
55 // these are the params which will be passed to the message signer
56 private HttpParameters requestParameters;
57
58 private boolean sendEmptyTokens;
59
60 final private Random random = new Random(System.nanoTime());
61
62 public AbstractOAuthConsumer(String consumerKey, String consumerSecret) {
63 this.consumerKey = consumerKey;
64 this.consumerSecret = consumerSecret;
65 setMessageSigner(new HmacSha1MessageSigner());
66 setSigningStrategy(new AuthorizationHeaderSigningStrategy());
67 }
68
69 @Override
70 public void setMessageSigner(OAuthMessageSigner messageSigner) {
71 this.messageSigner = messageSigner;
72 messageSigner.setConsumerSecret(consumerSecret);
73 }
74
75 @Override
76 public void setSigningStrategy(SigningStrategy signingStrategy) {
77 this.signingStrategy = signingStrategy;
78 }
79
80 @Override
81 public void setAdditionalParameters(HttpParameters additionalParameters) {
82 this.additionalParameters = additionalParameters;
83 }
84
85 @Override
86 public synchronized HttpRequest sign(HttpRequest request) throws OAuthMessageSignerException,
87 OAuthExpectationFailedException, OAuthCommunicationException {
88 if (consumerKey == null) {
89 throw new OAuthExpectationFailedException("consumer key not set");
90 }
91 if (consumerSecret == null) {
92 throw new OAuthExpectationFailedException("consumer secret not set");
93 }
94
95 requestParameters = new HttpParameters();
96 try {
97 if (additionalParameters != null) {
98 requestParameters.putAll(additionalParameters, false);
99 }
100 collectHeaderParameters(request, requestParameters);
101 collectQueryParameters(request, requestParameters);
102 collectBodyParameters(request, requestParameters);
103
104 // add any OAuth params that haven't already been set
105 completeOAuthParameters(requestParameters);
106
107 requestParameters.remove(OAuth.OAUTH_SIGNATURE);
108
109 } catch (IOException e) {
110 throw new OAuthCommunicationException(e);
111 }
112
113 String signature = messageSigner.sign(request, requestParameters);
114 OAuth.debugOut("signature", signature);
115
116 signingStrategy.writeSignature(signature, request, requestParameters);
117 OAuth.debugOut("Request URL", request.getRequestUrl());
118
119 return request;
120 }
121
122 @Override
123 public synchronized HttpRequest sign(Object request) throws OAuthMessageSignerException,
124 OAuthExpectationFailedException, OAuthCommunicationException {
125 return sign(wrap(request));
126 }
127
128 @Override
129 public synchronized String sign(String url) throws OAuthMessageSignerException,
130 OAuthExpectationFailedException, OAuthCommunicationException {
131 HttpRequest request = new UrlStringRequestAdapter(url);
132
133 // switch to URL signing
134 SigningStrategy oldStrategy = this.signingStrategy;
135 this.signingStrategy = new QueryStringSigningStrategy();
136
137 sign(request);
138
139 // revert to old strategy
140 this.signingStrategy = oldStrategy;
141
142 return request.getRequestUrl();
143 }
144
145 /**
146 * Adapts the given request object to a Signpost {@link HttpRequest}. How
147 * this is done depends on the consumer implementation.
148 *
149 * @param request
150 * the native HTTP request instance
151 * @return the adapted request
152 */
153 protected abstract HttpRequest wrap(Object request);
154
155 @Override
156 public void setTokenWithSecret(String token, String tokenSecret) {
157 this.token = token;
158 messageSigner.setTokenSecret(tokenSecret);
159 }
160
161 @Override
162 public String getToken() {
163 return token;
164 }
165
166 @Override
167 public String getTokenSecret() {
168 return messageSigner.getTokenSecret();
169 }
170
171 @Override
172 public String getConsumerKey() {
173 return this.consumerKey;
174 }
175
176 @Override
177 public String getConsumerSecret() {
178 return this.consumerSecret;
179 }
180
181 /**
182 * <p>
183 * Helper method that adds any OAuth parameters to the given request
184 * parameters which are missing from the current request but required for
185 * signing. A good example is the oauth_nonce parameter, which is typically
186 * not provided by the client in advance.
187 * </p>
188 * <p>
189 * It's probably not a very good idea to override this method. If you want
190 * to generate different nonces or timestamps, override
191 * {@link #generateNonce()} or {@link #generateTimestamp()} instead.
192 * </p>
193 *
194 * @param out
195 * the request parameter which should be completed
196 */
197 protected void completeOAuthParameters(HttpParameters out) {
198 if (!out.containsKey(OAuth.OAUTH_CONSUMER_KEY)) {
199 out.put(OAuth.OAUTH_CONSUMER_KEY, consumerKey, true);
200 }
201 if (!out.containsKey(OAuth.OAUTH_SIGNATURE_METHOD)) {
202 out.put(OAuth.OAUTH_SIGNATURE_METHOD, messageSigner.getSignatureMethod(), true);
203 }
204 if (!out.containsKey(OAuth.OAUTH_TIMESTAMP)) {
205 out.put(OAuth.OAUTH_TIMESTAMP, generateTimestamp(), true);
206 }
207 if (!out.containsKey(OAuth.OAUTH_NONCE)) {
208 out.put(OAuth.OAUTH_NONCE, generateNonce(), true);
209 }
210 if (!out.containsKey(OAuth.OAUTH_VERSION)) {
211 out.put(OAuth.OAUTH_VERSION, OAuth.VERSION_1_0, true);
212 }
213 if (!out.containsKey(OAuth.OAUTH_TOKEN)) {
214 if (token != null && !token.equals("") || sendEmptyTokens) {
215 out.put(OAuth.OAUTH_TOKEN, token, true);
216 }
217 }
218 }
219
220 @Override
221 public HttpParameters getRequestParameters() {
222 return requestParameters;
223 }
224
225 @Override
226 public void setSendEmptyTokens(boolean enable) {
227 this.sendEmptyTokens = enable;
228 }
229
230 /**
231 * Collects OAuth Authorization header parameters as per OAuth Core 1.0 spec
232 * section 9.1.1
233 */
234 protected void collectHeaderParameters(HttpRequest request, HttpParameters out) {
235 HttpParameters headerParams = OAuth.oauthHeaderToParamsMap(request.getHeader(OAuth.HTTP_AUTHORIZATION_HEADER));
236 out.putAll(headerParams, false);
237 }
238
239 /**
240 * Collects x-www-form-urlencoded body parameters as per OAuth Core 1.0 spec
241 * section 9.1.1
242 */
243 protected void collectBodyParameters(HttpRequest request, HttpParameters out)
244 throws IOException {
245
246 // collect x-www-form-urlencoded body params
247 String contentType = request.getContentType();
248 if (contentType != null && contentType.startsWith(OAuth.FORM_ENCODED)) {
249 InputStream payload = request.getMessagePayload();
250 out.putAll(OAuth.decodeForm(payload), true);
251 }
252 }
253
254 /**
255 * Collects HTTP GET query string parameters as per OAuth Core 1.0 spec
256 * section 9.1.1
257 */
258 protected void collectQueryParameters(HttpRequest request, HttpParameters out) {
259
260 String url = request.getRequestUrl();
261 int q = url.indexOf('?');
262 if (q >= 0) {
263 // Combine the URL query string with the other parameters:
264 out.putAll(OAuth.decodeForm(url.substring(q + 1)), true);
265 }
266 }
267
268 protected String generateTimestamp() {
269 return Long.toString(System.currentTimeMillis() / 1000L);
270 }
271
272 protected String generateNonce() {
273 return Long.toString(random.nextLong());
274 }
275}
Note: See TracBrowser for help on using the repository browser.