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