org.apache.http.impl.auth.BasicScheme Java Examples

The following examples show how to use org.apache.http.impl.auth.BasicScheme. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FormatClientSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
protected CloseableHttpResponse execute(final HttpUriRequest request, String username, String password)
    throws IOException
{
  log.debug("Authorizing request for {} using credentials provided for username: {}",
      request.getURI(), username);
  CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

  HttpHost host = URIUtils.extractHost(request.getURI());

  AuthCache authCache = new BasicAuthCache();
  authCache.put(host, new BasicScheme());

  HttpClientContext clientContext = new HttpClientContext(httpClientContext);
  clientContext.setAuthCache(authCache);
  clientContext.setCredentialsProvider(credsProvider);

  return execute(request, clientContext);
}
 
Example #2
Source File: Substitute_RestClient.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Substitute
public synchronized void setNodes(Collection<Node> nodes) {
    if (nodes == null || nodes.isEmpty()) {
        throw new IllegalArgumentException("nodes must not be null or empty");
    }
    AuthCache authCache = new NoSerializationBasicAuthCache();

    Map<HttpHost, Node> nodesByHost = new LinkedHashMap<>();
    for (Node node : nodes) {
        Objects.requireNonNull(node, "node cannot be null");
        // TODO should we throw an IAE if we have two nodes with the same host?
        nodesByHost.put(node.getHost(), node);
        authCache.put(node.getHost(), new BasicScheme());
    }
    this.nodeTuple = new NodeTuple<>(Collections.unmodifiableList(new ArrayList<>(nodesByHost.values())),
            authCache);
    this.blacklist.clear();
}
 
Example #3
Source File: DefaultSpringCloudConfigClientGateway.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private HttpClientContext setupContext() {
    final HttpClientContext context = HttpClientContext.create();
    if (baseUri.contains("@") || springCloudConfigClientConfig.usernameAndPasswordSet()) {
        final AuthCache authCache = InMemoryAuthCache.INSTANCE;
        authCache.put(HttpHost.create(baseUri), new BasicScheme());
        context.setAuthCache(authCache);
        if (springCloudConfigClientConfig.usernameAndPasswordSet()) {
            final CredentialsProvider provider = new BasicCredentialsProvider();
            final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                    springCloudConfigClientConfig.username.get(), springCloudConfigClientConfig.password.get());
            provider.setCredentials(AuthScope.ANY, credentials);
            context.setCredentialsProvider(provider);
        }
    }
    return context;
}
 
Example #4
Source File: ConnectorCommon.java    From nextcloud-java-api with GNU General Public License v3.0 6 votes vote down vote up
private HttpClientContext prepareContext()
{
    HttpHost targetHost = new HttpHost(serverConfig.getServerName(), serverConfig.getPort(), serverConfig.isUseHTTPS() ? "https" : "http");
    AuthCache authCache = new BasicAuthCache();
    authCache.put(targetHost, new BasicScheme());

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials
     = new UsernamePasswordCredentials(serverConfig.getUserName(), serverConfig.getPassword());
    credsProvider.setCredentials(AuthScope.ANY, credentials);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
    return context;
}
 
Example #5
Source File: TaxiiHandler.java    From metron with Apache License 2.0 6 votes vote down vote up
private static HttpClientContext createContext(URL endpoint, String username, String password, int port) {
  HttpClientContext context = null;
  HttpHost target = new HttpHost(endpoint.getHost(), port, endpoint.getProtocol());
  if (username != null && password != null) {

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
        new AuthScope(target.getHostName(), target.getPort()),
        new UsernamePasswordCredentials(username, password));

    // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html
    AuthCache authCache = new BasicAuthCache();
    authCache.put(target, new BasicScheme());

    // Add AuthCache to the execution context
    context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
  } else {
    context = null;
  }
  return context;
}
 
Example #6
Source File: UriStrategy.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
protected void initAuthentication() {
   if (registration.getAuthenticationMechanism() != null) {
      if (registration.getAuthenticationMechanism().getType() instanceof BasicAuth) {
         BasicAuth basic = (BasicAuth) registration.getAuthenticationMechanism().getType();
         UsernamePasswordCredentials creds = new UsernamePasswordCredentials(basic.getUsername(), basic.getPassword());
         AuthScope authScope = new AuthScope(AuthScope.ANY);
         ((DefaultHttpClient) client).getCredentialsProvider().setCredentials(authScope, creds);

         localContext = new BasicHttpContext();

         // Generate BASIC scheme object and stick it to the local execution context
         BasicScheme basicAuth = new BasicScheme();
         localContext.setAttribute("preemptive-auth", basicAuth);

         // Add as the first request interceptor
         ((DefaultHttpClient) client).addRequestInterceptor(new PreemptiveAuth(), 0);
         executor.setHttpContext(localContext);
      }
   }
}
 
Example #7
Source File: ApacheUtils.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext,
                                                     ProxyConfiguration proxyConfiguration) {

    if (proxyConfiguration.preemptiveBasicAuthenticationEnabled()) {
        HttpHost targetHost = new HttpHost(proxyConfiguration.host(), proxyConfiguration.port());
        CredentialsProvider credsProvider = newProxyCredentialsProvider(proxyConfiguration);
        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        clientContext.setCredentialsProvider(credsProvider);
        clientContext.setAuthCache(authCache);
    }
}
 
Example #8
Source File: ApacheUtils.java    From ibm-cos-sdk-java with Apache License 2.0 6 votes vote down vote up
private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext,
                                                     HttpClientSettings settings) {

    if (settings.isPreemptiveBasicProxyAuth()) {
        HttpHost targetHost = new HttpHost(settings.getProxyHost(), settings
                .getProxyPort());
        final CredentialsProvider credsProvider = newProxyCredentialsProvider(settings);
        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        clientContext.setCredentialsProvider(credsProvider);
        clientContext.setAuthCache(authCache);
    }
}
 
Example #9
Source File: HDInsightInstance.java    From reef with Apache License 2.0 6 votes vote down vote up
private HttpClientContext getClientContext(final String hostname, final String username, final String password)
    throws IOException {
  final HttpHost targetHost = new HttpHost(hostname, 443, "https");
  final HttpClientContext result = HttpClientContext.create();

  // Setup credentials provider
  final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

  credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
  result.setCredentialsProvider(credentialsProvider);

  // Setup preemptive authentication
  final AuthCache authCache = new BasicAuthCache();
  final BasicScheme basicAuth = new BasicScheme();
  authCache.put(targetHost, basicAuth);
  result.setAuthCache(authCache);
  final HttpGet httpget = new HttpGet("/");

  // Prime the cache
  try (CloseableHttpResponse response = this.httpClient.execute(targetHost, httpget, result)) {
    // empty try block used to automatically close resources
  }
  return result;
}
 
Example #10
Source File: SPARQLProtocolSession.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected void setUsernameAndPasswordForUrl(String username, String password, String url) {

		if (username != null && password != null) {
			logger.debug("Setting username '{}' and password for server at {}.", username, url);
			java.net.URI requestURI = java.net.URI.create(url);
			String host = requestURI.getHost();
			int port = requestURI.getPort();
			AuthScope scope = new AuthScope(host, port);
			UsernamePasswordCredentials cred = new UsernamePasswordCredentials(username, password);
			CredentialsProvider credsProvider = new BasicCredentialsProvider();
			credsProvider.setCredentials(scope, cred);
			httpContext.setCredentialsProvider(credsProvider);
			AuthCache authCache = new BasicAuthCache();
			BasicScheme basicAuth = new BasicScheme();
			HttpHost httpHost = new HttpHost(requestURI.getHost(), requestURI.getPort(), requestURI.getScheme());
			authCache.put(httpHost, basicAuth);
			httpContext.setAuthCache(authCache);
		} else {
			httpContext.removeAttribute(HttpClientContext.AUTH_CACHE);
			httpContext.removeAttribute(HttpClientContext.CREDS_PROVIDER);
		}
	}
 
Example #11
Source File: WireMockTestClient.java    From wiremock-webhooks-extension with Apache License 2.0 6 votes vote down vote up
public WireMockResponse getWithPreemptiveCredentials(String url, int port, String username, String password) {
    HttpHost target = new HttpHost("localhost", port);
    HttpClient httpClient = httpClientWithPreemptiveAuth(target, username, password);

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(target, basicAuth);
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    try {
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpClient.execute(target, httpget, localContext);
        return new WireMockResponse(response);
    } catch (IOException e) {
        return throwUnchecked(e, WireMockResponse.class);
    }
}
 
Example #12
Source File: HttpRpcTransport.java    From etherjar with Apache License 2.0 6 votes vote down vote up
/**
 * Setup Basic Auth for RPC calls
 *
 * @param username username
 * @param password password
 * @return builder
 */
public Builder basicAuth(String username, String password) {
    this.httpClient = null;

    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    AuthCache cache = new BasicAuthCache();
    cache.put(
        new HttpHost(target.getHost(), target.getPort(), target.getScheme()),
        new BasicScheme()
    );

    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(provider);
    context.setAuthCache(cache);
    this.context = context;

    return this;
}
 
Example #13
Source File: WebRealmServiceTest.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
@Override
public void process( final HttpRequest request, final HttpContext context )
    throws HttpException, IOException
{
    AuthState authState = (AuthState) context.getAttribute( ClientContext.TARGET_AUTH_STATE );
    CredentialsProvider credsProvider = (CredentialsProvider) context
        .getAttribute( ClientContext.CREDS_PROVIDER );
    HttpHost targetHost = (HttpHost) context.getAttribute( ExecutionContext.HTTP_TARGET_HOST );

    // If not auth scheme has been initialized yet
    if( authState.getAuthScheme() == null )
    {
        AuthScope authScope = new AuthScope( targetHost.getHostName(),
                                             targetHost.getPort() );
        // Obtain credentials matching the target host
        Credentials creds = credsProvider.getCredentials( authScope );
        // If found, generate BasicScheme preemptively
        if( creds != null )
        {
            authState.setAuthScheme( new BasicScheme() );
            authState.setCredentials( creds );
        }
    }
}
 
Example #14
Source File: FormatClientSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
protected CloseableHttpResponse execute(final HttpUriRequest request, String username, String password)
    throws IOException
{
  log.debug("Authorizing request for {} using credentials provided for username: {}",
      request.getURI(), username);
  CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

  HttpHost host = URIUtils.extractHost(request.getURI());

  AuthCache authCache = new BasicAuthCache();
  authCache.put(host, new BasicScheme());

  HttpClientContext clientContext = new HttpClientContext(httpClientContext);
  clientContext.setAuthCache(authCache);
  clientContext.setCredentialsProvider(credsProvider);

  return execute(request, clientContext);
}
 
Example #15
Source File: HopServer.java    From hop with Apache License 2.0 6 votes vote down vote up
private void addCredentials( HttpClientContext context ) {

    String host = environmentSubstitute( hostname );
    int port = Const.toInt( environmentSubstitute( this.port ), 80 );
    String userName = environmentSubstitute( username );
    String password = Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( this.password ) );
    String proxyHost = environmentSubstitute( proxyHostname );

    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( userName, password );
    if ( !Utils.isEmpty( proxyHost ) && host.equals( "localhost" ) ) {
      host = "127.0.0.1";
    }
    provider.setCredentials( new AuthScope( host, port ), credentials );
    context.setCredentialsProvider( provider );
    // Generate BASIC scheme object and add it to the local auth cache
    HttpHost target = new HttpHost( host, port, isSslMode() ? HTTPS : HTTP );
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put( target, basicAuth );
    context.setAuthCache( authCache );
  }
 
Example #16
Source File: HttpClientUtil.java    From hop with Apache License 2.0 6 votes vote down vote up
/**
 * Returns context with AuthCache or null in case of any exception was thrown.
 *
 * @param host
 * @param port
 * @param user
 * @param password
 * @param schema
 * @return {@link org.apache.http.client.protocol.HttpClientContext HttpClientContext}
 */
public static HttpClientContext createPreemptiveBasicAuthentication( String host, int port, String user,
                                                                     String password, String schema ) {
  HttpClientContext localContext = null;
  try {
    HttpHost target = new HttpHost( host, port, schema );
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
      new AuthScope( target.getHostName(), target.getPort() ),
      new UsernamePasswordCredentials( user, password ) );

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local
    // auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put( target, basicAuth );

    // Add AuthCache to the execution context
    localContext = HttpClientContext.create();
    localContext.setAuthCache( authCache );
  } catch ( Exception e ) {
    return null;
  }
  return localContext;
}
 
Example #17
Source File: GatewayBasicFuncTest.java    From knox with Apache License 2.0 5 votes vote down vote up
private String oozieQueryJobStatus( String user, String password, String id, int status ) throws Exception {
  driver.getMock( "OOZIE" )
      .expect()
      .method( "GET" )
      .pathInfo( "/v1/job/" + id )
      .respond()
      .status( HttpStatus.SC_OK )
      .content( driver.getResourceBytes( "oozie-job-show-info.json" ) )
      .contentType( "application/json" );

  //NOTE:  For some reason REST-assured doesn't like this and ends up failing with Content-Length issues.
  URL url = new URL( driver.getUrl( "OOZIE" ) + "/v1/job/" + id + ( driver.isUseGateway() ? "" : "?user.name=" + user ) );
  HttpHost targetHost = new HttpHost( url.getHost(), url.getPort(), url.getProtocol() );
  HttpClientBuilder builder = HttpClientBuilder.create();
  CloseableHttpClient client = builder.build();

  HttpClientContext context = HttpClientContext.create();
  CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials(
      new AuthScope( targetHost ),
      new UsernamePasswordCredentials( user, password ) );
  context.setCredentialsProvider( credsProvider );

  // Create AuthCache instance
  AuthCache authCache = new BasicAuthCache();
  // Generate BASIC scheme object and add it to the local auth cache
  BasicScheme basicAuth = new BasicScheme();
  authCache.put( targetHost, basicAuth );
  // Add AuthCache to the execution context
  context.setAuthCache( authCache );

  HttpGet request = new HttpGet( url.toURI() );
  request.setHeader("X-XSRF-Header", "ksdhfjkhdsjkf");
  HttpResponse response = client.execute( targetHost, request, context );
  assertThat( response.getStatusLine().getStatusCode(), Matchers.is(status) );
  String json = EntityUtils.toString( response.getEntity() );
  return JsonPath.from(json).getString( "status" );
}
 
Example #18
Source File: AuthSchemeProviderLookupBuilderTest.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
@Test
public void buildLookupWithBasicAuth() {
    AuthSchemeProvider provider = getAuthSchemeProvider(AuthSchemes.BASIC);
    assertThat(provider, instanceOf(BasicSchemeFactory.class));
    BasicScheme basicSchema = ((BasicScheme) provider.create(null));
    assertEquals("UTF-8", basicSchema.getCredentialsCharset().toString());
}
 
Example #19
Source File: TTSUtility.java    From speech-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Post text data to the server and get returned audio data
 * @param server iTrans server
 * @param username
 * @param password
 * @param content
 * @return {@link HttpResponse}
 * @throws Exception
 */
public static HttpResponse createPost(String server, String username, String password, String token, boolean learningOptOut, String content, String voice, String codec) throws Exception {
       String url = server;

       //HTTP GET Client
       HttpClient httpClient = new DefaultHttpClient();
       //Add params
       List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
       params.add(new BasicNameValuePair("text", content));
       params.add(new BasicNameValuePair("voice", voice));
       params.add(new BasicNameValuePair("accept", codec));
       HttpGet httpGet = new HttpGet(url+"?"+ URLEncodedUtils.format(params, "utf-8"));
       // use token based authentication if possible, otherwise Basic Authentication will be used
       if (token != null) {
           Log.d(TAG, "using token based authentication");
           httpGet.setHeader("X-Watson-Authorization-Token",token);
       } else {
           Log.d(TAG, "using basic authentication");
           httpGet.setHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(username, password), "UTF-8", false));
       }

       if (learningOptOut) {
           Log.d(TAG, "setting X-Watson-Learning-OptOut");
           httpGet.setHeader("X-Watson-Learning-Opt-Out", "true");
       }
       HttpResponse executed = httpClient.execute(httpGet);
	return executed;
}
 
Example #20
Source File: BceHttpClient.java    From bce-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates HttpClient Context object based on the internal request.
 *
 * @param request The internal request.
 * @return HttpClient Context object.
 */
protected HttpClientContext createHttpContext(InternalRequest request) {
    HttpClientContext context = HttpClientContext.create();
    context.setRequestConfig(this.requestConfigBuilder.setExpectContinueEnabled(request.isExpectContinueEnabled())
            .setSocketTimeout(this.config.getSocketTimeoutInMillis()).build());
    if (this.credentialsProvider != null) {
        context.setCredentialsProvider(this.credentialsProvider);
    }
    if (this.config.isProxyPreemptiveAuthenticationEnabled()) {
        AuthCache authCache = new BasicAuthCache();
        authCache.put(this.proxyHttpHost, new BasicScheme());
        context.setAuthCache(authCache);
    }
    return context;
}
 
Example #21
Source File: NexusITSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @return Cache with preemptive auth enabled for Nexus
 */
protected AuthCache basicAuthCache() {
  String hostname = nexusUrl.getHost();
  AuthCache authCache = new BasicAuthCache();
  HttpHost hostHttp = new HttpHost(hostname, nexusUrl.getPort(), "http");
  HttpHost hostHttps = new HttpHost(hostname, nexusSecureUrl.getPort(), "https");
  authCache.put(hostHttp, new BasicScheme());
  authCache.put(hostHttps, new BasicScheme());
  return authCache;
}
 
Example #22
Source File: PreemptiveAuthHttpRequestInterceptor.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
  HttpClientContext clientContext = HttpClientContext.adapt(context);
  AuthState authState = clientContext.getTargetAuthState();
  if (authState.getAuthScheme() == null) {
    CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
    HttpHost targetHost = clientContext.getTargetHost();
    Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
    if (creds != null) {
      authState.update(new BasicScheme(), creds);
    }
  }
}
 
Example #23
Source File: util.java    From octodroid with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void SetupAuthentication(HttpRequestBase request) {
    if ( memory.user.getUseBasicAuth() )
    {
        request.addHeader(
                BasicScheme.authenticate(
                        new UsernamePasswordCredentials(
                                memory.user.getUserName(),
                                memory.user.getPassword()),"UTF-8",false)
        );
    }
}
 
Example #24
Source File: TextToSpeech.java    From speech-android-sdk with Apache License 2.0 5 votes vote down vote up
private void buildAuthenticationHeader(HttpGet httpGet) {

        // use token based authentication if possible, otherwise Basic Authentication will be used
        if (this.tokenProvider != null) {
            Log.d(TAG, "using token based authentication");
            httpGet.setHeader("X-Watson-Authorization-Token",this.tokenProvider.getToken());
        } else {
            Log.d(TAG, "using basic authentication");
            httpGet.setHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(this.username, this.password), "UTF-8",false));
        }
    }
 
Example #25
Source File: CloseableHttpProvider.java    From tokens with Apache License 2.0 5 votes vote down vote up
public CloseableHttpProvider(ClientCredentials clientCredentials, UserCredentials userCredentials,
        URI accessTokenUri, HttpConfig httpConfig) {

    this.userCredentials = userCredentials;
    this.accessTokenUri = accessTokenUri;

    requestConfig = RequestConfig.custom()
                                 .setSocketTimeout(httpConfig.getSocketTimeout())
                                 .setConnectTimeout(httpConfig.getConnectTimeout())
                                 .setConnectionRequestTimeout(httpConfig.getConnectionRequestTimeout())
                                 .setStaleConnectionCheckEnabled(httpConfig.isStaleConnectionCheckEnabled())
                                 .build();

    // prepare basic auth credentials
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(accessTokenUri.getHost(), accessTokenUri.getPort()),
            new UsernamePasswordCredentials(clientCredentials.getId(), clientCredentials.getSecret()));

    client = HttpClients.custom()
                        .setUserAgent(USER_AGENT.get())
                        .useSystemProperties()
                        .setDefaultCredentialsProvider(credentialsProvider)
                        .build();

    host = new HttpHost(accessTokenUri.getHost(), accessTokenUri.getPort(), accessTokenUri.getScheme());

    // enable basic auth for the request
    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);

    localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
}
 
Example #26
Source File: HttpClientConfigurer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void configureCredentials(DefaultHttpClient httpClient, PasswordCredentials credentials) {
    String username = credentials.getUsername();
    if (username != null && username.length() > 0) {
        useCredentials(httpClient, credentials, AuthScope.ANY_HOST, AuthScope.ANY_PORT);

        // Use preemptive authorisation if no other authorisation has been established
        httpClient.addRequestInterceptor(new PreemptiveAuth(new BasicScheme()), 0);
    }
}
 
Example #27
Source File: HttpClientConfigurer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void configureCredentials(DefaultHttpClient httpClient, PasswordCredentials credentials) {
    if (GUtil.isTrue(credentials.getUsername())) {
        useCredentials(httpClient, credentials, AuthScope.ANY_HOST, AuthScope.ANY_PORT);

        // Use preemptive authorisation if no other authorisation has been established
        httpClient.addRequestInterceptor(new PreemptiveAuth(new BasicScheme()), 0);
    }
}
 
Example #28
Source File: DefaultFileDownloader.java    From flow with Apache License 2.0 5 votes vote down vote up
private HttpClientContext makeLocalContext(URL requestUrl) {
    // Auth target host
    HttpHost target = new HttpHost(requestUrl.getHost(),
            requestUrl.getPort(), requestUrl.getProtocol());
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(target, basicAuth);
    // Add AuthCache to the execution context
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    return localContext;
}
 
Example #29
Source File: SyntheticMonitorService.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private HttpClientContext getHttpClientContext() throws Exception {
    HttpProxyConfig httpProxyConfig = configRepository.getHttpProxyConfig();
    if (httpProxyConfig.host().isEmpty() || httpProxyConfig.username().isEmpty()) {
        return HttpClientContext.create();
    }

    // perform preemptive proxy authentication

    int proxyPort = MoreObjects.firstNonNull(httpProxyConfig.port(), 80);
    HttpHost proxyHost = new HttpHost(httpProxyConfig.host(), proxyPort);

    BasicScheme basicScheme = new BasicScheme();
    basicScheme.processChallenge(new BasicHeader(AUTH.PROXY_AUTH, "BASIC realm="));
    BasicAuthCache authCache = new BasicAuthCache();
    authCache.put(proxyHost, basicScheme);

    String password = httpProxyConfig.encryptedPassword();
    if (!password.isEmpty()) {
        password = Encryption.decrypt(password, configRepository.getLazySecretKey());
    }
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(proxyHost),
            new UsernamePasswordCredentials(httpProxyConfig.username(), password));
    HttpClientContext context = HttpClientContext.create();
    context.setAuthCache(authCache);
    context.setCredentialsProvider(credentialsProvider);
    return context;
}
 
Example #30
Source File: SpeechToText.java    From speech-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Build authentication header
 * @param httpGet
 */
private void buildAuthenticationHeader(HttpGet httpGet) {
    // use token based authentication if possible, otherwise Basic Authentication will be used
    if (this.tokenProvider != null) {
        Log.d(TAG, "using token based authentication");
        httpGet.setHeader("X-Watson-Authorization-Token",this.tokenProvider.getToken());
    } else {
        Log.d(TAG, "using basic authentication");
        httpGet.setHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(this.username, this.password), "UTF-8",false));
    }
}