You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucene.apache.org by da...@apache.org on 2018/11/12 17:19:00 UTC

lucene-solr:jira/http2: Add Keberos support based on latest Jetty source

Repository: lucene-solr
Updated Branches:
  refs/heads/jira/http2 6dd3ef2b8 -> 7ca1dad37


Add Keberos support based on latest Jetty source


Project: http://git-wip-us.apache.org/repos/asf/lucene-solr/repo
Commit: http://git-wip-us.apache.org/repos/asf/lucene-solr/commit/7ca1dad3
Tree: http://git-wip-us.apache.org/repos/asf/lucene-solr/tree/7ca1dad3
Diff: http://git-wip-us.apache.org/repos/asf/lucene-solr/diff/7ca1dad3

Branch: refs/heads/jira/http2
Commit: 7ca1dad37128d04d1d8353a2fd1b7b286e1a9dec
Parents: 6dd3ef2
Author: Cao Manh Dat <da...@apache.org>
Authored: Mon Nov 12 17:18:51 2018 +0000
Committer: Cao Manh Dat <da...@apache.org>
Committed: Mon Nov 12 17:18:51 2018 +0000

----------------------------------------------------------------------
 solr/solrj/build.xml                            |   4 +-
 .../solrj/impl/Krb5HttpClientBuilder.java       | 106 ++----
 .../client/AuthenticationProtocolHandler.java   | 314 +++++++++++++++
 .../jetty/client/SPNEGOAuthentication.java      | 380 +++++++++++++++++++
 4 files changed, 737 insertions(+), 67 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/7ca1dad3/solr/solrj/build.xml
----------------------------------------------------------------------
diff --git a/solr/solrj/build.xml b/solr/solrj/build.xml
index 3393438..fce4c55 100644
--- a/solr/solrj/build.xml
+++ b/solr/solrj/build.xml
@@ -52,7 +52,9 @@
       <mkdir dir="${javadoc.dir}/${name}"/>
       <solr-invoke-javadoc>
         <solrsources>
-          <packageset dir="${src.dir}"/>
+          <packageset dir="${src.dir}">
+            <exclude name="**/jetty/**"/>
+          </packageset>
         </solrsources>
       </solr-invoke-javadoc>
       <solr-jarify basedir="${javadoc.dir}/${name}" destfile="${build.dir}/${final.name}-javadoc.jar"/>

http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/7ca1dad3/solr/solrj/src/java/org/apache/solr/client/solrj/impl/Krb5HttpClientBuilder.java
----------------------------------------------------------------------
diff --git a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/Krb5HttpClientBuilder.java b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/Krb5HttpClientBuilder.java
index 80aff09..0695c98 100644
--- a/solr/solrj/src/java/org/apache/solr/client/solrj/impl/Krb5HttpClientBuilder.java
+++ b/solr/solrj/src/java/org/apache/solr/client/solrj/impl/Krb5HttpClientBuilder.java
@@ -16,18 +16,18 @@
  */
 package org.apache.solr.client.solrj.impl;
 
+import javax.security.auth.login.AppConfigurationEntry;
+import javax.security.auth.login.Configuration;
 import java.lang.invoke.MethodHandles;
 import java.net.URI;
+import java.nio.file.Paths;
 import java.security.Principal;
 import java.util.Arrays;
 import java.util.HashSet;
 import java.util.Locale;
+import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import javax.security.auth.login.AppConfigurationEntry;
-import javax.security.auth.login.Configuration;
 
 import org.apache.http.HttpEntity;
 import org.apache.http.HttpEntityEnclosingRequest;
@@ -44,17 +44,8 @@ import org.apache.http.entity.BufferedHttpEntity;
 import org.apache.http.impl.auth.SPNegoSchemeFactory;
 import org.apache.http.impl.client.BasicCredentialsProvider;
 import org.eclipse.jetty.client.HttpAuthenticationStore;
+import org.eclipse.jetty.client.SPNEGOAuthentication;
 import org.eclipse.jetty.client.WWWAuthenticationProtocolHandler;
-import org.eclipse.jetty.client.api.Authentication;
-import org.eclipse.jetty.client.api.ContentResponse;
-import org.eclipse.jetty.client.api.Request;
-import org.eclipse.jetty.util.Attributes;
-import org.ietf.jgss.GSSContext;
-import org.ietf.jgss.GSSCredential;
-import org.ietf.jgss.GSSException;
-import org.ietf.jgss.GSSManager;
-import org.ietf.jgss.GSSName;
-import org.ietf.jgss.Oid;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -95,62 +86,45 @@ public class Krb5HttpClientBuilder implements HttpClientBuilderFactory {
     return builder.isPresent() ? getBuilder(builder.get()) : getBuilder();
   }
 
-  @Override
-  public void setup(Http2SolrClient http2Client) {
-    HttpAuthenticationStore authenticationStore = new HttpAuthenticationStore();
-    authenticationStore.addAuthentication(new Authentication() {
-      @Override
+  private SPNEGOAuthentication createSPNEGOAuthentication() {
+    SPNEGOAuthentication authentication = new SPNEGOAuthentication(null){
+
       public boolean matches(String type, URI uri, String realm) {
-        return "Negotiate".equals(type);
+        return this.getType().equals(type);
       }
-
-      @Override
-      public Result authenticate(Request request, ContentResponse response, HeaderInfo headerInfo, Attributes context) {
-        String challenge = headerInfo.getBase64();
-        if (challenge == null) challenge = "";
-        byte[] input = java.util.Base64.getDecoder().decode(challenge);
-        byte[] token;
-        String authServer = request.getHost();
-        final GSSManager manager = GSSManager.getInstance();
-        try {
-          GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE);
-          final GSSContext gssContext = createGSSContext(manager, new Oid(SPNEGO_OID), serverName, null);
-          if (input != null) {
-            token = gssContext.initSecContext(input, 0, input.length);
-          } else {
-            token = gssContext.initSecContext(new byte[] {}, 0, 0);
-          }
-        } catch (GSSException e) {
-          throw new IllegalArgumentException("Unable to init GSSContext", e);
-        }
-        return new Result() {
-          AtomicBoolean sentToken = new AtomicBoolean(false);
-          @Override
-          public URI getURI() {
-            // Since Kerberos is connection based authentication, sub-sequence requests won't need to resend the token in header
-            // by return null, the ProtocolHandler won't try to apply this result on sequence requests
-            return null;
-          }
-
-          @Override
-          public void apply(Request request) {
-            if (sentToken.get()) return;
-
-            final String tokenstr = java.util.Base64.getEncoder().encodeToString(token);
-            log.info("Sending response with token:{} back to the auth server", tokenstr);
-            request.header(headerInfo.getHeader().asString(), "Negotiate "+tokenstr);
-          }
-        };
+    };
+    String clientAppName = System.getProperty("solr.kerberos.jaas.appname", "Client");
+    AppConfigurationEntry[] entries = jaasConfig.getAppConfigurationEntry(clientAppName);
+    if (entries == null) {
+      log.warn("Could not find login configuration entry for {}. SPNego authentication may not be successful.", (Object)clientAppName);
+      return authentication;
+    }
+    if (entries.length != 1) {
+      log.warn("Multiple login modules are specified in the configuration file");
+      return authentication;
+    }
+    Map<String, ?> options = entries[0].getOptions();
+    String keyTab = (String)options.get("keyTab");
+    if (keyTab != null) {
+      authentication.setUserKeyTabPath(Paths.get(keyTab, new String[0]));
+    }
+    authentication.setServiceName("HTTP");
+    authentication.setUserName((String)options.get("principal"));
+    if ("true".equalsIgnoreCase((String)options.get("useTicketCache"))) {
+      authentication.setUseTicketCache(true);
+      String ticketCachePath = (String)options.get("ticketCache");
+      if (ticketCachePath != null) {
+        authentication.setTicketCachePath(Paths.get(ticketCachePath));
       }
+      authentication.setRenewTGT("true".equalsIgnoreCase((String)options.get("renewTGT")));
+    }
+    return authentication;
+  }
 
-      private GSSContext createGSSContext(GSSManager manager, Oid oid, GSSName serverName, final GSSCredential gssCredential) throws GSSException {
-        // Get the credentials from the JAAS configuration rather than here
-        final GSSContext gssContext = manager.createContext(serverName.canonicalize(oid), oid, gssCredential,
-            GSSContext.DEFAULT_LIFETIME);
-        gssContext.requestMutualAuth(true);
-        return gssContext;
-      }
-    });
+  @Override
+  public void setup(Http2SolrClient http2Client) {
+    HttpAuthenticationStore authenticationStore = new HttpAuthenticationStore();
+    authenticationStore.addAuthentication(createSPNEGOAuthentication());
     http2Client.getHttpClient().setAuthenticationStore(authenticationStore);
     http2Client.getProtocolHandlers().put(new WWWAuthenticationProtocolHandler(http2Client.getHttpClient()));
   }

http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/7ca1dad3/solr/solrj/src/java/org/eclipse/jetty/client/AuthenticationProtocolHandler.java
----------------------------------------------------------------------
diff --git a/solr/solrj/src/java/org/eclipse/jetty/client/AuthenticationProtocolHandler.java b/solr/solrj/src/java/org/eclipse/jetty/client/AuthenticationProtocolHandler.java
new file mode 100644
index 0000000..f998944
--- /dev/null
+++ b/solr/solrj/src/java/org/eclipse/jetty/client/AuthenticationProtocolHandler.java
@@ -0,0 +1,314 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ *     http://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 org.eclipse.jetty.client;
+
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.eclipse.jetty.client.api.Authentication;
+import org.eclipse.jetty.client.api.Authentication.HeaderInfo;
+import org.eclipse.jetty.client.api.Connection;
+import org.eclipse.jetty.client.api.ContentProvider;
+import org.eclipse.jetty.client.api.ContentResponse;
+import org.eclipse.jetty.client.api.Request;
+import org.eclipse.jetty.client.api.Response;
+import org.eclipse.jetty.client.api.Result;
+import org.eclipse.jetty.client.util.BufferingResponseListener;
+import org.eclipse.jetty.http.HttpField;
+import org.eclipse.jetty.http.HttpHeader;
+import org.eclipse.jetty.http.QuotedCSV;
+import org.eclipse.jetty.util.log.Log;
+import org.eclipse.jetty.util.log.Logger;
+
+public abstract class AuthenticationProtocolHandler implements ProtocolHandler
+{
+  public static final int DEFAULT_MAX_CONTENT_LENGTH = 16*1024;
+  public static final Logger LOG = Log.getLogger(AuthenticationProtocolHandler.class);
+  private final HttpClient client;
+  private final int maxContentLength;
+  private final ResponseNotifier notifier;
+
+  private static final Pattern CHALLENGE_PATTERN = Pattern.compile("(?<schemeOnly>[!#$%&'*+\\-.^_`|~0-9A-Za-z]+)|(?:(?<scheme>[!#$%&'*+\\-.^_`|~0-9A-Za-z]+)\\s+)?(?:(?<token68>[a-zA-Z0-9\\-._~+/]+=*)|(?<paramName>[!#$%&'*+\\-.^_`|~0-9A-Za-z]+)\\s*=\\s*(?:(?<paramValue>.*)))");
+
+  protected AuthenticationProtocolHandler(HttpClient client, int maxContentLength)
+  {
+    this.client = client;
+    this.maxContentLength = maxContentLength;
+    this.notifier = new ResponseNotifier();
+  }
+
+  protected HttpClient getHttpClient()
+  {
+    return client;
+  }
+
+  protected abstract HttpHeader getAuthenticateHeader();
+
+  protected abstract HttpHeader getAuthorizationHeader();
+
+  protected abstract URI getAuthenticationURI(Request request);
+
+  protected abstract String getAuthenticationAttribute();
+
+  @Override
+  public Response.Listener getResponseListener()
+  {
+    // Return new instances every time to keep track of the response content
+    return new AuthenticationListener();
+  }
+
+
+  protected List<HeaderInfo> getHeaderInfo(String header) throws IllegalArgumentException
+  {
+    List<HeaderInfo> headerInfos = new ArrayList<>();
+    Matcher m;
+
+    for(String value : new QuotedCSV(true, header))
+    {
+      m = CHALLENGE_PATTERN.matcher(value);
+      if (m.matches())
+      {
+        if(m.group("schemeOnly") != null)
+        {
+          headerInfos.add(new HeaderInfo(getAuthorizationHeader(), m.group(1), new HashMap<>()));
+          continue;
+        }
+
+        if (m.group("scheme") != null)
+        {
+          headerInfos.add(new HeaderInfo(getAuthorizationHeader(), m.group("scheme"), new HashMap<>()));
+        }
+
+        if (headerInfos.isEmpty())
+          throw new IllegalArgumentException("Parameters without auth-scheme");
+
+        Map<String, String> authParams = headerInfos.get(headerInfos.size() - 1).getParameters();
+        if (m.group("paramName") != null)
+        {
+          String paramVal = QuotedCSV.unquote(m.group("paramValue"));
+          authParams.put(m.group("paramName"), paramVal);
+        }
+        else if (m.group("token68") != null)
+        {
+          if (!authParams.isEmpty())
+            throw new IllegalArgumentException("token68 after auth-params");
+
+          authParams.put("base64", m.group("token68"));
+        }
+      }
+    }
+
+    return headerInfos;
+  }
+
+  private class AuthenticationListener extends BufferingResponseListener
+  {
+    private AuthenticationListener()
+    {
+      super(maxContentLength);
+    }
+
+    @Override
+    public void onComplete(Result result)
+    {
+      HttpRequest request = (HttpRequest)result.getRequest();
+      ContentResponse response = new HttpContentResponse(result.getResponse(), getContent(), getMediaType(), getEncoding());
+      if (result.getResponseFailure() != null)
+      {
+        if (LOG.isDebugEnabled())
+          LOG.debug("Authentication challenge failed {}", result.getFailure());
+        forwardFailureComplete(request, result.getRequestFailure(), response, result.getResponseFailure());
+        return;
+      }
+
+      String authenticationAttribute = getAuthenticationAttribute();
+      HttpConversation conversation = request.getConversation();
+      if (conversation.getAttribute(authenticationAttribute) != null)
+      {
+        // We have already tried to authenticate, but we failed again.
+        if (LOG.isDebugEnabled())
+          LOG.debug("Bad credentials for {}", request);
+        forwardSuccessComplete(request, response);
+        return;
+      }
+
+      HttpHeader header = getAuthenticateHeader();
+      List<Authentication.HeaderInfo> headerInfos = parseAuthenticateHeader(response, header);
+      if (headerInfos.isEmpty())
+      {
+        if (LOG.isDebugEnabled())
+          LOG.debug("Authentication challenge without {} header", header);
+        forwardFailureComplete(request, result.getRequestFailure(), response, new HttpResponseException("HTTP protocol violation: Authentication challenge without " + header + " header", response));
+        return;
+      }
+
+      Authentication authentication = null;
+      Authentication.HeaderInfo headerInfo = null;
+      URI authURI = resolveURI(request, getAuthenticationURI(request));
+      if (authURI != null)
+      {
+        for (Authentication.HeaderInfo element : headerInfos)
+        {
+          authentication = client.getAuthenticationStore().findAuthentication(element.getType(), authURI, element.getRealm());
+          if (authentication != null)
+          {
+            headerInfo = element;
+            break;
+          }
+        }
+      }
+      if (authentication == null)
+      {
+        if (LOG.isDebugEnabled())
+          LOG.debug("No authentication available for {}", request);
+        forwardSuccessComplete(request, response);
+        return;
+      }
+
+      ContentProvider requestContent = request.getContent();
+      if (requestContent != null && !requestContent.isReproducible())
+      {
+        if (LOG.isDebugEnabled())
+          LOG.debug("Request content not reproducible for {}", request);
+        forwardSuccessComplete(request, response);
+        return;
+      }
+
+      try
+      {
+        Authentication.Result authnResult = authentication.authenticate(request, response, headerInfo, conversation);
+        if (LOG.isDebugEnabled())
+          LOG.debug("Authentication result {}", authnResult);
+        if (authnResult == null)
+        {
+          forwardSuccessComplete(request, response);
+          return;
+        }
+
+        conversation.setAttribute(authenticationAttribute, true);
+
+        URI requestURI = request.getURI();
+        String path = null;
+        if (requestURI == null)
+        {
+          requestURI = resolveURI(request, null);
+          path = request.getPath();
+        }
+        Request newRequest = client.copyRequest(request, requestURI);
+        if (path != null)
+          newRequest.path(path);
+
+        authnResult.apply(newRequest);
+        // Copy existing, explicitly set, authorization headers.
+        copyIfAbsent(request, newRequest, HttpHeader.AUTHORIZATION);
+        copyIfAbsent(request, newRequest, HttpHeader.PROXY_AUTHORIZATION);
+
+        AfterAuthenticationListener listener = new AfterAuthenticationListener(authnResult);
+        Connection connection = (Connection)request.getAttributes().get(Connection.class.getName());
+        if (connection != null)
+          connection.send(newRequest, listener);
+        else
+          newRequest.send(listener);
+      }
+      catch (Throwable x)
+      {
+        if (LOG.isDebugEnabled())
+          LOG.debug("Authentication failed", x);
+        forwardFailureComplete(request, null, response, x);
+      }
+    }
+
+    private URI resolveURI(HttpRequest request, URI uri)
+    {
+      if (uri != null)
+        return uri;
+      String target = request.getScheme() + "://" + request.getHost();
+      int port = request.getPort();
+      if (port > 0)
+        target += ":" + port;
+      return URI.create(target);
+    }
+
+    private void copyIfAbsent(HttpRequest oldRequest, Request newRequest, HttpHeader header)
+    {
+      HttpField field = oldRequest.getHeaders().getField(header);
+      if (field != null && !newRequest.getHeaders().contains(header))
+        newRequest.getHeaders().put(field);
+    }
+
+    private void forwardSuccessComplete(HttpRequest request, Response response)
+    {
+      HttpConversation conversation = request.getConversation();
+      conversation.updateResponseListeners(null);
+      notifier.forwardSuccessComplete(conversation.getResponseListeners(), request, response);
+    }
+
+    private void forwardFailureComplete(HttpRequest request, Throwable requestFailure, Response response, Throwable responseFailure)
+    {
+      HttpConversation conversation = request.getConversation();
+      conversation.updateResponseListeners(null);
+      List<Response.ResponseListener> responseListeners = conversation.getResponseListeners();
+      if (responseFailure == null)
+        notifier.forwardSuccess(responseListeners, response);
+      else
+        notifier.forwardFailure(responseListeners, response, responseFailure);
+      notifier.notifyComplete(responseListeners, new Result(request, requestFailure, response, responseFailure));
+    }
+
+    private List<Authentication.HeaderInfo> parseAuthenticateHeader(Response response, HttpHeader header)
+    {
+      // TODO: these should be ordered by strength
+      List<Authentication.HeaderInfo> result = new ArrayList<>();
+      List<String> values = response.getHeaders().getValuesList(header);
+      for (String value : values)
+      {
+        try
+        {
+          result.addAll(getHeaderInfo(value));
+        }
+        catch(IllegalArgumentException e)
+        {
+          if (LOG.isDebugEnabled())
+            LOG.debug("Failed to parse authentication header", e);
+        }
+      }
+      return result;
+    }
+  }
+
+  private class AfterAuthenticationListener extends Response.Listener.Adapter
+  {
+    private final Authentication.Result authenticationResult;
+
+    private AfterAuthenticationListener(Authentication.Result authenticationResult)
+    {
+      this.authenticationResult = authenticationResult;
+    }
+
+    @Override
+    public void onSuccess(Response response)
+    {
+      client.getAuthenticationStore().addAuthenticationResult(authenticationResult);
+    }
+  }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/lucene-solr/blob/7ca1dad3/solr/solrj/src/java/org/eclipse/jetty/client/SPNEGOAuthentication.java
----------------------------------------------------------------------
diff --git a/solr/solrj/src/java/org/eclipse/jetty/client/SPNEGOAuthentication.java b/solr/solrj/src/java/org/eclipse/jetty/client/SPNEGOAuthentication.java
new file mode 100644
index 0000000..1afc43b
--- /dev/null
+++ b/solr/solrj/src/java/org/eclipse/jetty/client/SPNEGOAuthentication.java
@@ -0,0 +1,380 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ *     http://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 org.eclipse.jetty.client;
+
+import java.io.IOException;
+import java.net.URI;
+import java.nio.file.Path;
+import java.security.PrivilegedAction;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.PasswordCallback;
+import javax.security.auth.login.AppConfigurationEntry;
+import javax.security.auth.login.Configuration;
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
+
+import org.eclipse.jetty.client.api.AuthenticationStore;
+import org.eclipse.jetty.client.api.ContentResponse;
+import org.eclipse.jetty.client.api.Request;
+import org.eclipse.jetty.client.util.AbstractAuthentication;
+import org.eclipse.jetty.http.HttpHeader;
+import org.eclipse.jetty.util.Attributes;
+import org.eclipse.jetty.util.log.Log;
+import org.eclipse.jetty.util.log.Logger;
+import org.ietf.jgss.GSSContext;
+import org.ietf.jgss.GSSException;
+import org.ietf.jgss.GSSManager;
+import org.ietf.jgss.GSSName;
+import org.ietf.jgss.Oid;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+/**
+ * <p>Implementation of the SPNEGO (or "Negotiate") authentication defined in RFC 4559.</p>
+ * <p>A {@link #getUserName() user} is logged in via JAAS (either via userName/password or
+ * via userName/keyTab) once only.</p>
+ * <p>For every request that needs authentication, a {@link GSSContext} is initiated and
+ * later established after reading the response from the server.</p>
+ * <p>Applications should create objects of this class and add them to the
+ * {@link AuthenticationStore} retrieved from the {@link HttpClient}
+ * via {@link HttpClient#getAuthenticationStore()}.</p>
+ */
+public class SPNEGOAuthentication extends AbstractAuthentication
+{
+  private static final Logger LOG = Log.getLogger(SPNEGOAuthentication.class);
+  private static final String NEGOTIATE = HttpHeader.NEGOTIATE.asString();
+
+  private final GSSManager gssManager = GSSManager.getInstance();
+  private String userName;
+  private String userPassword;
+  private Path userKeyTabPath;
+  private String serviceName;
+  private boolean useTicketCache;
+  private Path ticketCachePath;
+  private boolean renewTGT;
+
+  public SPNEGOAuthentication(URI uri)
+  {
+    super(uri, ANY_REALM);
+  }
+
+  @Override
+  public String getType()
+  {
+    return NEGOTIATE;
+  }
+
+  /**
+   * @return the user name of the user to login
+   */
+  public String getUserName()
+  {
+    return userName;
+  }
+
+  /**
+   * @param userName user name of the user to login
+   */
+  public void setUserName(String userName)
+  {
+    this.userName = userName;
+  }
+
+  /**
+   * @return the password of the user to login
+   */
+  public String getUserPassword()
+  {
+    return userPassword;
+  }
+
+  /**
+   * @param userPassword the password of the user to login
+   * @see #setUserKeyTabPath(Path)
+   */
+  public void setUserPassword(String userPassword)
+  {
+    this.userPassword = userPassword;
+  }
+
+  /**
+   * @return the path of the keyTab file with the user credentials
+   */
+  public Path getUserKeyTabPath()
+  {
+    return userKeyTabPath;
+  }
+
+  /**
+   * @param userKeyTabPath the path of the keyTab file with the user credentials
+   * @see #setUserPassword(String)
+   */
+  public void setUserKeyTabPath(Path userKeyTabPath)
+  {
+    this.userKeyTabPath = userKeyTabPath;
+  }
+
+  /**
+   * @return the name of the service to use
+   */
+  public String getServiceName()
+  {
+    return serviceName;
+  }
+
+  /**
+   * @param serviceName the name of the service to use
+   */
+  public void setServiceName(String serviceName)
+  {
+    this.serviceName = serviceName;
+  }
+
+  /**
+   * @return whether to use the ticket cache during login
+   */
+  public boolean isUseTicketCache()
+  {
+    return useTicketCache;
+  }
+
+  /**
+   * @param useTicketCache whether to use the ticket cache during login
+   * @see #setTicketCachePath(Path)
+   */
+  public void setUseTicketCache(boolean useTicketCache)
+  {
+    this.useTicketCache = useTicketCache;
+  }
+
+  /**
+   * @return the path of the ticket cache file
+   */
+  public Path getTicketCachePath()
+  {
+    return ticketCachePath;
+  }
+
+  /**
+   * @param ticketCachePath the path of the ticket cache file
+   * @see #setUseTicketCache(boolean)
+   */
+  public void setTicketCachePath(Path ticketCachePath)
+  {
+    this.ticketCachePath = ticketCachePath;
+  }
+
+  /**
+   * @return whether to renew the ticket granting ticket
+   */
+  public boolean isRenewTGT()
+  {
+    return renewTGT;
+  }
+
+  /**
+   * @param renewTGT whether to renew the ticket granting ticket
+   */
+  public void setRenewTGT(boolean renewTGT)
+  {
+    this.renewTGT = renewTGT;
+  }
+
+  @Override
+  public Result authenticate(Request request, ContentResponse response, HeaderInfo headerInfo, Attributes context)
+  {
+    SPNEGOContext spnegoContext = (SPNEGOContext)context.getAttribute(SPNEGOContext.ATTRIBUTE);
+    if (LOG.isDebugEnabled())
+      LOG.debug("Authenticate with context {}", spnegoContext);
+    if (spnegoContext == null)
+    {
+      spnegoContext = login();
+      context.setAttribute(SPNEGOContext.ATTRIBUTE, spnegoContext);
+    }
+
+    String b64Input = headerInfo.getBase64();
+    byte[] input = b64Input == null ? new byte[0] : Base64.getDecoder().decode(b64Input);
+    byte[] output = Subject.doAs(spnegoContext.subject, initGSSContext(spnegoContext, request.getHost(), input));
+    String b64Output = output == null ? null : new String(Base64.getEncoder().encode(output), UTF_8);
+
+    // The result cannot be used for subsequent requests,
+    // so it always has a null URI to avoid being cached.
+    return new SPNEGOResult(null, b64Output);
+  }
+
+  private SPNEGOContext login()
+  {
+    try
+    {
+      // First login via JAAS using the Kerberos AS_REQ call, with a client user.
+      // This will populate the Subject with the client user principal and the TGT.
+      String user = getUserName();
+      if (LOG.isDebugEnabled())
+        LOG.debug("Logging in user {}", user);
+      CallbackHandler callbackHandler = new PasswordCallbackHandler();
+      LoginContext loginContext = new LoginContext("", null, callbackHandler, new SPNEGOConfiguration());
+      loginContext.login();
+      Subject subject = loginContext.getSubject();
+
+      SPNEGOContext spnegoContext = new SPNEGOContext();
+      spnegoContext.subject = subject;
+      if (LOG.isDebugEnabled())
+        LOG.debug("Initialized {}", spnegoContext);
+      return spnegoContext;
+    }
+    catch (LoginException x)
+    {
+      throw new RuntimeException(x);
+    }
+  }
+
+  private PrivilegedAction<byte[]> initGSSContext(SPNEGOContext spnegoContext, String host, byte[] bytes)
+  {
+    return () ->
+    {
+      try
+      {
+        // The call to initSecContext with the service name will
+        // trigger the Kerberos TGS_REQ call, asking for the SGT,
+        // which will be added to the Subject credentials because
+        // initSecContext() is called from within Subject.doAs().
+        GSSContext gssContext = spnegoContext.gssContext;
+        if (gssContext == null)
+        {
+          String principal = getServiceName() + "@" + host;
+          GSSName serviceName = gssManager.createName(principal, GSSName.NT_HOSTBASED_SERVICE);
+          Oid spnegoOid = new Oid("1.3.6.1.5.5.2");
+          gssContext = gssManager.createContext(serviceName, spnegoOid, null, GSSContext.INDEFINITE_LIFETIME);
+          spnegoContext.gssContext = gssContext;
+          gssContext.requestMutualAuth(true);
+        }
+        byte[] result = gssContext.initSecContext(bytes, 0, bytes.length);
+        if (LOG.isDebugEnabled())
+          LOG.debug("{} {}", gssContext.isEstablished() ? "Initialized" : "Initializing", gssContext);
+        return result;
+      }
+      catch (GSSException x)
+      {
+        throw new RuntimeException(x);
+      }
+    };
+  }
+
+  public static class SPNEGOResult implements Result
+  {
+    private final URI uri;
+    private final HttpHeader header;
+    private final String value;
+
+    public SPNEGOResult(URI uri, String token)
+    {
+      this(uri, HttpHeader.AUTHORIZATION, token);
+    }
+
+    public SPNEGOResult(URI uri, HttpHeader header, String token)
+    {
+      this.uri = uri;
+      this.header = header;
+      this.value = NEGOTIATE + (token == null ? "" : " " + token);
+    }
+
+    @Override
+    public URI getURI()
+    {
+      return uri;
+    }
+
+    @Override
+    public void apply(Request request)
+    {
+      request.header(header, value);
+    }
+  }
+
+  private static class SPNEGOContext
+  {
+    private static final String ATTRIBUTE = SPNEGOContext.class.getName();
+
+    private Subject subject;
+    private GSSContext gssContext;
+
+    @Override
+    public String toString()
+    {
+      return String.format(Locale.ROOT, "%s@%x[context=%s]", getClass().getSimpleName(), hashCode(), gssContext);
+    }
+  }
+
+  private class PasswordCallbackHandler implements CallbackHandler
+  {
+    @Override
+    public void handle(Callback[] callbacks) throws IOException
+    {
+      PasswordCallback callback = Arrays.stream(callbacks)
+          .filter(PasswordCallback.class::isInstance)
+          .map(PasswordCallback.class::cast)
+          .findAny()
+          .filter(c -> c.getPrompt().contains(getUserName()))
+          .orElseThrow(IOException::new);
+      callback.setPassword(getUserPassword().toCharArray());
+    }
+  }
+
+  private class SPNEGOConfiguration extends Configuration
+  {
+    @Override
+    public AppConfigurationEntry[] getAppConfigurationEntry(String name)
+    {
+      Map<String, Object> options = new HashMap<>();
+      if (LOG.isDebugEnabled())
+        options.put("debug", "true");
+      options.put("refreshKrb5Config", "true");
+      options.put("principal", getUserName());
+      options.put("isInitiator", "true");
+      Path keyTabPath = getUserKeyTabPath();
+      if (keyTabPath != null)
+      {
+        options.put("doNotPrompt", "true");
+        options.put("useKeyTab", "true");
+        options.put("keyTab", keyTabPath.toAbsolutePath().toString());
+        options.put("storeKey", "true");
+      }
+      boolean useTicketCache = isUseTicketCache();
+      if (useTicketCache)
+      {
+        options.put("useTicketCache", "true");
+        Path ticketCachePath = getTicketCachePath();
+        if (ticketCachePath != null)
+          options.put("ticketCache", ticketCachePath.toAbsolutePath().toString());
+        options.put("renewTGT", String.valueOf(isRenewTGT()));
+      }
+
+      String moduleClass = "com.sun.security.auth.module.Krb5LoginModule";
+      AppConfigurationEntry config = new AppConfigurationEntry(moduleClass, AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
+      return new AppConfigurationEntry[]{config};
+    }
+  }
+}