Search in sources :

Example 31 with AuthScope

use of org.apache.commons.httpclient.auth.AuthScope in project sling by apache.

the class GetNodeContentCommand method execute.

@Override
public Result<ResourceProxy> execute() {
    GetMethod get = new GetMethod(getPath());
    try {
        httpClient.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(repositoryInfo.getUsername(), repositoryInfo.getPassword());
        httpClient.getState().setCredentials(new AuthScope(repositoryInfo.getHost(), repositoryInfo.getPort(), AuthScope.ANY_REALM), defaultcreds);
        int responseStatus = httpClient.executeMethod(get);
        // return EncodingUtil.getString(rawdata, m.getResponseCharSet());
        if (!isSuccessStatus(responseStatus))
            return failureResultForStatusCode(responseStatus);
        ResourceProxy resource = new ResourceProxy(path);
        try (JsonReader jsonReader = new JsonReader(new InputStreamReader(get.getResponseBodyAsStream(), get.getResponseCharSet()))) {
            jsonReader.beginObject();
            while (jsonReader.hasNext()) {
                String name = jsonReader.nextName();
                JsonToken token = jsonReader.peek();
                if (token == JsonToken.STRING) {
                    resource.addProperty(name, jsonReader.nextString());
                } else {
                    jsonReader.skipValue();
                }
            }
            jsonReader.endObject();
        }
        return AbstractResult.success(resource);
    } catch (Exception e) {
        return AbstractResult.failure(new RepositoryException(e));
    } finally {
        get.releaseConnection();
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) GetMethod(org.apache.commons.httpclient.methods.GetMethod) AuthScope(org.apache.commons.httpclient.auth.AuthScope) JsonReader(com.google.gson.stream.JsonReader) JsonToken(com.google.gson.stream.JsonToken) RepositoryException(org.apache.sling.ide.transport.RepositoryException) Credentials(org.apache.commons.httpclient.Credentials) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) ResourceProxy(org.apache.sling.ide.transport.ResourceProxy) RepositoryException(org.apache.sling.ide.transport.RepositoryException) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 32 with AuthScope

use of org.apache.commons.httpclient.auth.AuthScope in project sling by apache.

the class AuthenticationResponseCodeTest method testValidatingIncorrectHttpBasicCredentials.

@Test
public void testValidatingIncorrectHttpBasicCredentials() throws Exception {
    // assume http and webdav are on the same host + port
    URL url = new URL(HttpTest.HTTP_BASE_URL);
    Credentials defaultcreds = new UsernamePasswordCredentials("garbage", "garbage");
    H.getHttpClient().getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), defaultcreds);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("j_validate", "true"));
    HttpMethod post = H.assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check", HttpServletResponse.SC_FORBIDDEN, params, null);
    assertXReason(post);
    HttpMethod get = H.assertHttpStatus(HttpTest.HTTP_BASE_URL + "/?j_validate=true", HttpServletResponse.SC_FORBIDDEN);
    assertXReason(get);
}
Also used : NameValuePair(org.apache.commons.httpclient.NameValuePair) AuthScope(org.apache.commons.httpclient.auth.AuthScope) ArrayList(java.util.ArrayList) URL(java.net.URL) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) HttpMethod(org.apache.commons.httpclient.HttpMethod) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) HttpTest(org.apache.sling.commons.testing.integration.HttpTest) Test(org.junit.Test)

Example 33 with AuthScope

use of org.apache.commons.httpclient.auth.AuthScope in project sling by apache.

the class AuthRequestLoginTest method testForcedLogin.

public void testForcedLogin() throws Exception {
    // disable credentials -> anonymous session
    final URL url = new URL(HTTP_BASE_URL);
    final AuthScope scope = new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM);
    httpClient.getParams().setAuthenticationPreemptive(false);
    httpClient.getState().setCredentials(scope, null);
    {
        final String content = getContent(HTTP_BASE_URL + SESSION_INFO_PATH, CONTENT_TYPE_JSON);
        assertJavascript("anonymous", content, "out.println(data.userID)");
    }
    // root must return 20x or 30x
    final GetMethod get = new GetMethod(HTTP_BASE_URL + "/");
    final int status = httpClient.executeMethod(get);
    final int status10 = status / 10;
    if (status10 != 20 && status10 != 30) {
        fail("Expected 20x or 30x status, got " + status);
    }
    // root with sling:authRequestLogin=true must return 401
    assertHttpStatus(HTTP_BASE_URL + "/?sling:authRequestLogin=true", HttpServletResponse.SC_UNAUTHORIZED);
    // re-enable credentials -> admin session
    httpClient.getParams().setAuthenticationPreemptive(true);
    Credentials defaultcreds = new UsernamePasswordCredentials("admin", "admin");
    httpClient.getState().setCredentials(scope, defaultcreds);
    {
        final String content = getContent(HTTP_BASE_URL + SESSION_INFO_PATH, CONTENT_TYPE_JSON);
        assertJavascript("admin", content, "out.println(data.userID)");
    }
}
Also used : AuthScope(org.apache.commons.httpclient.auth.AuthScope) GetMethod(org.apache.commons.httpclient.methods.GetMethod) URL(java.net.URL) Credentials(org.apache.commons.httpclient.Credentials) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 34 with AuthScope

use of org.apache.commons.httpclient.auth.AuthScope in project sling by apache.

the class HttpOsgiClient method getHttpClient.

private HttpClient getHttpClient() {
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(DEFAULT_CONNECT_TIMEOUT_SECONDS * 1000);
    client.getHttpConnectionManager().getParams().setSoTimeout(DEFAULT_SOCKET_TIMEOUT_SECONDS * 1000);
    client.getParams().setAuthenticationPreemptive(true);
    Credentials defaultcreds = new UsernamePasswordCredentials(repositoryInfo.getUsername(), repositoryInfo.getPassword());
    client.getState().setCredentials(new AuthScope(repositoryInfo.getHost(), repositoryInfo.getPort(), AuthScope.ANY_REALM), defaultcreds);
    return client;
}
Also used : HttpClient(org.apache.commons.httpclient.HttpClient) AuthScope(org.apache.commons.httpclient.auth.AuthScope) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 35 with AuthScope

use of org.apache.commons.httpclient.auth.AuthScope in project nutch by apache.

the class Http method setCredentials.

/**
 * Reads authentication configuration file (defined as 'http.auth.file' in
 * Nutch configuration file) and sets the credentials for the configured
 * authentication scopes in the HTTP client object.
 *
 * @throws ParserConfigurationException
 *           If a document builder can not be created.
 * @throws SAXException
 *           If any parsing error occurs.
 * @throws IOException
 *           If any I/O error occurs.
 */
private static synchronized void setCredentials() throws ParserConfigurationException, SAXException, IOException {
    if (authRulesRead)
        return;
    // Avoid re-attempting to read
    authRulesRead = true;
    InputStream is = conf.getConfResourceAsInputStream(authFile);
    if (is != null) {
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
        Element rootElement = doc.getDocumentElement();
        if (!"auth-configuration".equals(rootElement.getTagName())) {
            if (LOG.isWarnEnabled())
                LOG.warn("Bad auth conf file: root element <" + rootElement.getTagName() + "> found in " + authFile + " - must be <auth-configuration>");
        }
        // For each set of credentials
        NodeList credList = rootElement.getChildNodes();
        for (int i = 0; i < credList.getLength(); i++) {
            Node credNode = credList.item(i);
            if (!(credNode instanceof Element))
                continue;
            Element credElement = (Element) credNode;
            if (!"credentials".equals(credElement.getTagName())) {
                if (LOG.isWarnEnabled())
                    LOG.warn("Bad auth conf file: Element <" + credElement.getTagName() + "> not recognized in " + authFile + " - expected <credentials>");
                continue;
            }
            String authMethod = credElement.getAttribute("authMethod");
            // read http form post auth info
            if (StringUtils.isNotBlank(authMethod)) {
                formConfigurer = readFormAuthConfigurer(credElement, authMethod);
                continue;
            }
            String username = credElement.getAttribute("username");
            String password = credElement.getAttribute("password");
            // For each authentication scope
            NodeList scopeList = credElement.getChildNodes();
            for (int j = 0; j < scopeList.getLength(); j++) {
                Node scopeNode = scopeList.item(j);
                if (!(scopeNode instanceof Element))
                    continue;
                Element scopeElement = (Element) scopeNode;
                if ("default".equals(scopeElement.getTagName())) {
                    // Determine realm and scheme, if any
                    String realm = scopeElement.getAttribute("realm");
                    String scheme = scopeElement.getAttribute("scheme");
                    // Set default credentials
                    defaultUsername = username;
                    defaultPassword = password;
                    defaultRealm = realm;
                    defaultScheme = scheme;
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Credentials - username: " + username + "; set as default" + " for realm: " + realm + "; scheme: " + scheme);
                    }
                } else if ("authscope".equals(scopeElement.getTagName())) {
                    // Determine authentication scope details
                    String host = scopeElement.getAttribute("host");
                    // For setting port to AuthScope.ANY_PORT
                    int port = -1;
                    try {
                        port = Integer.parseInt(scopeElement.getAttribute("port"));
                    } catch (Exception ex) {
                    // do nothing, port is already set to any port
                    }
                    String realm = scopeElement.getAttribute("realm");
                    String scheme = scopeElement.getAttribute("scheme");
                    // Set credentials for the determined scope
                    AuthScope authScope = getAuthScope(host, port, realm, scheme);
                    NTCredentials credentials = new NTCredentials(username, password, agentHost, realm);
                    client.getState().setCredentials(authScope, credentials);
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Credentials - username: " + username + "; set for AuthScope - " + "host: " + host + "; port: " + port + "; realm: " + realm + "; scheme: " + scheme);
                    }
                } else {
                    if (LOG.isWarnEnabled())
                        LOG.warn("Bad auth conf file: Element <" + scopeElement.getTagName() + "> not recognized in " + authFile + " - expected <authscope>");
                }
            }
            is.close();
        }
    }
}
Also used : InputStream(java.io.InputStream) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) AuthScope(org.apache.commons.httpclient.auth.AuthScope) Document(org.w3c.dom.Document) ProtocolException(org.apache.nutch.protocol.ProtocolException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) NTCredentials(org.apache.commons.httpclient.NTCredentials)

Aggregations

AuthScope (org.apache.commons.httpclient.auth.AuthScope)52 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)34 Credentials (org.apache.commons.httpclient.Credentials)19 GetMethod (org.apache.commons.httpclient.methods.GetMethod)12 HttpClient (org.apache.commons.httpclient.HttpClient)11 URL (java.net.URL)10 IOException (java.io.IOException)5 NTCredentials (org.apache.commons.httpclient.NTCredentials)5 Protocol (org.apache.commons.httpclient.protocol.Protocol)5 ProtocolSocketFactory (org.apache.commons.httpclient.protocol.ProtocolSocketFactory)5 Header (org.apache.commons.httpclient.Header)4 AuthScheme (org.apache.commons.httpclient.auth.AuthScheme)4 AuthState (org.apache.commons.httpclient.auth.AuthState)4 EasySSLProtocolSocketFactory (org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory)4 ClientConfig (com.sun.jersey.api.client.config.ClientConfig)3 DefaultClientConfig (com.sun.jersey.api.client.config.DefaultClientConfig)3 InputStream (java.io.InputStream)3 InputStreamReader (java.io.InputStreamReader)3 URISyntaxException (java.net.URISyntaxException)3 ArrayList (java.util.ArrayList)3