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 import java.nio.charset.StandardCharsets;
23
24 import org.eclipse.jetty.client.api.Authentication;
25 import org.eclipse.jetty.client.api.ContentResponse;
26 import org.eclipse.jetty.client.api.Request;
27 import org.eclipse.jetty.http.HttpHeader;
28 import org.eclipse.jetty.util.Attributes;
29 import org.eclipse.jetty.util.B64Code;
30
31
32
33
34
35
36
37
38 public class BasicAuthentication implements Authentication
39 {
40 private final URI uri;
41 private final String realm;
42 private final String user;
43 private final String password;
44
45
46
47
48
49
50
51 public BasicAuthentication(URI uri, String realm, String user, String password)
52 {
53 this.uri = uri;
54 this.realm = realm;
55 this.user = user;
56 this.password = password;
57 }
58
59 @Override
60 public boolean matches(String type, URI uri, String realm)
61 {
62 if (!"basic".equalsIgnoreCase(type))
63 return false;
64
65 if (!uri.toString().startsWith(this.uri.toString()))
66 return false;
67
68 return this.realm.equals(realm);
69 }
70
71 @Override
72 public Result authenticate(Request request, ContentResponse response, HeaderInfo headerInfo, Attributes context)
73 {
74 String value = "Basic " + B64Code.encode(user + ":" + password, StandardCharsets.ISO_8859_1);
75 return new BasicResult(headerInfo.getHeader(), uri, value);
76 }
77
78 private static class BasicResult implements Result
79 {
80 private final HttpHeader header;
81 private final URI uri;
82 private final String value;
83
84 public BasicResult(HttpHeader header, URI uri, String value)
85 {
86 this.header = header;
87 this.uri = uri;
88 this.value = value;
89 }
90
91 @Override
92 public URI getURI()
93 {
94 return uri;
95 }
96
97 @Override
98 public void apply(Request request)
99 {
100 request.header(header, value);
101 }
102
103 @Override
104 public String toString()
105 {
106 return String.format("Basic authentication result for %s", uri);
107 }
108 }
109 }