Example usage for org.apache.http.auth AUTH WWW_AUTH_RESP

List of usage examples for org.apache.http.auth AUTH WWW_AUTH_RESP

Introduction

In this page you can find the example usage for org.apache.http.auth AUTH WWW_AUTH_RESP.

Prototype

String WWW_AUTH_RESP

To view the source code for org.apache.http.auth AUTH WWW_AUTH_RESP.

Click Source Link

Document

The www authenticate response header.

Usage

From source file:org.apache.http.localserver.BasicAuthTokenExtractor.java

public String extract(final HttpRequest request) throws HttpException {
    String auth = null;//from   w w  w .jav a2  s.co  m

    Header h = request.getFirstHeader(AUTH.WWW_AUTH_RESP);
    if (h != null) {
        String s = h.getValue();
        if (s != null) {
            auth = s.trim();
        }
    }

    if (auth != null) {
        int i = auth.indexOf(' ');
        if (i == -1) {
            throw new ProtocolException("Invalid Authorization header: " + auth);
        }
        String authscheme = auth.substring(0, i);
        if (authscheme.equalsIgnoreCase("basic")) {
            String s = auth.substring(i + 1).trim();
            try {
                byte[] credsRaw = EncodingUtils.getAsciiBytes(s);
                BinaryDecoder codec = new Base64();
                auth = EncodingUtils.getAsciiString(codec.decode(credsRaw));
            } catch (DecoderException ex) {
                throw new ProtocolException("Malformed BASIC credentials");
            }
        }
    }
    return auth;
}

From source file:org.apache.http.localserver.RequestBasicAuth.java

public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {

    String auth = null;//  ww w  .j  ava 2  s.  c om

    Header h = request.getFirstHeader(AUTH.WWW_AUTH_RESP);
    if (h != null) {
        String s = h.getValue();
        if (s != null) {
            auth = s.trim();
        }
    }

    if (auth != null) {
        int i = auth.indexOf(' ');
        if (i == -1) {
            throw new ProtocolException("Invalid Authorization header: " + auth);
        }
        String authscheme = auth.substring(0, i);
        if (authscheme.equalsIgnoreCase("basic")) {
            String s = auth.substring(i + 1).trim();
            byte[] credsRaw = s.getBytes(HTTP.ASCII);
            BinaryDecoder codec = new Base64();
            try {
                String creds = new String(codec.decode(credsRaw), HTTP.ASCII);
                context.setAttribute("creds", creds);
            } catch (DecoderException ex) {
                throw new ProtocolException("Malformed BASIC credentials");
            }
        }
    }
}

From source file:org.flowable.ui.admin.service.engine.FlowableClientService.java

public CloseableHttpClient getHttpClient(String userName, String password) {

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));

    SSLConnectionSocketFactory sslsf = null;
    try {//w  w w  .j  a v  a 2  s. c  o m
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    } catch (Exception e) {
        LOGGER.warn("Could not configure HTTP client to use SSL", e);
    }

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    if (preemptiveBasicAuthentication) {
        String auth = userName + ":" + password;
        httpClientBuilder.setDefaultHeaders(Collections.singletonList(new BasicHeader(AUTH.WWW_AUTH_RESP,
                "Basic " + Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8)))));
    }

    if (sslsf != null) {
        httpClientBuilder.setSSLSocketFactory(sslsf);
    }

    return httpClientBuilder.build();
}

From source file:org.jboss.as.test.integration.security.common.negotiation.JBossNegotiateScheme.java

/**
 * Produces Negotiate authorization Header based on token created by processChallenge.
 *
 * @param credentials Never used be the Negotiate scheme but must be provided to satisfy common-httpclient API. Credentials
 *        from JAAS will be used instead.
 * @param request The request being authenticated
 *
 * @throws AuthenticationException if authorization string cannot be generated due to an authentication failure
 *
 * @return an Negotiate authorization Header
 *///w ww .j  a v a  2  s .c  o  m
@Override
public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context)
        throws AuthenticationException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (state == State.TOKEN_GENERATED) {
        // hack for auto redirects
        return new BasicHeader("X-dummy", "Token already generated");
    }
    if (state != State.CHALLENGE_RECEIVED) {
        throw new IllegalStateException("Negotiation authentication process has not been initiated");
    }
    try {
        String key = HttpCoreContext.HTTP_TARGET_HOST;
        HttpHost host = (HttpHost) context.getAttribute(key);
        if (host == null) {
            throw new AuthenticationException("Authentication host is not set " + "in the execution context");
        }
        String authServer;
        if (!this.stripPort && host.getPort() > 0) {
            authServer = host.toHostString();
        } else {
            authServer = host.getHostName();
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("init " + authServer);
        }
        final Oid negotiationOid = new Oid(SPNEGO_OID);

        final GSSManager manager = GSSManager.getInstance();
        final GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE);
        final GSSContext gssContext = manager.createContext(serverName.canonicalize(negotiationOid),
                negotiationOid, null, DEFAULT_LIFETIME);
        gssContext.requestMutualAuth(true);
        gssContext.requestCredDeleg(true);

        if (token == null) {
            token = new byte[0];
        }
        token = gssContext.initSecContext(token, 0, token.length);
        if (token == null) {
            state = State.FAILED;
            throw new AuthenticationException("GSS security context initialization failed");
        }

        state = State.TOKEN_GENERATED;
        String tokenstr = new String(base64codec.encode(token));
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Sending response '" + tokenstr + "' back to the auth server");
        }
        CharArrayBuffer buffer = new CharArrayBuffer(32);
        if (isProxy()) {
            buffer.append(AUTH.PROXY_AUTH_RESP);
        } else {
            buffer.append(AUTH.WWW_AUTH_RESP);
        }
        buffer.append(": Negotiate ");
        buffer.append(tokenstr);
        return new BufferedHeader(buffer);
    } catch (GSSException gsse) {
        state = State.FAILED;
        if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL
                || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED)
            throw new InvalidCredentialsException(gsse.getMessage(), gsse);
        if (gsse.getMajor() == GSSException.NO_CRED)
            throw new InvalidCredentialsException(gsse.getMessage(), gsse);
        if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN
                || gsse.getMajor() == GSSException.OLD_TOKEN)
            throw new AuthenticationException(gsse.getMessage(), gsse);
        // other error
        throw new AuthenticationException(gsse.getMessage());
    }
}