org.apache.http.auth.Credentials Java Examples

The following examples show how to use org.apache.http.auth.Credentials. 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: NexusITSupport.java    From nexus-public with Eclipse Public License 1.0 7 votes vote down vote up
/**
 * @return a generic REST client with authentication configured
 */
protected Client restClient() {
  try {
    final HttpClient httpClient = clientBuilder().build();
    final Credentials credentials = credentials();
    return restClientFactory
        .create(RestClientConfiguration.DEFAULTS
            .withHttpClient(() -> httpClient)
            .withCustomizer(getObjectMapperCustomizer(testSuiteObjectMapperResolver))
        )
        .register(new BasicAuthentication(credentials.getUserPrincipal().getName(), credentials.getPassword()));
  }
  catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example #2
Source File: HttpTransportFactory.java    From hadoop-connectors with Apache License 2.0 7 votes vote down vote up
/**
 * Create an {@link ApacheHttpTransport} for calling Google APIs with an optional HTTP proxy.
 *
 * @param proxyUri Optional HTTP proxy URI to use with the transport.
 * @param proxyCredentials Optional HTTP proxy credentials to authenticate with the transport
 *     proxy.
 * @return The resulting HttpTransport.
 * @throws IOException If there is an issue connecting to Google's certification server.
 * @throws GeneralSecurityException If there is a security issue with the keystore.
 */
public static ApacheHttpTransport createApacheHttpTransport(
    @Nullable URI proxyUri, @Nullable Credentials proxyCredentials)
    throws IOException, GeneralSecurityException {
  checkArgument(
      proxyUri != null || proxyCredentials == null,
      "if proxyUri is null than proxyCredentials should be null too");

  ApacheHttpTransport transport =
      new ApacheHttpTransport.Builder()
          .trustCertificates(GoogleUtils.getCertificateTrustStore())
          .setProxy(
              proxyUri == null ? null : new HttpHost(proxyUri.getHost(), proxyUri.getPort()))
          .build();

  if (proxyCredentials != null) {
    ((DefaultHttpClient) transport.getHttpClient())
        .getCredentialsProvider()
        .setCredentials(new AuthScope(proxyUri.getHost(), proxyUri.getPort()), proxyCredentials);
  }

  return transport;
}
 
Example #3
Source File: PreemptiveAuth.java    From verigreen with Apache License 2.0 6 votes vote down vote up
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    Credentials creds;
    
    if (authState.getAuthScheme() == null) {
        AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
        CredentialsProvider credsProvider =
                (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
        HttpHost targetHost =
                (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (authScheme != null) {
            creds =
                    credsProvider.getCredentials(new AuthScope(
                            targetHost.getHostName(),
                            targetHost.getPort()));
            if (creds == null) {
                throw new HttpException("No credentials for preemptive authentication");
            }
            authState.update(authScheme, creds);
        }
    }
}
 
Example #4
Source File: HttpConnection.java    From arangodb-java-driver with Apache License 2.0 6 votes vote down vote up
public Response execute(final Request request) throws ArangoDBException, IOException {
    final String url = buildUrl(buildBaseUrl(host), request);
    final HttpRequestBase httpRequest = buildHttpRequestBase(request, url);
    httpRequest.setHeader("User-Agent", "Mozilla/5.0 (compatible; ArangoDB-JavaDriver/1.1; +http://mt.orz.at/)");
    if (contentType == Protocol.HTTP_VPACK) {
        httpRequest.setHeader("Accept", "application/x-velocypack");
    }
    addHeader(request, httpRequest);
    final Credentials credentials = addCredentials(httpRequest);
    if (LOGGER.isDebugEnabled()) {
        CURLLogger.log(url, request, credentials, util);
    }
    Response response;
    response = buildResponse(client.execute(httpRequest));
    checkError(response);
    return response;
}
 
Example #5
Source File: SlaveServerTest.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddCredentials() throws IOException, ClassNotFoundException {
  String testUser = "test_username";
  slaveServer.setUsername( testUser );
  String testPassword = "test_password";
  slaveServer.setPassword( testPassword );
  String host = "somehost";
  slaveServer.setHostname( host );
  int port = 1000;
  slaveServer.setPort( "" + port );

  HttpClientContext auth = slaveServer.getAuthContext();
  Credentials cred = auth.getCredentialsProvider().getCredentials( new AuthScope( host, port ) );
  assertEquals( testUser, cred.getUserPrincipal().getName() );
  assertEquals( testPassword, cred.getPassword() );

  String user2 = "user2";
  slaveServer.setUsername( user2 );
  slaveServer.setPassword( "pass2" );
  auth = slaveServer.getAuthContext();
  cred = auth.getCredentialsProvider().getCredentials( new AuthScope( host, port ) );
  assertEquals( user2, cred.getUserPrincipal().getName() );
}
 
Example #6
Source File: JettyDigestAuthTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void doTest(boolean async) throws Exception {
    setupClient(async);
    assertEquals("Hello Alice", greeter.greetMe("Alice"));
    assertEquals("Hello Bob", greeter.greetMe("Bob"));

    try {
        BindingProvider bp = (BindingProvider)greeter;
        if (async) {
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials("blah", "foo");
            bp.getRequestContext().put(Credentials.class.getName(), creds);
        } else {
            bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "blah");
            bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "foo");
        }
        greeter.greetMe("Alice");
        fail("Password was wrong, should have failed");
    } catch (WebServiceException wse) {
        //ignore - expected
    }
}
 
Example #7
Source File: HttpService.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public static CloseableHttpResponse execute(HttpUriRequest req, @Nullable Credentials auth) throws IOException {
   if (auth != null) {
      URI uri = req.getURI();
      AuthScope scope = new AuthScope(uri.getHost(), uri.getPort());

      CredentialsProvider provider = new BasicCredentialsProvider();
      provider.setCredentials(scope, auth);

      HttpClientContext context = HttpClientContext.create();
      context.setCredentialsProvider(provider);

      return get().execute(req, context);
   }

   return execute(req);
}
 
Example #8
Source File: HttpQueryBackend.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static Credentials getCredentials( final String user,
                                          final String password ) {
  if ( StringUtils.isEmpty( user ) ) {
    return null;
  }

  final int domainIdx = user.indexOf( DOMAIN_SEPARATOR );
  if ( domainIdx == -1 ) {
    return new UsernamePasswordCredentials( user, password );
  }
  try {
    final String domain = user.substring( 0, domainIdx );
    final String username = user.substring( domainIdx + 1 );
    final String host = InetAddress.getLocalHost().getHostName();
    return new NTCredentials( username, password, host, domain );
  } catch ( UnknownHostException uhe ) {
    return new UsernamePasswordCredentials( user, password );
  }
}
 
Example #9
Source File: RepositoriesCredentialsTableModel.java    From snap-desktop with GNU General Public License v3.0 6 votes vote down vote up
public boolean add(Credentials credential) {
    boolean exists = false;
    for (CredentialsTableRow credentialData : credentialsTableData) {
        UsernamePasswordCredentials savedCredential = (UsernamePasswordCredentials) credentialData.getCredentials();
        String savedUsername = savedCredential.getUserPrincipal().getName();
        String username = credential.getUserPrincipal().getName();
        String savedPassword = savedCredential.getPassword();
        String password = credential.getPassword();
        if (savedUsername.contentEquals(username) && savedPassword.contentEquals(password)) {
            exists = true;
            break;
        }
    }
    if (!exists) {
        CredentialsTableRow credentialsTableRow = new CredentialsTableRow(credential, credentialsTableData.size());
        credentialsTableData.add(credentialsTableRow);
        int row = credentialsTableData.indexOf(credentialsTableRow);
        fireTableRowsInserted(row, row);
        return true;
    }
    return false;
}
 
Example #10
Source File: Tdm.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void initServers() throws HTTPException {
  if (serverNames == null) {
    servers = new ArrayList<>(); // empty list
    return;
  }

  this.servers = new ArrayList<>(this.serverNames.length);
  for (String name : this.serverNames) {
    HTTPSession session = HTTPFactory.newSession(name);
    if (user != null && pass != null) {
      Credentials bp = new UsernamePasswordCredentials(user, pass);
      BasicCredentialsProvider bcp = new BasicCredentialsProvider();
      bcp.setCredentials(AuthScope.ANY, bp);
      session.setCredentialsProvider(bcp);
    }
    session.setUserAgent("TDM");
    servers.add(new Server(name, session));
  }
}
 
Example #11
Source File: AuthenticatorTestCase.java    From hadoop with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #12
Source File: DownloadRemoteProductsHelper.java    From snap-desktop with GNU General Public License v3.0 6 votes vote down vote up
public void downloadProductsQuickLookImageAsync(List<RepositoryProduct> productsWithoutQuickLookImage, RemoteProductsRepositoryProvider productsRepositoryProvider,
                                                Credentials credentials, RepositoryOutputProductListPanel repositoryProductListPanel) {

    createThreadPoolExecutorIfNeeded();

    DownloadProductsQuickLookImageRunnable runnable = new DownloadProductsQuickLookImageRunnable(productsWithoutQuickLookImage, productsRepositoryProvider,
                                                                                                 credentials, this.remoteRepositoriesSemaphore, repositoryProductListPanel) {

        @Override
        protected void finishRunning() {
            super.finishRunning();
            finishRunningDownloadProductsQuickLookImageThreadLater(this);
        }
    };
    this.runningTasks.put(runnable, null);
    this.threadPoolExecutor.execute(runnable); // start the thread
}
 
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: WebServicesClientTest.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
public static void checkUserCredentials(String username, String password, AuthScheme authScheme) throws NoSuchFieldException,
    IllegalAccessException
{
  CredentialsProvider provider = getCredentialsProvider();
  String httpScheme = AuthScope.ANY_SCHEME;
  if (authScheme == AuthScheme.BASIC) {
    httpScheme = AuthSchemes.BASIC;
  } else if (authScheme == AuthScheme.DIGEST) {
    httpScheme = AuthSchemes.DIGEST;
  }
  AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, httpScheme);
  Credentials credentials = provider.getCredentials(authScope);
  Assert.assertNotNull("Credentials", credentials);
  Assert.assertTrue("Credentials type is user", UsernamePasswordCredentials.class.isAssignableFrom(credentials.getClass()));
  UsernamePasswordCredentials pwdCredentials = (UsernamePasswordCredentials)credentials;
  Assert.assertEquals("Username", username, pwdCredentials.getUserName());
  Assert.assertEquals("Password", password, pwdCredentials.getPassword());
}
 
Example #15
Source File: ProductLibraryToolViewV2.java    From snap-desktop with GNU General Public License v3.0 6 votes vote down vote up
private void outputProductsPageChanged() {
    this.downloadRemoteProductsHelper.cancelDownloadingProductsQuickLookImage();
    if (this.localRepositoryProductsThread == null) {
        AbstractProductsRepositoryPanel selectedProductsRepositoryPanel = this.repositorySelectionPanel.getSelectedProductsRepositoryPanel();
        if (selectedProductsRepositoryPanel instanceof RemoteProductsRepositoryPanel) {
            OutputProductListModel productListModel = this.repositoryOutputProductListPanel.getProductListPanel().getProductListModel();
            List<RepositoryProduct> productsWithoutQuickLookImage = productListModel.findProductsWithoutQuickLookImage();
            if (productsWithoutQuickLookImage.size() > 0) {
                if (logger.isLoggable(Level.FINE)) {
                    int currentPageNumber = selectedProductsRepositoryPanel.getOutputProductResults().getCurrentPageNumber();
                    String repositoryName = selectedProductsRepositoryPanel.getRepositoryName();
                    logger.log(Level.FINE, "Start downloading the quick look images for " + productsWithoutQuickLookImage.size()+" products from page number " + currentPageNumber + " using the '" +repositoryName+"' remote repository.");
                }

                RemoteProductsRepositoryPanel remoteProductsRepositoryPanel = (RemoteProductsRepositoryPanel)selectedProductsRepositoryPanel;
                Credentials selectedCredentials = remoteProductsRepositoryPanel.getSelectedAccount();
                RemoteProductsRepositoryProvider productsRepositoryProvider = remoteProductsRepositoryPanel.getProductsRepositoryProvider();
                this.downloadRemoteProductsHelper.downloadProductsQuickLookImageAsync(productsWithoutQuickLookImage, productsRepositoryProvider, selectedCredentials, this.repositoryOutputProductListPanel);
            }
        }
    }
}
 
Example #16
Source File: TestUrlCreds.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testUrlCredDefaultProvider() throws HTTPException {
  String url = "https://" + username + ":" + password + "@" + host + "/something/garbage.grb?query";
  logger.info("Testing {}", url);
  try (HTTPMethod method = HTTPFactory.Get(url)) {
    // we should have a default BasicCredentialProvider available, even though
    // we didn't call the factory with a specific provider
    HTTPSession session = method.getSession();
    CredentialsProvider credentialsProvider = session.sessionprovider;
    assertThat(credentialsProvider).isNotNull();
    AuthScope expectedAuthScope = new AuthScope(host, 80);
    Credentials credentials = credentialsProvider.getCredentials(expectedAuthScope);
    assertThat(credentials).isNotNull();
    assertThat(credentials.getUserPrincipal().getName()).isEqualTo(username);
    assertThat(credentials.getPassword()).isEqualTo(password);
  }
}
 
Example #17
Source File: HttpClientHandler.java    From ant-ivy with Apache License 2.0 5 votes vote down vote up
@Override
public Credentials getCredentials(final AuthScope authscope) {
    if (authscope == null) {
        return null;
    }
    final String realm = authscope.getRealm();
    final String host = authscope.getHost();
    final org.apache.ivy.util.Credentials ivyConfiguredCred = CredentialsStore.INSTANCE.getCredentials(realm, host);
    if (ivyConfiguredCred == null) {
        return null;
    }
    return createCredentials(ivyConfiguredCred.getUserName(), ivyConfiguredCred.getPasswd());
}
 
Example #18
Source File: ClientFactory.java    From fcrepo-camel-toolbox with Apache License 2.0 5 votes vote down vote up
/**
 * Create a linked data client suitable for use with a Fedora Repository.
 * @param authScope the authentication scope
 * @param credentials the credentials
 * @param endpoints additional endpoints to enable on the client
 * @param providers additional providers to enable on the client
 * @return a configuration for use with an LDClient
 */
public static ClientConfiguration createClient(final AuthScope authScope, final Credentials credentials,
        final List<Endpoint> endpoints, final List<DataProvider> providers) {

    final ClientConfiguration client = new ClientConfiguration();

    if (credentials != null && authScope != null) {
        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(authScope, credentials);
        client.setHttpClient(HttpClients.custom()
                .setDefaultCredentialsProvider(credsProvider)
                .useSystemProperties().build());
    }

    // manually add default Providers and Endpoints
    client.addProvider(new LinkedDataProvider());
    client.addProvider(new CacheProvider());
    client.addProvider(new RegexUriProvider());
    client.addProvider(new SPARQLProvider());
    client.addEndpoint(new LinkedDataEndpoint());

    // add any injected endpoints/providers
    endpoints.forEach(client::addEndpoint);
    providers.forEach(client::addProvider);

    return client;
}
 
Example #19
Source File: AccessApi.java    From nifi-swagger-client with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example #20
Source File: ApacheUtils.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new instance of NTCredentials used for proxy authentication.
 */
private static Credentials newNTCredentials(HttpClientSettings settings) {
    return new NTCredentials(settings.getProxyUsername(),
            settings.getProxyPassword(),
            settings.getProxyWorkstation(),
            settings.getProxyDomain());
}
 
Example #21
Source File: SPARQLEndpointExecution.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
@Override
public SPARQLExecutionResult call() {
    Map<String, Set<String>> resultSet = new HashMap<>();

    markers.forEach(marker -> resultSet.put(marker, new HashSet<>()));

    Model unionModel = ModelFactory.createDefaultModel();

    SPARQLServiceConverter converter = new SPARQLServiceConverter(schema);
    String sparqlQuery = converter.getSelectQuery(query, inputSubset, rootType);
    logger.info(sparqlQuery);

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    Credentials credentials =
            new UsernamePasswordCredentials(this.sparqlEndpointService.getUser(), this.sparqlEndpointService.getPassword());
    credsProvider.setCredentials(AuthScope.ANY, credentials);
    HttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider)
            .build();
    HttpOp.setDefaultHttpClient(httpclient);

    Query jenaQuery = QueryFactory.create(sparqlQuery);

    QueryEngineHTTP qEngine = QueryExecutionFactory.createServiceRequest(this.sparqlEndpointService.getUrl(), jenaQuery);
    qEngine.setClient(httpclient);

    ResultSet results = qEngine.execSelect();

    results.forEachRemaining(solution -> {
        markers.stream().filter(solution::contains).forEach(marker ->
                resultSet.get(marker).add(solution.get(marker).asResource().getURI()));

        unionModel.add(this.sparqlEndpointService.getModelFromResults(query, solution, schema));
    });

    SPARQLExecutionResult sparqlExecutionResult = new SPARQLExecutionResult(resultSet, unionModel);
    logger.info(sparqlExecutionResult);

    return sparqlExecutionResult;
}
 
Example #22
Source File: DispatchService.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void build() throws URISyntaxException {

        URI uri = MDSInterface2.getRoot(this);
        mHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        AuthScope authScope = new AuthScope(mHost.getHostName(), mHost.getPort());
        Credentials creds = new UsernamePasswordCredentials("username", "password");
        credsProvider.setCredentials(authScope, creds);

        mClient = new DefaultHttpClient();
        ((AbstractHttpClient) mClient).getCredentialsProvider().setCredentials(
                authScope, creds);
    }
 
Example #23
Source File: GerritRestClient.java    From gerrit-rest-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * With this impl, it only returns the same credentials once. Otherwise it's possible that a loop will occur.
 * When server returns status code 401, the HTTP client provides the same credentials forever.
 * Since we create a new HTTP client for every request, we can handle it this way.
 */
private BasicCredentialsProvider getCredentialsProvider() {
    return new BasicCredentialsProvider() {
        private Set<AuthScope> authAlreadyTried = Sets.newHashSet();

        @Override
        public Credentials getCredentials(AuthScope authscope) {
            if (authAlreadyTried.contains(authscope)) {
                return null;
            }
            authAlreadyTried.add(authscope);
            return super.getCredentials(authscope);
        }
    };
}
 
Example #24
Source File: DefaultCredentialsProvider.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public synchronized Credentials getCredentials(final AuthScope authscope) {
    if (authscope == null) {
        throw new IllegalArgumentException("Authentication scope may not be null");
    }
    return matchCredentials(credentialsMap_, authscope);
}
 
Example #25
Source File: KeycloakSPNegoSchemeFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected byte[] generateGSSToken(byte[] input, Oid oid, String authServer, Credentials credentials) throws GSSException {
    KerberosUsernamePasswordAuthenticator authenticator = new KerberosUsernamePasswordAuthenticator(kerberosConfig) {

        // Disable strict check for the configured kerberos realm, which is on super-method
        @Override
        protected String getKerberosPrincipal(String username) throws LoginException {
            if (username.contains("@")) {
                return username;
            } else {
                return username + "@" + config.getKerberosRealm();
            }
        }
    };

    try {
        Subject clientSubject = authenticator.authenticateSubject(username, password);

        ByteArrayHolder holder = Subject.doAs(clientSubject, new ClientAcceptSecContext(input, oid, authServer));

        return holder.bytes;
    } catch (Exception le) {
        throw new RuntimeException(le);
    } finally {
        authenticator.logoutSubject();
    }
}
 
Example #26
Source File: DefaultCredentialsProvider.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public synchronized void setCredentials(final AuthScope authscope, final Credentials credentials) {
    if (authscope == null) {
        throw new IllegalArgumentException("Authentication scope may not be null");
    }

    if ((credentials instanceof UsernamePasswordCredentials) || (credentials instanceof NTCredentials)) {
        credentialsMap_.put(new AuthScopeProxy(authscope), credentials);
        return;
    }

    throw new IllegalArgumentException("Unsupported Credential type: " + credentials.getClass().getName());
}
 
Example #27
Source File: RepositoriesCredentialsPersistence.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private static void saveCredentials(Properties properties, List<RemoteRepositoryCredentials> repositoriesCredentials) {
    if (validCredentials(repositoriesCredentials)) {
        for (RemoteRepositoryCredentials repositoryCredentials : repositoriesCredentials) {
            String repositoryId = repositoryCredentials.getRepositoryName();
            int id = 1;
            for (Credentials credential : repositoryCredentials.getCredentialsList()) {
                String credentialId = "" + id++;
                String username = credential.getUserPrincipal().getName();
                if (StringUtils.isNotNullAndNotEmpty(username)) {
                    String usernameKey = buildUsernameKey(repositoryId, credentialId);
                    properties.setProperty(usernameKey, username);
                } else {
                    throw new IllegalArgumentException("empty username");
                }
                String password = credential.getPassword();
                if (StringUtils.isNotNullAndNotEmpty(password)) {
                    String encryptedPassword;
                    try {
                        encryptedPassword = CryptoUtils.encrypt(password, repositoryId);
                    } catch (Exception e) {
                        throw new IllegalStateException("Failed to encrypt the password.", e);
                    }
                    String passwordKey = buildPasswordKey(repositoryId, credentialId);
                    properties.setProperty(passwordKey, encryptedPassword);
                } else {
                    throw new IllegalArgumentException("empty password");
                }
            }
        }

    } else {
        throw new IllegalArgumentException("invalid credentials (empty or duplicates)");
    }
}
 
Example #28
Source File: PreemtiveAuthorizationHttpRequestInterceptor.java    From Android-Basics-Codes with Artistic License 2.0 5 votes vote down vote up
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 (authState.getAuthScheme() == null) {
        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        Credentials creds = credsProvider.getCredentials(authScope);
        if (creds != null) {
            authState.setAuthScheme(new BasicScheme());
            authState.setCredentials(creds);
        }
    }
}
 
Example #29
Source File: AuthHelper.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
public static AuthenticationInfo createAuthenticationInfo(final String serverUri,
                                                          final Credentials credentials,
                                                          AuthenticationInfo.CredsType type) {
    return new AuthenticationInfo(
            credentials.getUserPrincipal().getName(),
            credentials.getPassword(),
            serverUri,
            credentials.getUserPrincipal().getName(),
            type,
            null
    );
}
 
Example #30
Source File: WebAuthentication.java    From fess with Apache License 2.0 5 votes vote down vote up
private Credentials getCredentials() {
    if (StringUtil.isEmpty(getUsername())) {
        throw new CrawlerSystemException("username is empty.");
    }

    if (Constants.NTLM.equals(getProtocolScheme())) {
        final Map<String, String> parameterMap = ParameterUtil.parse(getParameters());
        final String workstation = parameterMap.get("workstation");
        final String domain = parameterMap.get("domain");
        return new NTCredentials(getUsername(), getPassword(), workstation == null ? StringUtil.EMPTY : workstation,
                domain == null ? StringUtil.EMPTY : domain);
    }

    return new UsernamePasswordCredentials(getUsername(), getPassword() == null ? StringUtil.EMPTY : getPassword());
}