forked from quarkusio/quarkus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BasicAuthenticationMechanism.java
205 lines (176 loc) · 8.74 KB
/
BasicAuthenticationMechanism.java
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.quarkus.vertx.http.runtime.security;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
import javax.inject.Singleton;
import org.jboss.logging.Logger;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.quarkus.security.AuthenticationFailedException;
import io.quarkus.security.credential.PasswordCredential;
import io.quarkus.security.identity.IdentityProviderManager;
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.security.identity.request.AuthenticationRequest;
import io.quarkus.security.identity.request.UsernamePasswordAuthenticationRequest;
import io.smallrye.mutiny.Uni;
import io.vertx.ext.web.RoutingContext;
/**
* The authentication handler responsible for BASIC authentication as described by RFC2617
*
*/
@Singleton
public class BasicAuthenticationMechanism implements HttpAuthenticationMechanism {
private static final Logger log = Logger.getLogger(BasicAuthenticationMechanism.class);
public static final String SILENT = "silent";
public static final String CHARSET = "charset";
/**
* A comma separated list of patterns and charsets. The pattern is a regular expression.
*
* Because different browsers use different encodings this allows for the correct encoding to be selected based
* on the current browser. In general though it is recommended that BASIC auth not be used when passwords contain
* characters outside ASCII, as some browsers use the current locate to determine encoding.
*
* This list must have an even number of elements, as it is interpreted as pattern,charset,pattern,charset,...
*/
public static final String USER_AGENT_CHARSETS = "user-agent-charsets";
private final String challenge;
private static final String BASIC = "basic";
private static final String BASIC_PREFIX = BASIC + " ";
private static final String LOWERCASE_BASIC_PREFIX = BASIC_PREFIX.toLowerCase(Locale.ENGLISH);
private static final int PREFIX_LENGTH = BASIC_PREFIX.length();
private static final String COLON = ":";
/**
* If silent is true then this mechanism will only take effect if there is an Authorization header.
*
* This allows you to combine basic auth with form auth, so human users will use form based auth, but allows
* programmatic clients to login using basic auth.
*/
private final boolean silent;
private final Charset charset;
private final Map<Pattern, Charset> userAgentCharsets;
public BasicAuthenticationMechanism(final String realmName) {
this(realmName, false);
}
public BasicAuthenticationMechanism(final String realmName, final boolean silent) {
this(realmName, silent, StandardCharsets.UTF_8, Collections.emptyMap());
}
public BasicAuthenticationMechanism(final String realmName, final boolean silent,
Charset charset, Map<Pattern, Charset> userAgentCharsets) {
this.challenge = realmName == null ? BASIC : BASIC_PREFIX + "realm=\"" + realmName + "\"";
this.silent = silent;
this.charset = charset;
this.userAgentCharsets = Collections.unmodifiableMap(new LinkedHashMap<>(userAgentCharsets));
}
@Deprecated
public BasicAuthenticationMechanism(final String realmName, final String mechanismName) {
this(realmName, mechanismName, false);
}
@Deprecated
public BasicAuthenticationMechanism(final String realmName, final String mechanismName, final boolean silent) {
this(realmName, mechanismName, silent, StandardCharsets.UTF_8, Collections.emptyMap());
}
@Deprecated
public BasicAuthenticationMechanism(final String realmName, final String mechanismName, final boolean silent,
Charset charset, Map<Pattern, Charset> userAgentCharsets) {
this.challenge = BASIC_PREFIX + "realm=\"" + realmName + "\"";
this.silent = silent;
this.charset = charset;
this.userAgentCharsets = Collections.unmodifiableMap(new LinkedHashMap<>(userAgentCharsets));
}
@Override
public Uni<SecurityIdentity> authenticate(RoutingContext context,
IdentityProviderManager identityProviderManager) {
List<String> authHeaders = context.request().headers().getAll(HttpHeaderNames.AUTHORIZATION);
if (authHeaders != null) {
for (String current : authHeaders) {
if (current.toLowerCase(Locale.ENGLISH).startsWith(LOWERCASE_BASIC_PREFIX)) {
String base64Challenge = current.substring(PREFIX_LENGTH);
String plainChallenge = null;
byte[] decode = Base64.getDecoder().decode(base64Challenge);
Charset charset = this.charset;
if (!userAgentCharsets.isEmpty()) {
String ua = context.request().headers().get(HttpHeaderNames.USER_AGENT);
if (ua != null) {
for (Map.Entry<Pattern, Charset> entry : userAgentCharsets.entrySet()) {
if (entry.getKey().matcher(ua).find()) {
charset = entry.getValue();
break;
}
}
}
}
plainChallenge = new String(decode, charset);
int colonPos;
if ((colonPos = plainChallenge.indexOf(COLON)) > -1) {
String userName = plainChallenge.substring(0, colonPos);
char[] password = plainChallenge.substring(colonPos + 1).toCharArray();
log.debugf("Found basic auth header %s:***** (decoded using charset %s)", userName, charset);
UsernamePasswordAuthenticationRequest credential = new UsernamePasswordAuthenticationRequest(userName,
new PasswordCredential(password));
HttpSecurityUtils.setRoutingContextAttribute(credential, context);
context.put(HttpAuthenticationMechanism.class.getName(), this);
return identityProviderManager.authenticate(credential);
}
// By this point we had a header we should have been able to verify but for some reason
// it was not correctly structured.
return Uni.createFrom().failure(new AuthenticationFailedException());
}
}
}
// No suitable header has been found in this request,
return Uni.createFrom().optional(Optional.empty());
}
@Override
public Uni<ChallengeData> getChallenge(RoutingContext context) {
if (silent) {
//if this is silent we only send a challenge if the request contained auth headers
//otherwise we assume another method will send the challenge
String authHeader = context.request().headers().get(HttpHeaderNames.AUTHORIZATION);
if (authHeader == null) {
return Uni.createFrom().optional(Optional.empty());
}
}
ChallengeData result = new ChallengeData(
HttpResponseStatus.UNAUTHORIZED.code(),
HttpHeaderNames.WWW_AUTHENTICATE,
challenge);
return Uni.createFrom().item(result);
}
@Override
public Set<Class<? extends AuthenticationRequest>> getCredentialTypes() {
return Collections.singleton(UsernamePasswordAuthenticationRequest.class);
}
@Override
public Uni<HttpCredentialTransport> getCredentialTransport(RoutingContext context) {
return Uni.createFrom().item(new HttpCredentialTransport(HttpCredentialTransport.Type.AUTHORIZATION, BASIC));
}
@Override
public int getPriority() {
return 2000;
}
}