org.apache.http.impl.auth.SPNegoSchemeFactory源码实例Demo

org.apache.http.impl.client.SystemDefaultHttpClient#org.apache.http.impl.auth.SPNegoSchemeFactory源码实例Demo

下面列出了org.apache.http.impl.client.SystemDefaultHttpClient#org.apache.http.impl.auth.SPNegoSchemeFactory 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hadoop   文件: AuthenticatorTestCase.java
private SystemDefaultHttpClient getHttpClient() {
  final SystemDefaultHttpClient httpClient = new SystemDefaultHttpClient();
  httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory(true));
   Credentials use_jaas_creds = new Credentials() {
     public String getPassword() {
       return null;
     }

     public Principal getUserPrincipal() {
       return null;
     }
   };

   httpClient.getCredentialsProvider().setCredentials(
     AuthScope.ANY, use_jaas_creds);
   return httpClient;
}
 
源代码2 项目: big-c   文件: AuthenticatorTestCase.java
private SystemDefaultHttpClient getHttpClient() {
  final SystemDefaultHttpClient httpClient = new SystemDefaultHttpClient();
  httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory(true));
   Credentials use_jaas_creds = new Credentials() {
     public String getPassword() {
       return null;
     }

     public Principal getUserPrincipal() {
       return null;
     }
   };

   httpClient.getCredentialsProvider().setCredentials(
     AuthScope.ANY, use_jaas_creds);
   return httpClient;
}
 
源代码3 项目: registry   文件: AuthenticatorTestCase.java
private SystemDefaultHttpClient getHttpClient() {
    final SystemDefaultHttpClient httpClient = new SystemDefaultHttpClient();
    httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory(true));
    Credentials use_jaas_creds = new Credentials() {
        public String getPassword() {
            return null;
        }

        public Principal getUserPrincipal() {
            return null;
        }
    };

    httpClient.getCredentialsProvider().setCredentials(
            AuthScope.ANY, use_jaas_creds);
    return httpClient;
}
 
protected final CloseableHttpClient getHttpClient(final boolean useSpnego) throws Exception {

        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        final HttpClientBuilder hcb = HttpClients.custom();

        if (useSpnego) {
            //SPNEGO/Kerberos setup
            log.debug("SPNEGO activated");
            final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true);//  new NegotiateSchemeProvider();
            final Credentials jaasCreds = new JaasCredentials();
            credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds);
            credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM), new NTCredentials("Guest", "Guest", "Guest",
                    "Guest"));
            final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
                    .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build();

            hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry);
        }

        hcb.setDefaultCredentialsProvider(credsProvider);
        hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(10 * 1000).build());
        final CloseableHttpClient httpClient = hcb.build();
        return httpClient;
    }
 
源代码5 项目: hbase   文件: TestInfoServersACL.java
private CloseableHttpClient createHttpClient(String clientPrincipal) throws Exception {
  // Logs in with Kerberos via GSS
  GSSManager gssManager = GSSManager.getInstance();
  // jGSS Kerberos login constant
  Oid oid = new Oid("1.2.840.113554.1.2.2");
  GSSName gssClient = gssManager.createName(clientPrincipal, GSSName.NT_USER_NAME);
  GSSCredential credential = gssManager.createCredential(
      gssClient, GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);

  Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
      .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build();

  BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));

  return HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry)
      .setDefaultCredentialsProvider(credentialsProvider).build();
}
 
源代码6 项目: hbase   文件: TestSecureRESTServer.java
private Pair<CloseableHttpClient,HttpClientContext> getClient() {
  HttpClientConnectionManager pool = new PoolingHttpClientConnectionManager();
  HttpHost host = new HttpHost("localhost", REST_TEST.getServletPort());
  Registry<AuthSchemeProvider> authRegistry =
      RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO,
          new SPNegoSchemeFactory(true, true)).build();
  CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(AuthScope.ANY, EmptyCredentials.INSTANCE);
  AuthCache authCache = new BasicAuthCache();

  CloseableHttpClient client = HttpClients.custom()
      .setDefaultAuthSchemeRegistry(authRegistry)
      .setConnectionManager(pool).build();

  HttpClientContext context = HttpClientContext.create();
  context.setTargetHost(host);
  context.setCredentialsProvider(credentialsProvider);
  context.setAuthSchemeRegistry(authRegistry);
  context.setAuthCache(authCache);

  return new Pair<>(client, context);
}
 
源代码7 项目: davmail   文件: HttpClientAdapter.java
private Registry<AuthSchemeProvider> getAuthSchemeRegistry() {
    final RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.create();
    registryBuilder.register(AuthSchemes.NTLM, new JCIFSNTLMSchemeFactory())
            .register(AuthSchemes.BASIC, new BasicSchemeFactory())
            .register(AuthSchemes.DIGEST, new DigestSchemeFactory());
    if (Settings.getBooleanProperty("davmail.enableKerberos")) {
        registryBuilder.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
                .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory());
    }

    return registryBuilder.build();
}
 
源代码8 项目: nifi-swagger-client   文件: AccessApi.java
private HttpClient createSPNEGOHttpClient()  throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    Credentials jaasCredentials = new Credentials() {
        public String getPassword() {
            return null;
        }
        public Principal getUserPrincipal() {
            return null;
        }
    };
    credsProvider.setCredentials(new AuthScope(null, -1, null), jaasCredentials);
    Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create()
            .register(AuthSchemes.SPNEGO,new SPNegoSchemeFactory(true, false))
            .build();

    RequestConfig config = RequestConfig.custom().setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.SPNEGO, AuthSchemes.KERBEROS, AuthSchemes.NTLM)).build();

    HttpClientBuilder httpClientBuilder = HttpClients.custom()
            .setDefaultAuthSchemeRegistry(authSchemeRegistry)
            .setDefaultCredentialsProvider(credsProvider)
            .setDefaultRequestConfig(config);

    if (!this.apiClient.isVerifyingSsl()) {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true).build();
        HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
        httpClientBuilder = httpClientBuilder
                                .setSSLContext(sslContext)
                                .setSSLHostnameVerifier(hostnameVerifier);
    }

    return httpClientBuilder.build();
}
 
public void setGSSCredential(GSSCredential credential) {
  this.authRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO,
      new SPNegoSchemeFactory(STRIP_PORT_ON_SERVER_LOOKUP, USE_CANONICAL_HOSTNAME)).build();

  this.credentialsProvider = new BasicCredentialsProvider();
  if (null != credential) {
    // Non-null credential should be used directly with KerberosCredentials.
    // This is never set by the JDBC driver, nor the tests
    this.credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));
  } else {
    // A null credential implies that the user is logged in via JAAS using the
    // java.security.auth.login.config system property
    this.credentialsProvider.setCredentials(AuthScope.ANY, EmptyCredentials.INSTANCE);
  }
}
 
源代码10 项目: zeppelin   文件: YarnClient.java
private static HttpClient buildSpengoHttpClient() {
  HttpClientBuilder builder = HttpClientBuilder.create();
  Lookup<AuthSchemeProvider> authSchemeRegistry
      = RegistryBuilder.<AuthSchemeProvider>create().register(
          AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
  builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
  BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() {
    @Override
    public Principal getUserPrincipal() {
      return null;
    }

    @Override
    public String getPassword() {
      return null;
    }
  });
  builder.setDefaultCredentialsProvider(credentialsProvider);

  // Avoid output WARN: Cookie rejected
  RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES)
      .build();
  builder.setDefaultRequestConfig(globalConfig);

  CloseableHttpClient httpClient = builder.build();

  return httpClient;
}
 
源代码11 项目: nifi   文件: KerberosHttpClientBuilder.java
public SolrHttpClientBuilder getBuilder(SolrHttpClientBuilder builder) {

        //Enable only SPNEGO authentication scheme.

        builder.setAuthSchemeRegistryProvider(() -> {
            Lookup<AuthSchemeProvider> authProviders = RegistryBuilder.<AuthSchemeProvider>create()
                    .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, false))
                    .build();
            return authProviders;
        });
        // Get the credentials from the JAAS configuration rather than here
        Credentials useJaasCreds = new Credentials() {
            public String getPassword() {
                return null;
            }
            public Principal getUserPrincipal() {
                return null;
            }
        };

        HttpClientUtil.setCookiePolicy(SolrPortAwareCookieSpecFactory.POLICY_NAME);

        builder.setCookieSpecRegistryProvider(() -> {
            SolrPortAwareCookieSpecFactory cookieFactory = new SolrPortAwareCookieSpecFactory();

            Lookup<CookieSpecProvider> cookieRegistry = RegistryBuilder.<CookieSpecProvider> create()
                    .register(SolrPortAwareCookieSpecFactory.POLICY_NAME, cookieFactory).build();

            return cookieRegistry;
        });

        builder.setDefaultCredentialsProvider(() -> {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, useJaasCreds);
            return credentialsProvider;
        });
        HttpClientUtil.addRequestInterceptor(bufferedEntityInterceptor);
        return builder;
    }
 
源代码12 项目: pentaho-kettle   文件: SessionConfigurator.java
private Header spnegoAuthenticate( boolean stripPort, URI uri ) throws Exception {
  SPNegoSchemeFactory spNegoSchemeFactory = new SPNegoSchemeFactory( stripPort );
  // using newInstance method instead of create method to be compatible httpclient library from 4.2 to 4.5
  // the create method was introduced at version 4.3
  SPNegoScheme spNegoScheme = (SPNegoScheme) spNegoSchemeFactory.newInstance( null );
  spNegoScheme.processChallenge( AUTHENTICATE_HEADER );
  return spNegoScheme.authenticate( credentials, new HttpGet( "" ), getContext( uri ) );
}
 
源代码13 项目: cyberduck   文件: HttpConnectionPoolBuilder.java
/**
 * @param proxy    Proxy configuration
 * @param listener Log listener
 * @param prompt   Prompt for proxy credentials
 * @return Builder for HTTP client
 */
public HttpClientBuilder build(final Proxy proxy, final TranscriptListener listener, final LoginCallback prompt) {
    final HttpClientBuilder configuration = HttpClients.custom();
    // Use HTTP Connect proxy implementation provided here instead of
    // relying on internal proxy support in socket factory
    switch(proxy.getType()) {
        case HTTP:
        case HTTPS:
            final HttpHost h = new HttpHost(proxy.getHostname(), proxy.getPort(), Scheme.http.name());
            if(log.isInfoEnabled()) {
                log.info(String.format("Setup proxy %s", h));
            }
            configuration.setProxy(h);
            configuration.setProxyAuthenticationStrategy(new CallbackProxyAuthenticationStrategy(ProxyCredentialsStoreFactory.get(), host, prompt));
            break;
    }
    configuration.setUserAgent(new PreferencesUseragentProvider().get());
    final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000;
    configuration.setDefaultSocketConfig(SocketConfig.custom()
        .setTcpNoDelay(true)
        .setSoTimeout(timeout)
        .build());
    configuration.setDefaultRequestConfig(this.createRequestConfig(timeout));
    configuration.setDefaultConnectionConfig(ConnectionConfig.custom()
        .setBufferSize(preferences.getInteger("http.socket.buffer"))
        .setCharset(Charset.forName(host.getEncoding()))
        .build());
    if(preferences.getBoolean("http.connections.reuse")) {
        configuration.setConnectionReuseStrategy(new DefaultClientConnectionReuseStrategy());
    }
    else {
        configuration.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
    }
    configuration.setRetryHandler(new ExtendedHttpRequestRetryHandler(preferences.getInteger("http.connections.retry")));
    configuration.setServiceUnavailableRetryStrategy(new DisabledServiceUnavailableRetryStrategy());
    if(!preferences.getBoolean("http.compression.enable")) {
        configuration.disableContentCompression();
    }
    configuration.setRequestExecutor(new LoggingHttpRequestExecutor(listener));
    // Always register HTTP for possible use with proxy. Contains a number of protocol properties such as the
    // default port and the socket factory to be used to create the java.net.Socket instances for the given protocol
    configuration.setConnectionManager(this.createConnectionManager(this.createRegistry()));
    configuration.setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create()
        .register(AuthSchemes.BASIC, new BasicSchemeFactory(
            Charset.forName(preferences.getProperty("http.credentials.charset"))))
        .register(AuthSchemes.DIGEST, new DigestSchemeFactory(
            Charset.forName(preferences.getProperty("http.credentials.charset"))))
        .register(AuthSchemes.NTLM, preferences.getBoolean("webdav.ntlm.windows.authentication.enable") && WinHttpClients.isWinAuthAvailable() ?
            new BackportWindowsNTLMSchemeFactory(null) :
            new NTLMSchemeFactory())
        .register(AuthSchemes.SPNEGO, preferences.getBoolean("webdav.ntlm.windows.authentication.enable") && WinHttpClients.isWinAuthAvailable() ?
            new BackportWindowsNegotiateSchemeFactory(null) :
            new SPNegoSchemeFactory())
        .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build());
    return configuration;
}
 
源代码14 项目: lucene-solr   文件: Krb5HttpClientBuilder.java
public SolrHttpClientBuilder getBuilder(SolrHttpClientBuilder builder) {
  if (System.getProperty(LOGIN_CONFIG_PROP) != null) {
    String configValue = System.getProperty(LOGIN_CONFIG_PROP);

    if (configValue != null) {
      log.info("Setting up SPNego auth with config: {}", configValue);
      final String useSubjectCredsProp = "javax.security.auth.useSubjectCredsOnly";
      String useSubjectCredsVal = System.getProperty(useSubjectCredsProp);

      // "javax.security.auth.useSubjectCredsOnly" should be false so that the underlying
      // authentication mechanism can load the credentials from the JAAS configuration.
      if (useSubjectCredsVal == null) {
        System.setProperty(useSubjectCredsProp, "false");
      } else if (!useSubjectCredsVal.toLowerCase(Locale.ROOT).equals("false")) {
        // Don't overwrite the prop value if it's already been written to something else,
        // but log because it is likely the Credentials won't be loaded correctly.
        log.warn("System Property: {} set to: {} not false.  SPNego authentication may not be successful."
            , useSubjectCredsProp, useSubjectCredsVal);
      }

      javax.security.auth.login.Configuration.setConfiguration(jaasConfig);
      //Enable only SPNEGO authentication scheme.

      builder.setAuthSchemeRegistryProvider(() -> {
        Lookup<AuthSchemeProvider> authProviders = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, false))
            .build();
        return authProviders;
      });
      // Get the credentials from the JAAS configuration rather than here
      Credentials useJaasCreds = new Credentials() {
        public String getPassword() {
          return null;
        }
        public Principal getUserPrincipal() {
          return null;
        }
      };

      HttpClientUtil.setCookiePolicy(SolrPortAwareCookieSpecFactory.POLICY_NAME);

      builder.setCookieSpecRegistryProvider(() -> {
        SolrPortAwareCookieSpecFactory cookieFactory = new SolrPortAwareCookieSpecFactory();

        Lookup<CookieSpecProvider> cookieRegistry = RegistryBuilder.<CookieSpecProvider> create()
            .register(SolrPortAwareCookieSpecFactory.POLICY_NAME, cookieFactory).build();

        return cookieRegistry;
      });
      
      builder.setDefaultCredentialsProvider(() -> {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, useJaasCreds);
        return credentialsProvider;
      });
      HttpClientUtil.addRequestInterceptor(bufferedEntityInterceptor);
    }
  } else {
    log.warn("{} is configured without specifying system property '{}'",
        getClass().getName(), LOGIN_CONFIG_PROP);
  }

  return builder;
}
 
public void configure(DefaultHttpClient httpClient, SolrParams config) {
  super.configure(httpClient, config);
  if (System.getProperty(LOGIN_CONFIG_PROP) != null) {
    String configValue = System.getProperty(LOGIN_CONFIG_PROP);
    if (configValue != null) {
      logger.debug("Setting up kerberos auth with config: " + configValue);
      System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

      if (fusionPrincipal != null) {
        Subject subject = new Subject(false, Sets.newHashSet(new KerberosPrincipal(fusionPrincipal)),
            Collections.emptySet(), Collections.emptySet());
        LoginContext loginContext;
        try {
          loginContext = new LoginContext("", subject, null, jaasConfig);
          loginContext.login();
          logger.debug("Successful Fusion Login with principal: " + fusionPrincipal);
        } catch (LoginException e) {
          String errorMessage = "Unsuccessful Fusion Login with principal: " + fusionPrincipal;
          logger.error(errorMessage, e);
          throw new RuntimeException(errorMessage, e);
        }
      }

      Configuration.setConfiguration(jaasConfig);
      httpClient.getAuthSchemes().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, false));
      Credentials useJaasCreds = new Credentials() {
        public String getPassword() {
          return null;
        }

        public Principal getUserPrincipal() {
          return null;
        }
      };
      httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, useJaasCreds);
      httpClient.addRequestInterceptor(this.bufferedEntityInterceptor);
    } else {
      httpClient.getCredentialsProvider().clear();
    }
  }
}
 
源代码16 项目: datacollector   文件: SdcSolrHttpClientBuilder.java
static SolrHttpClientBuilder create() {
  SolrHttpClientBuilder solrHttpClientBuilder = SolrHttpClientBuilder.create();

  final String useSubjectCredentialsProperty = USE_SUBJECT_CREDENTIALS_PROPERTY;
  String useSubjectCredentialsValue = System.getProperty(useSubjectCredentialsProperty);

  if (useSubjectCredentialsValue == null) {
    System.setProperty(useSubjectCredentialsProperty, FALSE);
  } else if (!useSubjectCredentialsValue.toLowerCase(Locale.ROOT).equals(FALSE)) {
    LOG.warn(String.format(
        "System Property: %s set to: %s not false. SPNego authentication may not be successful.",
        useSubjectCredentialsProperty,
        useSubjectCredentialsValue
    ));
  }

  solrHttpClientBuilder.setAuthSchemeRegistryProvider(() -> RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO,
      new SPNegoSchemeFactory(true)
  ).build());

  SolrPortAwareCookieSpecFactory cookieFactory = new SolrPortAwareCookieSpecFactory();
  solrHttpClientBuilder.setCookieSpecRegistryProvider(() -> RegistryBuilder.<CookieSpecProvider>create().register(SolrPortAwareCookieSpecFactory.POLICY_NAME,
      cookieFactory
  ).build());

  Credentials jassCredentials = new Credentials() {
    public String getPassword() {
      return null;
    }

    public Principal getUserPrincipal() {
      return null;
    }
  };

  CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(AuthScope.ANY, jassCredentials);
  solrHttpClientBuilder.setDefaultCredentialsProvider(() -> credentialsProvider);

  return solrHttpClientBuilder;
}
 
public void configure(DefaultHttpClient httpClient, SolrParams config) {
  super.configure(httpClient, config);

  // Begin change for SDC-2962
  // Instead of checking existence of JAAS file, do the following if solr kerberos is enabled
  //if (System.getProperty(LOGIN_CONFIG_PROP) != null) {
    //String configValue = System.getProperty(LOGIN_CONFIG_PROP);

    //if (configValue != null) {
     // logger.info("Setting up SPNego auth with config: " + configValue);
      final String useSubjectCredsProp = "javax.security.auth.useSubjectCredsOnly";
      String useSubjectCredsVal = System.getProperty(useSubjectCredsProp);

      // "javax.security.auth.useSubjectCredsOnly" should be false so that the underlying
      // authentication mechanism can load the credentials from the JAAS configuration.
      if (useSubjectCredsVal == null) {
        System.setProperty(useSubjectCredsProp, "false");
      }
      else if (!useSubjectCredsVal.toLowerCase(Locale.ROOT).equals("false")) {
        // Don't overwrite the prop value if it's already been written to something else,
        // but log because it is likely the Credentials won't be loaded correctly.
        logger.warn("System Property: " + useSubjectCredsProp + " set to: " + useSubjectCredsVal
            + " not false.  SPNego authentication may not be successful.");
      }

      // Change for SDC-2962
      //javax.security.auth.login.Configuration.setConfiguration(jaasConfig);
      //Enable only SPNEGO authentication scheme.
      AuthSchemeRegistry registry = new AuthSchemeRegistry();
      registry.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, false));
      httpClient.setAuthSchemes(registry);
      // Get the credentials from the JAAS configuration rather than here
      Credentials useJaasCreds = new Credentials() {
        public String getPassword() {
          return null;
        }
        public Principal getUserPrincipal() {
          return null;
        }
      };

      SolrPortAwareCookieSpecFactory cookieFactory = new SolrPortAwareCookieSpecFactory();
      httpClient.getCookieSpecs().register(cookieFactory.POLICY_NAME, cookieFactory);
      httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, cookieFactory.POLICY_NAME);

      httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, useJaasCreds);

      httpClient.addRequestInterceptor(bufferedEntityInterceptor);
    //} else {
      //httpClient.getCredentialsProvider().clear();
    //}
 // }
}
 
public static boolean setSPNegoAuth(DefaultHttpClient httpClient) {
  // Begin change for SDC-2962
  // Instead of checking existence of JAAS file, do the following if solr kerberos is enabled
  //String configValue = System.getProperty("java.security.auth.login.config");
  //if(configValue != null) {
    //logger.info("Setting up SPNego auth with config: " + configValue);
  // End change for SDC-2962
    String useSubjectCredsProp = "javax.security.auth.useSubjectCredsOnly";
    String useSubjectCredsVal = System.getProperty("javax.security.auth.useSubjectCredsOnly");
    if(useSubjectCredsVal == null) {
      System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
    } else if(!useSubjectCredsVal.toLowerCase(Locale.ROOT).equals("false")) {
      logger.warn("System Property: javax.security.auth.useSubjectCredsOnly set to: " + useSubjectCredsVal + " not false.  SPNego authentication may not be successful.");
    }

    // Change for SDC-2962
    //Configuration.setConfiguration(jaasConf);

    // Change for SDC-8292
    //httpClient.getAuthSchemes().register("negotiate", new SPNegoSchemeFactory(true));
    //Enable only SPNEGO authentication scheme.
    AuthSchemeRegistry registry = new AuthSchemeRegistry();
    registry.register("Negotiate", new SPNegoSchemeFactory(true));
    httpClient.setAuthSchemes(registry);

    Credentials use_jaas_creds = new Credentials() {
      public String getPassword() {
        return null;
      }

      public Principal getUserPrincipal() {
        return null;
      }
    };
    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, use_jaas_creds);
    return true;
  /*} else {
    httpClient.getCredentialsProvider().clear();
    return false;
  }*/
}
 
源代码19 项目: hbase   文件: TestThriftSpnegoHttpFallbackServer.java
private CloseableHttpClient createHttpClient() throws Exception {
  final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(clientPrincipal, clientKeytab);
  final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
  // Make sure the subject has a principal
  assertFalse("Found no client principals in the clientSubject.",
    clientPrincipals.isEmpty());

  // Get a TGT for the subject (might have many, different encryption types). The first should
  // be the default encryption type.
  Set<KerberosTicket> privateCredentials =
    clientSubject.getPrivateCredentials(KerberosTicket.class);
  assertFalse("Found no private credentials in the clientSubject.",
    privateCredentials.isEmpty());
  KerberosTicket tgt = privateCredentials.iterator().next();
  assertNotNull("No kerberos ticket found.", tgt);

  // The name of the principal
  final String clientPrincipalName = clientPrincipals.iterator().next().getName();

  return Subject.doAs(clientSubject, (PrivilegedExceptionAction<CloseableHttpClient>) () -> {
    // Logs in with Kerberos via GSS
    GSSManager gssManager = GSSManager.getInstance();
    // jGSS Kerberos login constant
    Oid oid = new Oid("1.2.840.113554.1.2.2");
    GSSName gssClient = gssManager.createName(clientPrincipalName, GSSName.NT_USER_NAME);
    GSSCredential credential = gssManager.createCredential(gssClient,
      GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);

    Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
      .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true))
      .build();

    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));

    return HttpClients.custom()
      .setDefaultAuthSchemeRegistry(authRegistry)
      .setDefaultCredentialsProvider(credentialsProvider)
      .build();
  });
}
 
源代码20 项目: hbase   文件: TestThriftSpnegoHttpServer.java
private CloseableHttpClient createHttpClient() throws Exception {
  final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(clientPrincipal, clientKeytab);
  final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
  // Make sure the subject has a principal
  assertFalse("Found no client principals in the clientSubject.",
    clientPrincipals.isEmpty());

  // Get a TGT for the subject (might have many, different encryption types). The first should
  // be the default encryption type.
  Set<KerberosTicket> privateCredentials =
      clientSubject.getPrivateCredentials(KerberosTicket.class);
  assertFalse("Found no private credentials in the clientSubject.",
    privateCredentials.isEmpty());
  KerberosTicket tgt = privateCredentials.iterator().next();
  assertNotNull("No kerberos ticket found.", tgt);

  // The name of the principal
  final String clientPrincipalName = clientPrincipals.iterator().next().getName();

  return Subject.doAs(clientSubject, (PrivilegedExceptionAction<CloseableHttpClient>) () -> {
    // Logs in with Kerberos via GSS
    GSSManager gssManager = GSSManager.getInstance();
    // jGSS Kerberos login constant
    Oid oid = new Oid("1.2.840.113554.1.2.2");
    GSSName gssClient = gssManager.createName(clientPrincipalName, GSSName.NT_USER_NAME);
    GSSCredential credential = gssManager.createCredential(gssClient,
        GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);

    Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
        .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true))
        .build();

    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));

    return HttpClients.custom()
        .setDefaultAuthSchemeRegistry(authRegistry)
        .setDefaultCredentialsProvider(credentialsProvider)
        .build();
  });
}
 
源代码21 项目: hbase   文件: TestSpnegoHttpServer.java
@Test
public void testAllowedClient() throws Exception {
  // Create the subject for the client
  final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(CLIENT_PRINCIPAL, clientKeytab);
  final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
  // Make sure the subject has a principal
  assertFalse(clientPrincipals.isEmpty());

  // Get a TGT for the subject (might have many, different encryption types). The first should
  // be the default encryption type.
  Set<KerberosTicket> privateCredentials =
          clientSubject.getPrivateCredentials(KerberosTicket.class);
  assertFalse(privateCredentials.isEmpty());
  KerberosTicket tgt = privateCredentials.iterator().next();
  assertNotNull(tgt);

  // The name of the principal
  final String principalName = clientPrincipals.iterator().next().getName();

  // Run this code, logged in as the subject (the client)
  HttpResponse resp = Subject.doAs(clientSubject, new PrivilegedExceptionAction<HttpResponse>() {
      @Override
      public HttpResponse run() throws Exception {
        // Logs in with Kerberos via GSS
        GSSManager gssManager = GSSManager.getInstance();
        // jGSS Kerberos login constant
        Oid oid = new Oid("1.2.840.113554.1.2.2");
        GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME);
        GSSCredential credential = gssManager.createCredential(gssClient,
            GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);

        HttpClientContext context = HttpClientContext.create();
        Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true))
            .build();

        HttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry)
                .build();
        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));

        URL url = new URL(getServerURL(server), "/echo?a=b");
        context.setTargetHost(new HttpHost(url.getHost(), url.getPort()));
        context.setCredentialsProvider(credentialsProvider);
        context.setAuthSchemeRegistry(authRegistry);

        HttpGet get = new HttpGet(url.toURI());
        return client.execute(get, context);
      }
  });

  assertNotNull(resp);
  assertEquals(HttpURLConnection.HTTP_OK, resp.getStatusLine().getStatusCode());
  assertEquals("a:b", EntityUtils.toString(resp.getEntity()).trim());
}
 
源代码22 项目: hbase   文件: TestProxyUserSpnegoHttpServer.java
public void testProxy(String clientPrincipal, String doAs, int responseCode, String statusLine) throws Exception {
  // Create the subject for the client
  final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(WHEEL_PRINCIPAL, wheelKeytab);
  final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
  // Make sure the subject has a principal
  assertFalse(clientPrincipals.isEmpty());

  // Get a TGT for the subject (might have many, different encryption types). The first should
  // be the default encryption type.
  Set<KerberosTicket> privateCredentials =
          clientSubject.getPrivateCredentials(KerberosTicket.class);
  assertFalse(privateCredentials.isEmpty());
  KerberosTicket tgt = privateCredentials.iterator().next();
  assertNotNull(tgt);

  // The name of the principal
  final String principalName = clientPrincipals.iterator().next().getName();

  // Run this code, logged in as the subject (the client)
  HttpResponse resp = Subject.doAs(clientSubject, new PrivilegedExceptionAction<HttpResponse>() {
      @Override
      public HttpResponse run() throws Exception {
        // Logs in with Kerberos via GSS
        GSSManager gssManager = GSSManager.getInstance();
        // jGSS Kerberos login constant
        Oid oid = new Oid("1.2.840.113554.1.2.2");
        GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME);
        GSSCredential credential = gssManager.createCredential(gssClient,
            GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);

        HttpClientContext context = HttpClientContext.create();
        Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true))
            .build();

        HttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry)
                .build();
        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));

        URL url = new URL(getServerURL(server), "/echo?doAs=" + doAs + "&a=b");
        context.setTargetHost(new HttpHost(url.getHost(), url.getPort()));
        context.setCredentialsProvider(credentialsProvider);
        context.setAuthSchemeRegistry(authRegistry);

        HttpGet get = new HttpGet(url.toURI());
        return client.execute(get, context);
      }
  });

  assertNotNull(resp);
  assertEquals(responseCode, resp.getStatusLine().getStatusCode());
  if(responseCode == HttpURLConnection.HTTP_OK) {
      assertTrue(EntityUtils.toString(resp.getEntity()).trim().contains("a:b"));
  } else {
      assertTrue(resp.getStatusLine().toString().contains(statusLine));
  }
}