View Javadoc
1   /*
2    * Copyright 2006-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.client.token;
14  
15  import java.io.UnsupportedEncodingException;
16  import java.math.BigInteger;
17  import java.security.MessageDigest;
18  import java.security.NoSuchAlgorithmException;
19  import java.util.LinkedHashMap;
20  import java.util.Map;
21  
22  import org.springframework.security.core.Authentication;
23  import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
24  import org.springframework.security.oauth2.common.util.OAuth2Utils;
25  
26  /**
27   * Basic key generator taking into account the client id, scope and username (principal name) if they exist.
28   * 
29   * @author Dave Syer
30   * 
31   */
32  public class DefaultClientKeyGenerator implements ClientKeyGenerator {
33  
34  	private static final String CLIENT_ID = "client_id";
35  
36  	private static final String SCOPE = "scope";
37  
38  	private static final String USERNAME = "username";
39  
40  	public String extractKey(OAuth2ProtectedResourceDetails resource, Authentication authentication) {
41  		Map<String, String> values = new LinkedHashMap<String, String>();
42  		if (authentication != null) {
43  			values.put(USERNAME, authentication.getName());
44  		}
45  		values.put(CLIENT_ID, resource.getClientId());
46  		if (resource.getScope() != null) {
47  			values.put(SCOPE, OAuth2Utils.formatParameterList(resource.getScope()));
48  		}
49  		MessageDigest digest;
50  		try {
51  			digest = MessageDigest.getInstance("MD5");
52  		}
53  		catch (NoSuchAlgorithmException e) {
54  			throw new IllegalStateException("MD5 algorithm not available.  Fatal (should be in the JDK).");
55  		}
56  
57  		try {
58  			byte[] bytes = digest.digest(values.toString().getBytes("UTF-8"));
59  			return String.format("%032x", new BigInteger(1, bytes));
60  		}
61  		catch (UnsupportedEncodingException e) {
62  			throw new IllegalStateException("UTF-8 encoding not available.  Fatal (should be in the JDK).");
63  		}
64  	}
65  
66  }