Java Code Examples for org.apache.http.auth.Credentials#getPassword()

The following examples show how to use org.apache.http.auth.Credentials#getPassword() . 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: JolokiaClientFactory.java    From hawkular-agent with Apache License 2.0 6 votes vote down vote up
@Override
public Header authenticate(Credentials credentials, HttpRequest request, HttpContext context)
        throws AuthenticationException {
    Args.notNull(credentials, "Credentials");
    Args.notNull(request, "HTTP request");

    // the bearer token is stored in the password field, not credentials.getUserPrincipal().getName()
    String bearerToken = credentials.getPassword();

    CharArrayBuffer buffer = new CharArrayBuffer(64);
    if (isProxy()) {
        buffer.append("Proxy-Authorization");
    } else {
        buffer.append("Authorization");
    }
    buffer.append(": Bearer ");
    buffer.append(bearerToken);

    return new BufferedHeader(buffer);
}
 
Example 2
Source File: HttpFeed.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public Map<String, String> buildBaseHeaders() {
    if (Boolean.TRUE.equals(preemptiveBasicAuth)) {
        Credentials creds = credentials;
        if (creds == null) {
            throw new IllegalArgumentException("Must not enable preemptiveBasicAuth when there are no credentials, in feed for "+baseUri);
        }
        String username = checkNotNull(creds.getUserPrincipal().getName(), "username");
        if (username == null) {
            throw new IllegalArgumentException("Must not enable preemptiveBasicAuth when username is null, in feed for "+baseUri);
        }
        if (username.contains(":")) {
            throw new IllegalArgumentException("Username must not contain colon when preemptiveBasicAuth is enabled, in feed for "+baseUri);
        }
        
        String password = creds.getPassword();
        String toencode = username + ":" + (password == null ? "" : password);
        String headerVal = "Basic " + BaseEncoding.base64().encode((toencode).getBytes(StandardCharsets.UTF_8));
        
        return ImmutableMap.<String,String>builder()
                .put("Authorization", headerVal)
                .putAll(checkNotNull(headers, "headers"))
                .build();
    } else {
        return ImmutableMap.copyOf(checkNotNull(headers, "headers"));
    }
}
 
Example 3
Source File: RemoteRepositoryCredentials.java    From snap-desktop with GNU General Public License v3.0 6 votes vote down vote up
private int findCredential(String targetUser, String targetPassword) {
    int matchesCount = 0;
    for (Credentials credential : credentialsList) {
        String username = credential.getUserPrincipal().getName();
        String password = credential.getPassword();
        if (StringUtils.isNotNullAndNotEmpty(targetUser)) {
            if (targetUser.equals(username)) {
                if (StringUtils.isNotNullAndNotEmpty(targetPassword)) {
                    if (targetPassword.equals(password)) {
                        matchesCount++;
                    }
                } else {
                    matchesCount++;
                }
            }
        } else {
            if (StringUtils.isNotNullAndNotEmpty(targetPassword) && targetPassword.equals(password)) {
                matchesCount++;
            }
        }
    }
    return matchesCount;
}
 
Example 4
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 5
Source File: HttpService.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public static void upload(URI uri, Credentials auth, File src, String description) throws IOException {
   String cred = auth.getUserPrincipal().getName()+":"+auth.getPassword();
   String encoding = Base64.encodeBase64String(cred.getBytes());
   HttpPost httppost = new HttpPost(uri);
   // Add in authentication
   httppost.setHeader("Authorization", "Basic " + encoding);
   FileBody data = new FileBody(src);
   StringBody text = new StringBody(description, ContentType.TEXT_PLAIN);

   // Build up multi-part form
   HttpEntity reqEntity = MultipartEntityBuilder.create()
           .addPart("upload", data)
           .addPart("comment", text)
           .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
           .build();
   httppost.setEntity(reqEntity);

   // Execute post and get response
   CloseableHttpClient client = get();
   CloseableHttpResponse response = client.execute(httppost);
   try {
       HttpEntity resEntity = response.getEntity();
       EntityUtils.consume(resEntity);
   } finally {
       response.close();
   }
}
 
Example 6
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 7
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 8
Source File: RepositoriesCredentialsControllerUI.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private static List<RemoteRepositoryCredentials> createCopy(List<RemoteRepositoryCredentials> repositoriesCredentialsSource) {
    List<RemoteRepositoryCredentials> repositoriesCredentialsCopy = new ArrayList<>();
    for (RemoteRepositoryCredentials repositoryCredentialsSource : repositoriesCredentialsSource) {
        List<Credentials> credentialsCopy = new ArrayList<>();
        for (Credentials credentialsSource : repositoryCredentialsSource.getCredentialsList()) {
            UsernamePasswordCredentials repositoryCredential = new UsernamePasswordCredentials(credentialsSource.getUserPrincipal().getName(), credentialsSource.getPassword());
            credentialsCopy.add(repositoryCredential);
        }
        repositoriesCredentialsCopy.add(new RemoteRepositoryCredentials(repositoryCredentialsSource.getRepositoryName(), credentialsCopy));
    }
    return repositoriesCredentialsCopy;
}
 
Example 9
Source File: ApiClient.java    From spring-hmac-rest with MIT License 4 votes vote down vote up
public <I, O extends AbstractResponseWrapper<I>> O echo(I request, Class<O> clazz) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        final AuthScope authScope = new AuthScope(host, port, AuthScope.ANY_REALM, scheme);
        final Credentials credentials = credentialsProvider.getCredentials(authScope);

        if (credentials == null) {
            throw new RuntimeException("Can't find credentials for AuthScope: " + authScope);
        }

        String apiKey = credentials.getUserPrincipal().getName();
        String apiSecret = credentials.getPassword();

        String nonce = UUID.randomUUID().toString();

        headers.setDate(clock.millis());
        String dateString = headers.getFirst(HttpHeaders.DATE);

        RequestWrapper<I> requestWrapper = new RequestWrapper<>(request);
        requestWrapper.setData(request);

        final String valueAsString;
        try {
            valueAsString = objectMapper.writeValueAsString(requestWrapper);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        final String resource = "/api/echo";
        final HmacSignatureBuilder signatureBuilder = new HmacSignatureBuilder()
                .scheme(scheme)
                .host(host+":" + port)
                .method("POST")
                .resource(resource)
                .apiKey(apiKey)
                .contentType(MediaType.APPLICATION_JSON_VALUE)
                .nonce(nonce)
                .date(dateString)
                .apiSecret(apiSecret)
                .payload(valueAsString.getBytes(StandardCharsets.UTF_8));
        final String signature = signatureBuilder
                .buildAsBase64String();

        final String authHeader = signatureBuilder.getAlgorithm() + " " + apiKey + ":" + nonce + ":" + signature;
        headers.add(HttpHeaders.AUTHORIZATION, authHeader);

        headers.add(HttpHeaders.USER_AGENT, USER_AGENT);

        HttpEntity<String> entity = new HttpEntity<>(valueAsString, headers);

        final O payloadWrapper = restTemplate.postForObject(
                scheme + "://" + host + ":" + port + resource,
                entity,
                clazz);

        return payloadWrapper;
    }
 
Example 10
Source File: RemoteRepositoryCredentials.java    From snap-desktop with GNU General Public License v3.0 4 votes vote down vote up
public boolean credentialInvalid(Credentials credential) {
    String username = credential.getUserPrincipal().getName();
    String password = credential.getPassword();
    return StringUtils.isNullOrEmpty(username) || StringUtils.isNullOrEmpty(password) || credentialDuplicate(username);
}