View Javadoc
1   /*
2    * Copyright 2011 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  package org.springframework.security.oauth2.http.converter;
14  
15  import java.io.IOException;
16  
17  import org.springframework.http.HttpInputMessage;
18  import org.springframework.http.HttpOutputMessage;
19  import org.springframework.http.MediaType;
20  import org.springframework.http.converter.AbstractHttpMessageConverter;
21  import org.springframework.http.converter.FormHttpMessageConverter;
22  import org.springframework.http.converter.HttpMessageNotReadableException;
23  import org.springframework.http.converter.HttpMessageNotWritableException;
24  import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
25  import org.springframework.security.oauth2.common.OAuth2AccessToken;
26  import org.springframework.util.MultiValueMap;
27  
28  /**
29   * Converter that can handle inbound form data and convert it to an access token. Needed to support external servers,
30   * like Facebook that might not send JSON token data.
31   * 
32   * @author Rob Winch
33   * @author Dave Syer
34   * 
35   */
36  public class FormOAuth2AccessTokenMessageConverter extends AbstractHttpMessageConverter<OAuth2AccessToken> {
37  
38  	private final FormHttpMessageConverter delegateMessageConverter;
39  
40  	public FormOAuth2AccessTokenMessageConverter() {
41  		super(MediaType.APPLICATION_FORM_URLENCODED, MediaType.TEXT_PLAIN);
42  		this.delegateMessageConverter = new FormHttpMessageConverter();
43  	}
44  
45  	@Override
46  	protected boolean supports(Class<?> clazz) {
47  		return OAuth2AccessToken.class.equals(clazz);
48  	}
49  
50  	@Override
51  	protected OAuth2AccessToken readInternal(Class<? extends OAuth2AccessToken> clazz, HttpInputMessage inputMessage)
52  			throws IOException, HttpMessageNotReadableException {
53  		MultiValueMap<String, String> data = delegateMessageConverter.read(null, inputMessage);
54  		return DefaultOAuth2AccessToken.valueOf(data.toSingleValueMap());
55  	}
56  
57  	@Override
58  	protected void writeInternal(OAuth2AccessToken accessToken, HttpOutputMessage outputMessage) throws IOException,
59  			HttpMessageNotWritableException {
60  		throw new UnsupportedOperationException(
61  				"This converter is only used for converting from externally aqcuired form data");
62  	}
63  }