Search in sources :

Example 76 with PasswordAuthentication

use of java.net.PasswordAuthentication in project Bytecoder by mirkosertic.

the class EmptyInputStream method getHttpProxyAuthentication.

/**
 * Gets the authentication for an HTTP proxy, and applies it to
 * the connection.
 */
@SuppressWarnings("fallthrough")
private AuthenticationInfo getHttpProxyAuthentication(AuthenticationHeader authhdr) {
    /* get authorization from authenticator */
    AuthenticationInfo ret = null;
    String raw = authhdr.raw();
    String host = http.getProxyHostUsed();
    int port = http.getProxyPortUsed();
    if (host != null && authhdr.isPresent()) {
        HeaderParser p = authhdr.headerParser();
        String realm = p.findValue("realm");
        String scheme = authhdr.scheme();
        AuthScheme authScheme = UNKNOWN;
        if ("basic".equalsIgnoreCase(scheme)) {
            authScheme = BASIC;
        } else if ("digest".equalsIgnoreCase(scheme)) {
            authScheme = DIGEST;
        } else if ("ntlm".equalsIgnoreCase(scheme)) {
            authScheme = NTLM;
            doingNTLMp2ndStage = true;
        } else if ("Kerberos".equalsIgnoreCase(scheme)) {
            authScheme = KERBEROS;
            doingNTLMp2ndStage = true;
        } else if ("Negotiate".equalsIgnoreCase(scheme)) {
            authScheme = NEGOTIATE;
            doingNTLMp2ndStage = true;
        }
        if (realm == null)
            realm = "";
        proxyAuthKey = AuthenticationInfo.getProxyAuthKey(host, port, realm, authScheme, getAuthenticatorKey());
        ret = AuthenticationInfo.getProxyAuth(proxyAuthKey);
        if (ret == null) {
            switch(authScheme) {
                case BASIC:
                    InetAddress addr = null;
                    try {
                        final String finalHost = host;
                        addr = java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction<>() {

                            public InetAddress run() throws java.net.UnknownHostException {
                                return InetAddress.getByName(finalHost);
                            }
                        });
                    } catch (java.security.PrivilegedActionException ignored) {
                    // User will have an unknown host.
                    }
                    PasswordAuthentication a = privilegedRequestPasswordAuthentication(authenticator, host, addr, port, "http", realm, scheme, url, RequestorType.PROXY);
                    if (a != null) {
                        ret = new BasicAuthentication(true, host, port, realm, a, getAuthenticatorKey());
                    }
                    break;
                case DIGEST:
                    a = privilegedRequestPasswordAuthentication(authenticator, host, null, port, url.getProtocol(), realm, scheme, url, RequestorType.PROXY);
                    if (a != null) {
                        DigestAuthentication.Parameters params = new DigestAuthentication.Parameters();
                        ret = new DigestAuthentication(true, host, port, realm, scheme, a, params, getAuthenticatorKey());
                    }
                    break;
                case NTLM:
                    if (NTLMAuthenticationProxy.supported) {
                        /* tryTransparentNTLMProxy will always be true the first
                         * time around, but verify that the platform supports it
                         * otherwise don't try. */
                        if (tryTransparentNTLMProxy) {
                            tryTransparentNTLMProxy = NTLMAuthenticationProxy.supportsTransparentAuth;
                            /* If the platform supports transparent authentication
                             * then normally it's ok to do transparent auth to a proxy
                                         * because we generally trust proxies (chosen by the user)
                                         * But not in the case of 305 response where the server
                             * chose it. */
                            if (tryTransparentNTLMProxy && useProxyResponseCode) {
                                tryTransparentNTLMProxy = false;
                            }
                        }
                        a = null;
                        if (tryTransparentNTLMProxy) {
                            logger.finest("Trying Transparent NTLM authentication");
                        } else {
                            a = privilegedRequestPasswordAuthentication(authenticator, host, null, port, url.getProtocol(), "", scheme, url, RequestorType.PROXY);
                        }
                        /* If we are not trying transparent authentication then
                         * we need to have a PasswordAuthentication instance. For
                         * transparent authentication (Windows only) the username
                         * and password will be picked up from the current logged
                         * on users credentials.
                        */
                        if (tryTransparentNTLMProxy || (!tryTransparentNTLMProxy && a != null)) {
                            ret = NTLMAuthenticationProxy.proxy.create(true, host, port, a, getAuthenticatorKey());
                        }
                        /* set to false so that we do not try again */
                        tryTransparentNTLMProxy = false;
                    }
                    break;
                case NEGOTIATE:
                    ret = new NegotiateAuthentication(new HttpCallerInfo(authhdr.getHttpCallerInfo(), "Negotiate"));
                    break;
                case KERBEROS:
                    ret = new NegotiateAuthentication(new HttpCallerInfo(authhdr.getHttpCallerInfo(), "Kerberos"));
                    break;
                case UNKNOWN:
                    if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
                        logger.finest("Unknown/Unsupported authentication scheme: " + scheme);
                    }
                /*fall through*/
                default:
                    throw new AssertionError("should not reach here");
            }
        }
        if (ret == null && defaultAuth != null && defaultAuth.schemeSupported(scheme)) {
            try {
                URL u = new URL("http", host, port, "/");
                String a = defaultAuth.authString(u, scheme, realm);
                if (a != null) {
                    ret = new BasicAuthentication(true, host, port, realm, a, getAuthenticatorKey());
                // not in cache by default - cache on success
                }
            } catch (java.net.MalformedURLException ignored) {
            }
        }
        if (ret != null) {
            if (!ret.setHeaders(this, p, raw)) {
                ret = null;
            }
        }
    }
    if (logger.isLoggable(PlatformLogger.Level.FINER)) {
        logger.finer("Proxy Authentication for " + authhdr.toString() + " returned " + (ret != null ? ret.toString() : "null"));
    }
    return ret;
}
Also used : PrivilegedActionException(java.security.PrivilegedActionException) MalformedURLException(java.net.MalformedURLException) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) URL(java.net.URL) sun.net(sun.net) InetAddress(java.net.InetAddress) PasswordAuthentication(java.net.PasswordAuthentication)

Example 77 with PasswordAuthentication

use of java.net.PasswordAuthentication in project Bytecoder by mirkosertic.

the class EmptyInputStream method getServerAuthentication.

/**
 * Gets the authentication for an HTTP server, and applies it to
 * the connection.
 * @param authHdr the AuthenticationHeader which tells what auth scheme is
 * preferred.
 */
@SuppressWarnings("fallthrough")
private AuthenticationInfo getServerAuthentication(AuthenticationHeader authhdr) {
    /* get authorization from authenticator */
    AuthenticationInfo ret = null;
    String raw = authhdr.raw();
    /* When we get an NTLM auth from cache, don't set any special headers */
    if (authhdr.isPresent()) {
        HeaderParser p = authhdr.headerParser();
        String realm = p.findValue("realm");
        String scheme = authhdr.scheme();
        AuthScheme authScheme = UNKNOWN;
        if ("basic".equalsIgnoreCase(scheme)) {
            authScheme = BASIC;
        } else if ("digest".equalsIgnoreCase(scheme)) {
            authScheme = DIGEST;
        } else if ("ntlm".equalsIgnoreCase(scheme)) {
            authScheme = NTLM;
            doingNTLM2ndStage = true;
        } else if ("Kerberos".equalsIgnoreCase(scheme)) {
            authScheme = KERBEROS;
            doingNTLM2ndStage = true;
        } else if ("Negotiate".equalsIgnoreCase(scheme)) {
            authScheme = NEGOTIATE;
            doingNTLM2ndStage = true;
        }
        domain = p.findValue("domain");
        if (realm == null)
            realm = "";
        serverAuthKey = AuthenticationInfo.getServerAuthKey(url, realm, authScheme, getAuthenticatorKey());
        ret = AuthenticationInfo.getServerAuth(serverAuthKey);
        InetAddress addr = null;
        if (ret == null) {
            try {
                addr = InetAddress.getByName(url.getHost());
            } catch (java.net.UnknownHostException ignored) {
            // User will have addr = null
            }
        }
        // replacing -1 with default port for a protocol
        int port = url.getPort();
        if (port == -1) {
            port = url.getDefaultPort();
        }
        if (ret == null) {
            switch(authScheme) {
                case KERBEROS:
                    ret = new NegotiateAuthentication(new HttpCallerInfo(authhdr.getHttpCallerInfo(), "Kerberos"));
                    break;
                case NEGOTIATE:
                    ret = new NegotiateAuthentication(new HttpCallerInfo(authhdr.getHttpCallerInfo(), "Negotiate"));
                    break;
                case BASIC:
                    PasswordAuthentication a = privilegedRequestPasswordAuthentication(authenticator, url.getHost(), addr, port, url.getProtocol(), realm, scheme, url, RequestorType.SERVER);
                    if (a != null) {
                        ret = new BasicAuthentication(false, url, realm, a, getAuthenticatorKey());
                    }
                    break;
                case DIGEST:
                    a = privilegedRequestPasswordAuthentication(authenticator, url.getHost(), addr, port, url.getProtocol(), realm, scheme, url, RequestorType.SERVER);
                    if (a != null) {
                        digestparams = new DigestAuthentication.Parameters();
                        ret = new DigestAuthentication(false, url, realm, scheme, a, digestparams, getAuthenticatorKey());
                    }
                    break;
                case NTLM:
                    if (NTLMAuthenticationProxy.supported) {
                        URL url1;
                        try {
                            url1 = new URL(url, "/");
                        /* truncate the path */
                        } catch (Exception e) {
                            url1 = url;
                        }
                        /* tryTransparentNTLMServer will always be true the first
                         * time around, but verify that the platform supports it
                         * otherwise don't try. */
                        if (tryTransparentNTLMServer) {
                            tryTransparentNTLMServer = NTLMAuthenticationProxy.supportsTransparentAuth;
                            /* If the platform supports transparent authentication
                             * then check if we are in a secure environment
                             * whether, or not, we should try transparent authentication.*/
                            if (tryTransparentNTLMServer) {
                                tryTransparentNTLMServer = NTLMAuthenticationProxy.isTrustedSite(url);
                            }
                        }
                        a = null;
                        if (tryTransparentNTLMServer) {
                            logger.finest("Trying Transparent NTLM authentication");
                        } else {
                            a = privilegedRequestPasswordAuthentication(authenticator, url.getHost(), addr, port, url.getProtocol(), "", scheme, url, RequestorType.SERVER);
                        }
                        /* If we are not trying transparent authentication then
                         * we need to have a PasswordAuthentication instance. For
                         * transparent authentication (Windows only) the username
                         * and password will be picked up from the current logged
                         * on users credentials.
                         */
                        if (tryTransparentNTLMServer || (!tryTransparentNTLMServer && a != null)) {
                            ret = NTLMAuthenticationProxy.proxy.create(false, url1, a, getAuthenticatorKey());
                        }
                        /* set to false so that we do not try again */
                        tryTransparentNTLMServer = false;
                    }
                    break;
                case UNKNOWN:
                    if (logger.isLoggable(PlatformLogger.Level.FINEST)) {
                        logger.finest("Unknown/Unsupported authentication scheme: " + scheme);
                    }
                /*fall through*/
                default:
                    throw new AssertionError("should not reach here");
            }
        }
        if (ret == null && defaultAuth != null && defaultAuth.schemeSupported(scheme)) {
            String a = defaultAuth.authString(url, scheme, realm);
            if (a != null) {
                ret = new BasicAuthentication(false, url, realm, a, getAuthenticatorKey());
            // not in cache by default - cache on success
            }
        }
        if (ret != null) {
            if (!ret.setHeaders(this, p, raw)) {
                ret = null;
            }
        }
    }
    if (logger.isLoggable(PlatformLogger.Level.FINER)) {
        logger.finer("Server Authentication for " + authhdr.toString() + " returned " + (ret != null ? ret.toString() : "null"));
    }
    return ret;
}
Also used : UnknownHostException(java.net.UnknownHostException) URL(java.net.URL) HttpRetryException(java.net.HttpRetryException) SocketTimeoutException(java.net.SocketTimeoutException) PrivilegedActionException(java.security.PrivilegedActionException) MalformedURLException(java.net.MalformedURLException) UnknownHostException(java.net.UnknownHostException) ProtocolException(java.net.ProtocolException) sun.net(sun.net) InetAddress(java.net.InetAddress) PasswordAuthentication(java.net.PasswordAuthentication)

Example 78 with PasswordAuthentication

use of java.net.PasswordAuthentication in project tomee by apache.

the class CXFAuthenticator method getPasswordAuthentication.

protected PasswordAuthentication getPasswordAuthentication() {
    PasswordAuthentication auth = null;
    Message m = PhaseInterceptorChain.getCurrentMessage();
    if (m != null) {
        Exchange exchange = m.getExchange();
        Conduit conduit = exchange.getConduit(m);
        if (conduit instanceof HTTPConduit) {
            HTTPConduit httpConduit = (HTTPConduit) conduit;
            if (getRequestorType() == RequestorType.PROXY && httpConduit.getProxyAuthorization() != null) {
                String un = httpConduit.getProxyAuthorization().getUserName();
                String pwd = httpConduit.getProxyAuthorization().getPassword();
                if (un != null && pwd != null) {
                    auth = new PasswordAuthentication(un, pwd.toCharArray());
                }
            } else if (getRequestorType() == RequestorType.SERVER && httpConduit.getAuthorization() != null) {
                if ("basic".equals(getRequestingScheme()) || "digest".equals(getRequestingScheme())) {
                    return null;
                }
                String un = httpConduit.getAuthorization().getUserName();
                String pwd = httpConduit.getAuthorization().getPassword();
                if (un != null && pwd != null) {
                    auth = new PasswordAuthentication(un, pwd.toCharArray());
                }
            }
        }
    }
    // this HTTP call has therefore not been generated by CXF
    return auth;
}
Also used : Exchange(org.apache.cxf.message.Exchange) Message(org.apache.cxf.message.Message) Conduit(org.apache.cxf.transport.Conduit) PasswordAuthentication(java.net.PasswordAuthentication)

Example 79 with PasswordAuthentication

use of java.net.PasswordAuthentication in project jena by apache.

the class DigestLib method getUserNameAndPassword.

/**
 * Extract user and password from a {@link HttpClient}.
 */
private static Pair<String, String> getUserNameAndPassword(HttpClient httpClient) {
    Optional<Authenticator> optAuth = httpClient.authenticator();
    if (optAuth.isEmpty())
        throw new HttpException("Username/password required but not present in HttpClient");
    // We just want the PasswordAuthentication!
    PasswordAuthentication x = optAuth.get().requestPasswordAuthenticationInstance(null, null, // port,
    -1, // protocol,
    null, // prompt,
    null, // scheme,
    null, // url,
    null, RequestorType.SERVER);
    String user = x.getUserName();
    String password = new String(x.getPassword());
    return Pair.create(user, password);
}
Also used : HttpException(org.apache.jena.atlas.web.HttpException) Authenticator(java.net.Authenticator) PasswordAuthentication(java.net.PasswordAuthentication)

Example 80 with PasswordAuthentication

use of java.net.PasswordAuthentication in project twitter-2-weibo by rjyo.

the class HttpClient method getConnection.

private HttpURLConnection getConnection(String url) throws IOException {
    HttpURLConnection con = null;
    if (proxyHost != null && !proxyHost.equals("")) {
        if (proxyAuthUser != null && !proxyAuthUser.equals("")) {
            log("Proxy AuthUser: " + proxyAuthUser);
            log("Proxy AuthPassword: " + proxyAuthPassword);
            Authenticator.setDefault(new Authenticator() {

                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // respond only to proxy auth requests
                    if (getRequestorType().equals(RequestorType.PROXY)) {
                        return new PasswordAuthentication(proxyAuthUser, proxyAuthPassword.toCharArray());
                    } else {
                        return null;
                    }
                }
            });
        }
        final Proxy proxy = new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(proxyHost, proxyPort));
        if (DEBUG) {
            log("Opening proxied connection(" + proxyHost + ":" + proxyPort + ")");
        }
        con = (HttpURLConnection) new URL(url).openConnection(proxy);
    } else {
        con = (HttpURLConnection) new URL(url).openConnection();
    }
    if (connectionTimeout > 0 && !isJDK14orEarlier) {
        con.setConnectTimeout(connectionTimeout);
    }
    if (readTimeout > 0 && !isJDK14orEarlier) {
        con.setReadTimeout(readTimeout);
    }
    return con;
}
Also used : Proxy(java.net.Proxy) HttpURLConnection(java.net.HttpURLConnection) Authenticator(java.net.Authenticator) URL(java.net.URL) PasswordAuthentication(java.net.PasswordAuthentication)

Aggregations

PasswordAuthentication (java.net.PasswordAuthentication)108 Authenticator (java.net.Authenticator)52 URL (java.net.URL)27 InetSocketAddress (java.net.InetSocketAddress)22 Proxy (java.net.Proxy)19 Test (org.junit.Test)16 HttpURLConnection (java.net.HttpURLConnection)11 InetAddress (java.net.InetAddress)11 URI (java.net.URI)10 MalformedURLException (java.net.MalformedURLException)9 File (java.io.File)8 IOException (java.io.IOException)8 SocketAddress (java.net.SocketAddress)8 UnknownHostException (java.net.UnknownHostException)6 PrivilegedActionException (java.security.PrivilegedActionException)6 InputStream (java.io.InputStream)5 SocketTimeoutException (java.net.SocketTimeoutException)5 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)5 HttpRetryException (java.net.HttpRetryException)4 ProtocolException (java.net.ProtocolException)4