code: public static GSSContext authenticateClient(final Socket socket, Subject subject, final String servicePrincipalName) {
      return Subject.doAs(subject, new PrivilegedAction<GSSContext>() {
        public GSSContext run() {
          try {
            GSSManager manager = GSSManager.getInstance();
            GSSName peerName = manager.createName(servicePrincipalName, GSSName.NT_HOSTBASED_SERVICE);
            GSSContext context = manager.createContext(peerName, null, null, GSSContext.DEFAULT_LIFETIME);
  
            // Loop while the context is still not established
            while (!context.isEstablished()) {
              context.initSecContext(socket.getInputStream(), socket.getOutputStream());
            }
  
            return context;
          } catch (Exception e) {
            log.error("Unable to authenticate client against Kerberos", e);
            return null;
          }
        }
      });
    }
docs: Authenticate client to use this service and return secure context
  
  @param socket
  The socket used for communication
  @param subject
  The Kerberos service subject
  @param servicePrincipalName
  Service principal name
  
  @return context if authorized or null