1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.jetty.client.util;
20
21 import java.net.URI;
22
23 import org.eclipse.jetty.client.HttpClient;
24 import org.eclipse.jetty.client.api.Authentication;
25 import org.eclipse.jetty.client.api.AuthenticationStore;
26 import org.eclipse.jetty.client.api.ContentResponse;
27 import org.eclipse.jetty.client.api.Request;
28 import org.eclipse.jetty.http.HttpHeader;
29 import org.eclipse.jetty.util.Attributes;
30 import org.eclipse.jetty.util.B64Code;
31 import org.eclipse.jetty.util.StringUtil;
32
33
34
35
36
37
38
39
40 public class BasicAuthentication implements Authentication
41 {
42 private final URI uri;
43 private final String realm;
44 private final String user;
45 private final String password;
46
47
48
49
50
51
52
53 public BasicAuthentication(URI uri, String realm, String user, String password)
54 {
55 this.uri = uri;
56 this.realm = realm;
57 this.user = user;
58 this.password = password;
59 }
60
61 @Override
62 public boolean matches(String type, URI uri, String realm)
63 {
64 if (!"basic".equalsIgnoreCase(type))
65 return false;
66
67 if (!uri.toString().startsWith(this.uri.toString()))
68 return false;
69
70 return this.realm.equals(realm);
71 }
72
73 @Override
74 public Result authenticate(Request request, ContentResponse response, HeaderInfo headerInfo, Attributes context)
75 {
76 String encoding = StringUtil.__ISO_8859_1;
77 String value = "Basic " + B64Code.encode(user + ":" + password, encoding);
78 return new BasicResult(headerInfo.getHeader(), uri, value);
79 }
80
81 private static class BasicResult implements Result
82 {
83 private final HttpHeader header;
84 private final URI uri;
85 private final String value;
86
87 public BasicResult(HttpHeader header, URI uri, String value)
88 {
89 this.header = header;
90 this.uri = uri;
91 this.value = value;
92 }
93
94 @Override
95 public URI getURI()
96 {
97 return uri;
98 }
99
100 @Override
101 public void apply(Request request)
102 {
103 request.header(header, value);
104 }
105
106 @Override
107 public String toString()
108 {
109 return String.format("Basic authentication result for %s", uri);
110 }
111 }
112 }