1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.apache.hc.client5.testing.auth;
29
30 import java.util.List;
31
32 import org.apache.hc.core5.http.HttpException;
33 import org.apache.hc.core5.http.NameValuePair;
34 import org.apache.hc.core5.http.ProtocolException;
35
36 abstract class AbstractAuthenticationHandler implements AuthenticationHandler<String> {
37
38 abstract String getSchemeName();
39
40 @Override
41 public final String challenge(final List<NameValuePair> params) {
42 final StringBuilder buf = new StringBuilder();
43 buf.append(getSchemeName());
44 if (params != null && params.size() > 0) {
45 buf.append(" ");
46 for (int i = 0; i < params.size(); i++) {
47 if (i > 0) {
48 buf.append(", ");
49 }
50 final NameValuePair param = params.get(i);
51 buf.append(param.getName()).append("=\"").append(param.getValue()).append("\"");
52 }
53 }
54 return buf.toString();
55 }
56
57 abstract String decodeChallenge(String challenge);
58
59 public final String extractAuthToken(final String challengeResponse) throws HttpException {
60 final int i = challengeResponse.indexOf(' ');
61 if (i == -1) {
62 throw new ProtocolException("Invalid " + getSchemeName() + " challenge response");
63 }
64 final String schemeName = challengeResponse.substring(0, i);
65 if (schemeName.equalsIgnoreCase(getSchemeName())) {
66 final String s = challengeResponse.substring(i + 1).trim();
67 try {
68 return decodeChallenge(s);
69 } catch (final IllegalArgumentException ex) {
70 throw new ProtocolException("Malformed " + getSchemeName() + " credentials");
71 }
72 } else {
73 throw new ProtocolException("Unexpected challenge type");
74 }
75 }
76
77 }