1 package org.springframework.security.oauth2.client.token.auth;
2
3 import java.io.UnsupportedEncodingException;
4
5 import org.springframework.http.HttpHeaders;
6 import org.springframework.security.crypto.codec.Base64;
7 import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
8 import org.springframework.security.oauth2.common.AuthenticationScheme;
9 import org.springframework.util.MultiValueMap;
10 import org.springframework.util.StringUtils;
11
12
13
14
15
16
17
18 public class DefaultClientAuthenticationHandler implements ClientAuthenticationHandler {
19
20 public void authenticateTokenRequest(OAuth2ProtectedResourceDetails resource, MultiValueMap<String, String> form,
21 HttpHeaders headers) {
22 if (resource.isAuthenticationRequired()) {
23 AuthenticationScheme scheme = AuthenticationScheme.header;
24 if (resource.getClientAuthenticationScheme() != null) {
25 scheme = resource.getClientAuthenticationScheme();
26 }
27
28 try {
29 String clientSecret = resource.getClientSecret();
30 clientSecret = clientSecret == null ? "" : clientSecret;
31 switch (scheme) {
32 case header:
33 form.remove("client_secret");
34 headers.add(
35 "Authorization",
36 String.format(
37 "Basic %s",
38 new String(Base64.encode(String.format("%s:%s", resource.getClientId(),
39 clientSecret).getBytes("UTF-8")), "UTF-8")));
40 break;
41 case form:
42 case query:
43 form.set("client_id", resource.getClientId());
44 if (StringUtils.hasText(clientSecret)) {
45 form.set("client_secret", clientSecret);
46 }
47 break;
48 default:
49 throw new IllegalStateException(
50 "Default authentication handler doesn't know how to handle scheme: " + scheme);
51 }
52 }
53 catch (UnsupportedEncodingException e) {
54 throw new IllegalStateException(e);
55 }
56 }
57 }
58 }