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