Example usage for org.springframework.http HttpHeaders AUTHORIZATION

List of usage examples for org.springframework.http HttpHeaders AUTHORIZATION

Introduction

In this page you can find the example usage for org.springframework.http HttpHeaders AUTHORIZATION.

Prototype

String AUTHORIZATION

To view the source code for org.springframework.http HttpHeaders AUTHORIZATION.

Click Source Link

Document

The HTTP Authorization header field name.

Usage

From source file:com.muk.services.api.impl.StripePaymentService.java

private ResponseEntity<JsonNode> send(String path, JsonNode payload) {
    final HttpHeaders headers = new HttpHeaders();

    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.add(HttpHeaders.AUTHORIZATION, getTokenHeader());

    final MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
    final Iterator<Entry<String, JsonNode>> nodes = payload.fields();

    while (nodes.hasNext()) {
        final Map.Entry<String, JsonNode> entry = nodes.next();

        if (entry.getValue().isObject()) {
            final String key = entry.getKey();
            final Iterator<Entry<String, JsonNode>> metadataNodes = entry.getValue().fields();

            while (metadataNodes.hasNext()) {
                final Map.Entry<String, JsonNode> element = metadataNodes.next();
                body.add(key + "[\"" + element.getKey() + "\"]", element.getValue().asText());
            }//w ww  .j a  v a2  s.c om
        } else {
            body.add(entry.getKey(), entry.getValue().asText());
        }
    }

    return restTemplate.postForEntity(securityCfgService.getStripeUri() + path,
            new HttpEntity<MultiValueMap<String, String>>(body, headers), JsonNode.class);
}

From source file:com.oneops.antenna.senders.generic.HTTPMsgService.java

/**
 * Posts the message to http endpoint//ww w. ja  v a2  s .  c o m
 *
 * @param msg the notification message
 * @param sub URL subscriber
 * @return <code>true</code> if response code is 200, else return <code>false</code>
 */
@Override
public boolean postMessage(NotificationMessage msg, BasicSubscriber sub) {
    URLSubscriber urlSub = (URLSubscriber) sub;
    boolean isHpom = urlSub.hasHpomXfmr();

    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost req = new HttpPost(urlSub.getUrl());
    req.setEntity(new StringEntity(gson.toJson(msg), ContentType.APPLICATION_JSON));

    int timeout = urlSub.getTimeout();
    req.setConfig(RequestConfig.custom().setSocketTimeout(timeout > 0 ? timeout : 2000).build());
    String userName = urlSub.getUserName();
    if (userName != null && StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(urlSub.getPassword())) {
        String auth = userName + ":" + urlSub.getPassword();
        req.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.encodeBase64(auth.getBytes())));
    }

    try (CloseableHttpResponse res = httpClient.execute(req)) {
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            countOK(isHpom);
            return true;
        } else {
            logger.warn(isHpom ? "HPOM"
                    : "HTTP" + " message post response code: " + res.getStatusLine().getStatusCode()
                            + " for URL sink: " + urlSub.getName());
        }
    } catch (IOException ex) {
        logger.error(isHpom ? "HPOM" : "HTTP" + " message post failed." + ex.getMessage());
    }

    countErr(isHpom);
    return false;
}

From source file:eu.europa.ec.grow.espd.ted.TedService.java

private HttpHeaders createHeaders(final String username, final String password) {
    String plainCreds = username + ":" + password;
    String base64Creds = BaseEncoding.base64().encode(plainCreds.getBytes());

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.AUTHORIZATION, "Basic " + base64Creds);
    headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
    return headers;
}

From source file:io.syndesis.runtime.BaseITCase.java

private void prepareHeaders(Object body, HttpHeaders headers, String token) {
    if (body != null) {
        headers.set(HttpHeaders.CONTENT_TYPE, "application/json");
    }/*w w w .j  a  va  2 s.c o m*/
    if (token != null) {
        headers.set(HttpHeaders.AUTHORIZATION, "Bearer " + token);
    }
}

From source file:net.shibboleth.idp.authn.spnego.impl.SPNEGOAuthnController.java

/**
 * Process an input GSS token from the client and attempt to complete the context establishment process.
 * /* www .j  a v  a2s  .  c o m*/
 * @param conversationKey the conversation key
 * @param authorizationHeader the token from the client
 * @param httpRequest the HTTP request
 * @param httpResponse the HTTP response
 * 
 * @return the response view
 * @throws ExternalAuthenticationException 
 * @throws IOException 
 */
@RequestMapping(value = "/{conversationKey}", method = RequestMethod.GET, headers = "Authorization")
@Nullable
public ModelAndView continueSPNEGO(@PathVariable @Nonnull @NotEmpty final String conversationKey,
        @RequestHeader(HttpHeaders.AUTHORIZATION) @Nonnull @NotEmpty final String authorizationHeader,
        @Nonnull final HttpServletRequest httpRequest, @Nonnull final HttpServletResponse httpResponse)
        throws ExternalAuthenticationException, IOException {

    final ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(conversationKey,
            httpRequest);

    if (!authorizationHeader.startsWith("Negotiate ")) {
        return replyUnauthorizedNegotiate(prc, httpRequest, httpResponse);
    }

    final SPNEGOContext spnegoCtx = getSPNEGOContext(prc);
    if (spnegoCtx == null || spnegoCtx.getKerberosSettings() == null) {
        log.error("Kerberos settings not found in profile request context");
        finishWithError(conversationKey, httpRequest, httpResponse, AuthnEventIds.INVALID_AUTHN_CTX);
        return null;
    }

    GSSContextAcceptor acceptor = spnegoCtx.getContextAcceptor();
    if (acceptor == null) {
        try {
            acceptor = createGSSContextAcceptor(spnegoCtx);
            spnegoCtx.setContextAcceptor(acceptor);
        } catch (final GSSException e) {
            log.error("Unable to create GSSContextAcceptor", e);
            finishWithException(conversationKey, httpRequest, httpResponse,
                    new ExternalAuthenticationException(SPNEGO_NOT_AVAILABLE, e));
            return null;
        }
    }

    final byte[] gssapiData = Base64.decodeBase64(authorizationHeader.substring(10).getBytes());
    log.trace("SPNEGO negotiation, Authorization header received, gssapi-data: {}", gssapiData);

    // NTLM Authentication is not supported.
    if (isNTLMMechanism(gssapiData)) {
        log.warn("NTLM is unsupported, failing context negotiation");
        acceptor.logout();
        finishWithError(conversationKey, httpRequest, httpResponse, NTLM_UNSUPPORTED);
        return null;
    }

    byte[] tokenBytes;
    try {
        tokenBytes = acceptor.acceptSecContext(gssapiData, 0, gssapiData.length);
        log.trace("GSS token accepted");
    } catch (final Exception e) {
        log.debug("Exception processing GSS token", e);
        acceptor.logout();
        finishWithException(conversationKey, httpRequest, httpResponse,
                new ExternalAuthenticationException(SPNEGO_NOT_AVAILABLE, e));
        return null;
    }

    // If the context is established, we can attempt to retrieve the name of the "context initiator."
    // In the case of the Kerberos mechanism, the context initiator is the Kerberos principal of the client.
    if (acceptor.getContext() != null && acceptor.getContext().isEstablished()) {
        log.debug("GSS security context is complete");
        try {
            final GSSName clientGSSName = acceptor.getContext().getSrcName();
            if (clientGSSName == null) {
                // This case should never happen, but we observed it. Handle it as authentication failure.
                log.error("Error extracting principal name from security context");
                acceptor.logout();
                finishWithException(conversationKey, httpRequest, httpResponse,
                        new ExternalAuthenticationException(SPNEGO_NOT_AVAILABLE));
                return null;
            }
            final KerberosPrincipal kerberosPrincipal = new KerberosPrincipal(clientGSSName.toString());

            log.info("SPNEGO/Kerberos authentication succeeded for principal: {}", clientGSSName.toString());

            acceptor.logout();
            finishWithSuccess(conversationKey, httpRequest, httpResponse, kerberosPrincipal);
        } catch (final GSSException e) {
            log.error("Error extracting principal name from security context", e);
            acceptor.logout();
            finishWithException(conversationKey, httpRequest, httpResponse,
                    new ExternalAuthenticationException(SPNEGO_NOT_AVAILABLE, e));
        }
    } else {
        // The context is not complete yet.
        // return "WWW-Authenticate: Negotiate <data>" to the browser
        log.trace("SPNEGO negotiation in process, output token: {}", tokenBytes);
        return replyUnauthorizedNegotiate(prc, httpRequest, httpResponse,
                Base64.encodeBase64String(tokenBytes));
    }

    return null;
}

From source file:org.apereo.portal.security.oauth.IdTokenFactory.java

public String getBearerToken(HttpServletRequest request) {
    final String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
    logger.debug("{} header value:  {}", HttpHeaders.AUTHORIZATION, authorization);
    return StringUtils.isNotBlank(authorization)
            && authorization.length() > Headers.BEARER_TOKEN_PREFIX.length()
                    ? authorization.substring(Headers.BEARER_TOKEN_PREFIX.length())
                    : null;//from w w  w  . j  a  va2  s  .  c o  m
}

From source file:org.apereo.portal.soffit.security.SoffitApiPreAuthenticatedProcessingFilter.java

@Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {

    final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
    if (StringUtils.isBlank(authHeader) || !authHeader.startsWith(Headers.BEARER_TOKEN_PREFIX)) {
        /*/*from   w  w w . ja v a 2 s  .com*/
         * In authenticating the user, this filter has no opinion if either (1) the
         * Authorization header is not set or (2) the value isn't a Bearer token.
         */
        return null;
    }

    final String bearerToken = authHeader.substring(Headers.BEARER_TOKEN_PREFIX.length());

    try {
        // Validate & parse the JWT
        final Jws<Claims> claims = Jwts.parser().setSigningKey(signatureKey).parseClaimsJws(bearerToken);

        logger.debug("Found the following pre-authenticated user:  {}", claims.toString());

        final List<String> groupsClaim = claims.getBody().get("groups", List.class);
        final List<String> groupsList = groupsClaim != null ? groupsClaim : Collections.emptyList();
        final UserDetails rslt = new SoffitApiUserDetails(claims.getBody().getSubject(), groupsList);
        request.setAttribute(USER_DETAILS_REQUEST_ATTRIBUTE, rslt);
        return rslt;
    } catch (Exception e) {
        logger.info("The following Bearer token is unusable:  '{}'", bearerToken);
        logger.debug("Failed to validate and/or parse the specified Bearer token", e);
    }

    return null;
}

From source file:org.cloudfoundry.identity.client.UaaContextFactory.java

protected UaaContext fetchTokenFromCode(final TokenRequest request) {
    String clientBasicAuth = getClientBasicAuthHeader(request);

    RestTemplate template = new RestTemplate();
    if (request.isSkipSslValidation()) {
        template.setRequestFactory(getNoValidatingClientHttpRequestFactory());
    }/*  ww  w  .j  a va2  s.com*/
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.AUTHORIZATION, clientBasicAuth);
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.add(OAuth2Utils.GRANT_TYPE, "authorization_code");
    form.add(OAuth2Utils.REDIRECT_URI, request.getRedirectUri().toString());
    String responseType = "token";
    if (request.wantsIdToken()) {
        responseType += " id_token";
    }
    form.add(OAuth2Utils.RESPONSE_TYPE, responseType);
    form.add("code", request.getAuthorizationCode());

    ResponseEntity<CompositeAccessToken> token = template.exchange(request.getTokenEndpoint(), HttpMethod.POST,
            new HttpEntity<>(form, headers), CompositeAccessToken.class);
    return new UaaContextImpl(request, null, token.getBody());
}

From source file:org.jasig.portlet.notice.filter.ApiUrlSupportFilter.java

private String getBearerToken(HttpServletRequest request) {
    String rslt = ""; // default
    final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
    if (StringUtils.isNotBlank(authHeader)) { // Authorization header is present?
        if (authHeader.startsWith(Headers.BEARER_TOKEN_PREFIX)) { // Authorization header is a Bearer token?
            rslt = authHeader.substring(Headers.BEARER_TOKEN_PREFIX.length());
        }/*ww w . j  a v a2  s  . com*/
    }
    return rslt;
}

From source file:org.jasig.portlet.notice.service.jdbc.AbstractJdbcNotificationService.java

/**
 * General-purpose implementation of this method that wraps the OIDC Id token in an
 * {@link SqlParameterSource}.  Subclasses <em>may</em> override this method to provide a custom
 * {@link SqlParameterSource} when needed.
 *//*from  www . j  a  v  a2 s.c o m*/
protected SqlParameterSource getSqlParameterSource(HttpServletRequest request) {

    final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
    if (StringUtils.isBlank(authHeader) || !authHeader.startsWith(Headers.BEARER_TOKEN_PREFIX)) {
        // No attribute without JWT...
        return EmptySqlParameterSource.INSTANCE;
    }

    final String bearerToken = authHeader.substring(Headers.BEARER_TOKEN_PREFIX.length());

    try {
        // Validate & parse the JWT
        final Jws<Claims> claims = Jwts.parser().setSigningKey(signatureKey).parseClaimsJws(bearerToken);
        // Convert to MapSqlParameterSource
        Map<String, Object> map = new HashMap<>();
        claims.getBody().entrySet().forEach(entry -> {
            final Object value = entry.getValue();
            if (List.class.isInstance(value) && ((List<Object>) value).size() != 0) {
                map.put(entry.getKey(), ((List<Object>) value).get(0));
            } else {
                map.put(entry.getKey(), value);
            }
        });
        return new MapSqlParameterSource(map);
    } catch (Exception e) {
        logger.warn("The specified Bearer token is unusable:  '{}'", bearerToken);
        logger.debug("Failed to validate and/or parse the specified Bearer token", e);
    }

    return EmptySqlParameterSource.INSTANCE;

}