Example usage for com.google.common.net HttpHeaders AUTHORIZATION

List of usage examples for com.google.common.net HttpHeaders AUTHORIZATION

Introduction

In this page you can find the example usage for com.google.common.net HttpHeaders AUTHORIZATION.

Prototype

String AUTHORIZATION

To view the source code for com.google.common.net HttpHeaders AUTHORIZATION.

Click Source Link

Document

The HTTP Authorization header field name.

Usage

From source file:org.haiku.haikudepotserver.security.AuthenticationFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authorizationHeader = httpRequest.getHeader(HttpHeaders.AUTHORIZATION);
    Optional<ObjectId> authenticatedUserObjectId = Optional.empty();

    if (!Strings.isNullOrEmpty(authorizationHeader)) {

        Matcher authorizationMatcher = PATTERN_AUTHORIZATION_HEADER.matcher(authorizationHeader);

        if (authorizationMatcher.matches()) {

            switch (authorizationMatcher.group(1)) {

            case "Basic":
                byte[] usernamePasswordBytes = Base64.getDecoder().decode(authorizationMatcher.group(2));

                if (null != usernamePasswordBytes && usernamePasswordBytes.length >= 3) {
                    List<String> parts = new ArrayList<>();
                    Splitter.on(":").split(new String(usernamePasswordBytes, Charsets.UTF_8))
                            .forEach(parts::add);

                    if (2 == parts.size()) {
                        authenticatedUserObjectId = authenticationService
                                .authenticateByNicknameAndPassword(parts.get(0), parts.get(1));
                    } else {
                        LOGGER.warn(/*ww  w .j ava2  s .c o m*/
                                "attempt to process an authorization header, but the username password is malformed; is not <username>:<password>");
                    }
                } else {
                    LOGGER.warn(
                            "attempt to process an authorization header, but the username password is malformed; being decoded from base64");
                }
                break;

            case "Bearer":
                authenticatedUserObjectId = authenticationService
                        .authenticateByToken(authorizationMatcher.group(2));
                break;

            default:
                LOGGER.warn(
                        "attempt to process an authorization header, but the authorization method {} is unknown :. ignoring",
                        authorizationMatcher.group(1));
                break;

            }
        } else {
            LOGGER.warn("attempt to process an authorization header, but it is malformed :. ignoring");
        }
    }

    // if the user was not authenticated on the header, under certain circumstances, it may be possible for
    // the authentication to occur based on a parameter of the GET request (in the query).

    if (!authenticatedUserObjectId.isPresent() && httpRequest.getMethod().equals("GET")) {
        String filterPathInfo = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());

        if (filterPathInfo.startsWith("/" + SEGMENT_SECURED + "/")) {
            String param = httpRequest.getParameter(PARAM_BEARER_TOKEN);

            if (!Strings.isNullOrEmpty(param)) {
                authenticatedUserObjectId = authenticationService.authenticateByToken(param);
            }
        }
    }

    // now continue with the rest of the servlet filter chain, keeping the thread local

    try {
        AuthenticationHelper.setAuthenticatedUserObjectId(authenticatedUserObjectId.orElse(null));
        chain.doFilter(request, response);
    } finally {
        AuthenticationHelper.setAuthenticatedUserObjectId(null);
    }
}

From source file:com.cdancy.artifactory.rest.filters.ArtifactoryAuthentication.java

@Override
public HttpRequest filter(HttpRequest request) throws HttpException {
    Credentials currentCreds = checkNotNull(creds.get(), "credential supplier returned null");
    if (currentCreds.credential == null) {
        throw new AuthorizationException("Credentials credential can not be null");
    }/*  w w w  . jav  a  2s . c om*/

    /*
     * client can pass in credential string in 1 of 3 ways:
     * 
     * 1.) As colon delimited username and password: admin:password
     * 
     * 2.) As base64 encoded value of colon delimited username and password:
     * YWRtaW46cGFzc3dvcmQ=
     * 
     * 3.) As JFrog api key which can be obtained from Artifactory portal:
     * 
     * AKCp2TfiyqrqHmfzUzeQhJmQrDyEx1o2S25pcC2hLzCTu65rpVhEoL1G6ppHn4exmHYfCiyT4
     */
    String foundCredential = currentCreds.credential;
    boolean isbase64 = false;
    if (foundCredential.contains(":")) {
        foundCredential = base64().encode(foundCredential.getBytes());
        isbase64 = true;
    }

    boolean useBasicAuth = isbase64 ? true : isBase64Encoded(foundCredential);
    if (useBasicAuth) {
        return request.toBuilder().addHeader(HttpHeaders.AUTHORIZATION, "Basic " + foundCredential).build();
    } else {
        return request.toBuilder().addHeader("X-JFrog-Art-Api", foundCredential).build();
    }
}

From source file:com.eucalyptus.objectstorage.policy.AuthTypeKey.java

private String getAuthType() throws AuthException {
    final AccessKeyCredential credential = getAccessKeyCredential();
    if (credential != null)
        try { // ensure access key credential was used to authenticate
            final Context context = Contexts.lookup();
            final MappingHttpRequest request = context.getHttpRequest();
            if (context.getChannel().getPipeline()
                    .get(ObjectStorageFormPOSTAuthenticationHandler.class) != null) {
                return "POST";
            } else if (context.getChannel().getPipeline()
                    .get(ObjectStorageAuthenticationHandler.class) != null) {
                if (request.containsHeader(HttpHeaders.AUTHORIZATION)) {
                    return "REST-HEADER";
                } else {
                    return "REST-QUERY-STRING";
                }// ww w.j a v a 2  s .  c om
            }
        } catch (final Exception e) {
            Exceptions.findAndRethrow(e, AuthException.class);
            throw new AuthException("Error getting value for s3 authType condition", e);
        }
    return null;
}

From source file:org.icgc.dcc.portal.auth.UserAuthInjectable.java

private static String resolveAccessToken(HttpContext httpContext) {
    val headers = httpContext.getRequest().getRequestHeader(HttpHeaders.AUTHORIZATION);

    String token = null;//from  w  ww.  j  a va 2 s  . c o  m

    try {
        // Typically there is only one (most servers enforce that)
        for (val value : headers)
            if ((value.toLowerCase().startsWith(AUTH_BEARER_TYPE.toLowerCase()))) {
                val authHeaderValue = value.substring(AUTH_BEARER_TYPE.length()).trim();
                int commaIndex = authHeaderValue.indexOf(',');
                if (commaIndex > 0) {
                    token = authHeaderValue.substring(0, commaIndex);
                } else {
                    token = authHeaderValue;
                }
            }
    } catch (NullPointerException e) {
        log.debug("No OAuth access token passed in request");
    } catch (Exception e) {
        log.debug("Invalid OAuth access token passed in request");
    }

    return token;
}

From source file:org.jenkinsci.plugins.kubernetesworkflowsteps.KubeStepExecution.java

private static CloseableHttpClient getClient()
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    if (client == null) {
        synchronized (client_lock) {
            if (client == null) {
                SSLContextBuilder builder = SSLContexts.custom();
                builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

                SSLContext sslContext = builder.build();

                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

                Collection<BasicHeader> headers = new ArrayList<BasicHeader>();
                headers.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
                headers.add(new BasicHeader(HttpHeaders.AUTHORIZATION, "Bearer " + env.get("BEARER_TOKEN")));

                client = HttpClients.custom().setDefaultHeaders(headers).setSSLSocketFactory(sslsf).build();
            }//from   ww w.  j  a  v a  2s.c  om
        }
    }
    return client;
}

From source file:com.ibm.watson.app.common.services.box.impl.BoxRestClient.java

/**
 * We need to add the access token as an auth header to every call
 *//*from  ww  w .ja  v  a2 s .c om*/
@Override
protected <T> T doGet(HttpGet httpget, ResponseHandler<? extends T> responseHandler) throws IOException {
    httpget.addHeader(new BasicHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken));
    return super.doGet(httpget, responseHandler);
}

From source file:org.codice.ddf.admin.sources.wfs.WfsSourceUtils.java

public UrlAvailability getUrlAvailability(String url, String un, String pw) {
    UrlAvailability result = new UrlAvailability(url);
    int status;//from  ww  w  . j ava2  s.c  om
    String contentType;
    url += GET_CAPABILITIES_PARAMS;
    HttpGet request = new HttpGet(url);
    CloseableHttpResponse response = null;
    CloseableHttpClient client = null;
    if (url.startsWith("https") && un != null && pw != null) {
        byte[] auth = Base64.encodeBase64((un + ":" + pw).getBytes());
        request.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(auth));
    }
    try {
        client = getCloseableHttpClient(false);
        response = client.execute(request);
        status = response.getStatusLine().getStatusCode();
        contentType = response.getEntity().getContentType().getValue();
        if (status == HTTP_OK && WFS_MIME_TYPES.contains(contentType)) {
            return result.trustedCertAuthority(true).certError(false).available(true);
        } else {
            return result.trustedCertAuthority(true).certError(false).available(false);
        }
    } catch (SSLPeerUnverifiedException e) {
        // This is the hostname != cert name case - if this occurs, the URL's SSL cert configuration
        // is incorrect, or a serious network security issue has occurred.
        return result.trustedCertAuthority(false).certError(true).available(false);
    } catch (Exception e) {
        try {
            closeClientAndResponse(client, response);
            client = getCloseableHttpClient(true);
            response = client.execute(request);
            status = response.getStatusLine().getStatusCode();
            contentType = response.getEntity().getContentType().getValue();
            if (status == HTTP_OK && WFS_MIME_TYPES.contains(contentType)) {
                return result.trustedCertAuthority(false).certError(false).available(true);
            }
        } catch (Exception e1) {
            return result.trustedCertAuthority(false).certError(false).available(false);
        }
    } finally {
        closeClientAndResponse(client, response);
    }
    return result;
}

From source file:org.codice.ddf.admin.sources.opensearch.OpenSearchSourceUtils.java

public UrlAvailability getUrlAvailability(String url, String un, String pw) {
    UrlAvailability result = new UrlAvailability(url);
    boolean queryResponse;
    int status;/* ww w . j  a v  a 2s  .  co  m*/
    String contentType;
    HttpGet request = new HttpGet(url + SIMPLE_QUERY_PARAMS);
    CloseableHttpResponse response = null;
    CloseableHttpClient client = null;

    if (url.startsWith("https") && un != null && pw != null) {
        byte[] auth = Base64.encodeBase64((un + ":" + pw).getBytes());
        request.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(auth));
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(SOURCES_NAMESPACE_CONTEXT);
    try {
        client = getCloseableHttpClient(false);
        response = client.execute(request);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document responseXml = builder.parse(response.getEntity().getContent());
        queryResponse = (Boolean) xpath.compile(TOTAL_RESULTS_XPATH).evaluate(responseXml,
                XPathConstants.BOOLEAN);
        status = response.getStatusLine().getStatusCode();
        contentType = response.getEntity().getContentType().getValue();
        if (status == HTTP_OK && OPENSEARCH_MIME_TYPES.contains(contentType) && queryResponse) {
            return result.trustedCertAuthority(true).certError(false).available(true);
        } else {
            return result.trustedCertAuthority(true).certError(false).available(false);
        }
    } catch (SSLPeerUnverifiedException e) {
        // This is the hostname != cert name case - if this occurs, the URL's SSL cert configuration
        // is incorrect, or a serious network security issue has occurred.
        return result.trustedCertAuthority(false).certError(true).available(false);
    } catch (Exception e) {
        try {
            closeClientAndResponse(client, response);
            client = getCloseableHttpClient(true);
            response = client.execute(request);
            status = response.getStatusLine().getStatusCode();
            contentType = response.getEntity().getContentType().getValue();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document responseXml = builder.parse(response.getEntity().getContent());
            queryResponse = (Boolean) xpath.compile(TOTAL_RESULTS_XPATH).evaluate(responseXml,
                    XPathConstants.BOOLEAN);
            if (status == HTTP_OK && OPENSEARCH_MIME_TYPES.contains(contentType) && queryResponse) {
                return result.trustedCertAuthority(false).certError(false).available(true);
            }
        } catch (Exception e1) {
            return result.trustedCertAuthority(false).certError(false).available(false);
        }
    } finally {
        closeClientAndResponse(client, response);
    }
    return result;
}

From source file:nl.knaw.huygens.security.client.HuygensAuthenticationHandler.java

private HttpRequest sessionRequest(String verb, String sessionToken) {
    HttpRequest resource = new HttpRequest(verb, authorizationUrl).withExtraPath(SESSION_AUTHENTICATION_URI)
            .withExtraPath("/" + sessionToken).withHeader(HttpHeaders.AUTHORIZATION, basicCredentials);

    return resource;
}

From source file:de.borntohula.dropwizard.auth.jwt.JwtAuthFactory.java

@Override
public T provide() {
    try {//from  w  w  w  .  ja  va 2s  . c o m
        final String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (header != null) {
            final int separator = header.indexOf(' ');
            if (separator > 0) {
                final String method = header.substring(0, separator);
                if (prefix.equalsIgnoreCase(method)) {
                    final String jwt = header.substring(separator + 1);
                    final Optional<T> result = authenticator().authenticate(jwt);
                    if (result.isPresent()) {
                        return result.get();
                    }
                }
            }
        }
    } catch (AuthenticationException ex) {
        LOG.warn("Error while authenticating credentials", ex);
        throw new InternalServerErrorException();
    }

    if (required) {
        throw new WebApplicationException(unauthorizedHandler.buildResponse(prefix, realm));
    }

    return null;
}