1
2
3
4
5
6
7
8
9
10
11
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
29
30
31
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 }