Java 类org.apache.http.auth.AUTH 实例源码

项目:diadocsdk-java    文件:DiadocAuthScheme.java   
/**
 * Returns a Diadoc <tt>Authorization</tt> header value for the given
 * {@link DiadocCredentials}.
 *
 * @param credentials The credentials to encode.
 * @return a Diadoc authorization header
 */
public static Header authenticate(final DiadocCredentials credentials) {
    if (credentials == null) {
        throw new IllegalArgumentException("Credentials may not be null");
    }

    StringBuilder sb = new StringBuilder();
    sb.append("ddauth_api_client_id=");
    sb.append(credentials.getApiClientId());
    if (credentials.getAuthToken() != null) {
        sb.append(",ddauth_token=");
        sb.append(credentials.getAuthToken());
    }

    CharArrayBuffer buffer = new CharArrayBuffer(128);
    buffer.append(AUTH.WWW_AUTH_RESP);
    buffer.append(": DiadocAuth ");
    buffer.append(sb.toString());

    return new BufferedHeader(buffer);
}
项目:purecloud-iot    文件:TestHttpAuthenticator.java   
@Test
public void testAuthentication() throws Exception {
    final HttpHost host = new HttpHost("somehost", 80);
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\""));
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\""));
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "whatever realm=\"realm1\", stuff=\"1234\""));

    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();

    Assert.assertTrue(this.httpAuthenticator.handleAuthChallenge(host,
            response, authStrategy, this.authState, this.context));
    Assert.assertEquals(AuthProtocolState.CHALLENGED, this.authState.getState());

    final Queue<AuthOption> options = this.authState.getAuthOptions();
    Assert.assertNotNull(options);
    final AuthOption option1 = options.poll();
    Assert.assertNotNull(option1);
    Assert.assertEquals("digest", option1.getAuthScheme().getSchemeName());
    final AuthOption option2 = options.poll();
    Assert.assertNotNull(option2);
    Assert.assertEquals("basic", option2.getAuthScheme().getSchemeName());
    Assert.assertNull(options.poll());
}
项目:purecloud-iot    文件:TestHttpAuthenticator.java   
@Test
public void testAuthenticationFailed() throws Exception {
    final HttpHost host = new HttpHost("somehost", 80);
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\""));
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\""));

    this.authState.setState(AuthProtocolState.CHALLENGED);
    this.authState.update(this.authScheme, this.credentials);

    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();

    Assert.assertFalse(this.httpAuthenticator.handleAuthChallenge(host,
            response, authStrategy, this.authState, this.context));

    Assert.assertEquals(AuthProtocolState.FAILURE, this.authState.getState());

    Mockito.verify(this.authCache).remove(host);
}
项目:purecloud-iot    文件:TestHttpAuthenticator.java   
@Test
public void testAuthenticationFailedPreviously() throws Exception {
    final HttpHost host = new HttpHost("somehost", 80);
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\""));
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\""));

    this.authState.setState(AuthProtocolState.FAILURE);

    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();

    Assert.assertFalse(this.httpAuthenticator.handleAuthChallenge(host,
            response, authStrategy, this.authState, this.context));

    Assert.assertEquals(AuthProtocolState.FAILURE, this.authState.getState());
}
项目:purecloud-iot    文件:TestHttpAuthenticator.java   
@Test
public void testAuthenticationFailure() throws Exception {
    final HttpHost host = new HttpHost("somehost", 80);
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\""));
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\""));
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "whatever realm=\"realm1\", stuff=\"1234\""));

    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();

    this.authState.setState(AuthProtocolState.CHALLENGED);
    this.authState.update(new BasicScheme(), this.credentials);

    Assert.assertFalse(this.httpAuthenticator.handleAuthChallenge(host,
            response, authStrategy, this.authState, this.context));
    Assert.assertEquals(AuthProtocolState.FAILURE, this.authState.getState());
    Assert.assertNull(this.authState.getCredentials());
}
项目:purecloud-iot    文件:TestHttpAuthenticator.java   
@Test
public void testAuthenticationHandshaking() throws Exception {
    final HttpHost host = new HttpHost("somehost", 80);
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\""));
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", stale=true, nonce=\"1234\""));
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "whatever realm=\"realm1\", stuff=\"1234\""));

    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();

    this.authState.setState(AuthProtocolState.CHALLENGED);
    this.authState.update(new DigestScheme(), this.credentials);

    Assert.assertTrue(this.httpAuthenticator.handleAuthChallenge(host,
            response, authStrategy, this.authState, this.context));

    Assert.assertEquals(AuthProtocolState.HANDSHAKE, this.authState.getState());
}
项目:purecloud-iot    文件:TestHttpAuthenticator.java   
@Test
public void testAuthenticationNoMatchingChallenge() throws Exception {
    final HttpHost host = new HttpHost("somehost", 80);
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\""));
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "whatever realm=\"realm1\", stuff=\"1234\""));

    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();

    this.authState.setState(AuthProtocolState.CHALLENGED);
    this.authState.update(new BasicScheme(), this.credentials);

    Assert.assertTrue(this.httpAuthenticator.handleAuthChallenge(host,
            response, authStrategy, this.authState, this.context));
    Assert.assertEquals(AuthProtocolState.CHALLENGED, this.authState.getState());

    final Queue<AuthOption> options = this.authState.getAuthOptions();
    Assert.assertNotNull(options);
    final AuthOption option1 = options.poll();
    Assert.assertNotNull(option1);
    Assert.assertEquals("digest", option1.getAuthScheme().getSchemeName());
    Assert.assertNull(options.poll());
}
项目:purecloud-iot    文件:TestHttpAuthenticator.java   
@Test
public void testAuthChallengeStateNoOption() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");
    this.authState.setState(AuthProtocolState.CHALLENGED);
    this.authState.update(this.authScheme, this.credentials);

    Mockito.when(this.authScheme.authenticate(
            Mockito.any(Credentials.class),
            Mockito.any(HttpRequest.class),
            Mockito.any(HttpContext.class))).thenReturn(new BasicHeader(AUTH.WWW_AUTH_RESP, "stuff"));

    this.httpAuthenticator.generateAuthResponse(request, authState, context);

    Assert.assertTrue(request.containsHeader(AUTH.WWW_AUTH_RESP));

    Mockito.verify(this.authScheme).authenticate(this.credentials, request, this.context);
}
项目:purecloud-iot    文件:TestHttpAuthenticator.java   
@Test
public void testAuthChallengeStateOneOptions() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");
    this.authState.setState(AuthProtocolState.CHALLENGED);
    final LinkedList<AuthOption> authOptions = new LinkedList<AuthOption>();
    authOptions.add(new AuthOption(this.authScheme, this.credentials));
    this.authState.update(authOptions);

    Mockito.when(this.authScheme.authenticate(
            Mockito.any(Credentials.class),
            Mockito.any(HttpRequest.class),
            Mockito.any(HttpContext.class))).thenReturn(new BasicHeader(AUTH.WWW_AUTH_RESP, "stuff"));

    this.httpAuthenticator.generateAuthResponse(request, authState, context);

    Assert.assertSame(this.authScheme, this.authState.getAuthScheme());
    Assert.assertSame(this.credentials, this.authState.getCredentials());
    Assert.assertNull(this.authState.getAuthOptions());

    Assert.assertTrue(request.containsHeader(AUTH.WWW_AUTH_RESP));

    Mockito.verify(this.authScheme).authenticate(this.credentials, request, this.context);
}
项目:purecloud-iot    文件:TestHttpAuthenticator.java   
@Test
public void testAuthSuccess() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");
    this.authState.setState(AuthProtocolState.SUCCESS);
    this.authState.update(this.authScheme, this.credentials);

    Mockito.when(this.authScheme.isConnectionBased()).thenReturn(Boolean.FALSE);
    Mockito.when(this.authScheme.authenticate(
            Mockito.any(Credentials.class),
            Mockito.any(HttpRequest.class),
            Mockito.any(HttpContext.class))).thenReturn(new BasicHeader(AUTH.WWW_AUTH_RESP, "stuff"));

    this.httpAuthenticator.generateAuthResponse(request, authState, context);

    Assert.assertSame(this.authScheme, this.authState.getAuthScheme());
    Assert.assertSame(this.credentials, this.authState.getCredentials());
    Assert.assertNull(this.authState.getAuthOptions());

    Assert.assertTrue(request.containsHeader(AUTH.WWW_AUTH_RESP));

    Mockito.verify(this.authScheme).authenticate(this.credentials, request, this.context);
}
项目:purecloud-iot    文件:TestHttpAuthenticator.java   
@Test
public void testAuthSuccessConnectionBased() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");
    this.authState.setState(AuthProtocolState.SUCCESS);
    this.authState.update(this.authScheme, this.credentials);

    Mockito.when(this.authScheme.isConnectionBased()).thenReturn(Boolean.TRUE);
    Mockito.when(this.authScheme.authenticate(
            Mockito.any(Credentials.class),
            Mockito.any(HttpRequest.class),
            Mockito.any(HttpContext.class))).thenReturn(new BasicHeader(AUTH.WWW_AUTH_RESP, "stuff"));

    this.httpAuthenticator.generateAuthResponse(request, authState, context);

    Assert.assertFalse(request.containsHeader(AUTH.WWW_AUTH_RESP));

    Mockito.verify(this.authScheme, Mockito.never()).authenticate(
            Mockito.any(Credentials.class),
            Mockito.any(HttpRequest.class),
            Mockito.any(HttpContext.class));
}
项目:purecloud-iot    文件:TestRFC2617Scheme.java   
@Test
public void testProcessChallenge() throws Exception {
    final TestAuthScheme authscheme = new TestAuthScheme();
    final Header header = new BasicHeader(
            AUTH.WWW_AUTH,
            "Test realm=\"realm1\", test, test1 =  stuff, test2 =  \"stuff, stuff\", test3=\"crap");

    authscheme.processChallenge(header);

    Assert.assertEquals("test", authscheme.getSchemeName());
    Assert.assertEquals("TEST", authscheme.toString());
    Assert.assertEquals("realm1", authscheme.getParameter("realm"));
    Assert.assertEquals(null, authscheme.getParameter("test"));
    Assert.assertEquals("stuff", authscheme.getParameter("test1"));
    Assert.assertEquals("stuff, stuff", authscheme.getParameter("test2"));
    Assert.assertEquals("crap", authscheme.getParameter("test3"));
    Assert.assertEquals(null, authscheme.getParameter(null));
}
项目:purecloud-iot    文件:TestRFC2617Scheme.java   
@Test
public void testSerialization() throws Exception {
    final Header challenge = new BasicHeader(AUTH.WWW_AUTH, "test realm=\"test\", blah=blah, yada=\"yada yada\"");

    final TestAuthScheme testScheme = new TestAuthScheme(Consts.ISO_8859_1);
    testScheme.processChallenge(challenge);

    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    final ObjectOutputStream out = new ObjectOutputStream(buffer);
    out.writeObject(testScheme);
    out.flush();
    final byte[] raw = buffer.toByteArray();
    final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(raw));
    final TestAuthScheme authScheme = (TestAuthScheme) in.readObject();

    Assert.assertEquals(Consts.ISO_8859_1, authScheme.getCredentialsCharset());
    Assert.assertEquals("test", authScheme.getParameter("realm"));
    Assert.assertEquals("blah", authScheme.getParameter("blah"));
    Assert.assertEquals("yada yada", authScheme.getParameter("yada"));
}
项目:purecloud-iot    文件:TestDigestScheme.java   
@Test
public void testDigestAuthenticationWithDefaultCreds() throws Exception {
    final String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
    final Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
    final HttpRequest request = new BasicHttpRequest("Simple", "/");
    final Credentials cred = new UsernamePasswordCredentials("username","password");
    final DigestScheme authscheme = new DigestScheme();
    final HttpContext context = new BasicHttpContext();
    authscheme.processChallenge(authChallenge);
    final Header authResponse = authscheme.authenticate(cred, request, context);
    Assert.assertTrue(authscheme.isComplete());
    Assert.assertFalse(authscheme.isConnectionBased());

    final Map<String, String> table = parseAuthResponse(authResponse);
    Assert.assertEquals("username", table.get("username"));
    Assert.assertEquals("realm1", table.get("realm"));
    Assert.assertEquals("/", table.get("uri"));
    Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
    Assert.assertEquals("e95a7ddf37c2eab009568b1ed134f89a", table.get("response"));
}
项目:purecloud-iot    文件:TestDigestScheme.java   
@Test
public void testDigestAuthentication() throws Exception {
    final String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
    final Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
    final HttpRequest request = new BasicHttpRequest("Simple", "/");
    final Credentials cred = new UsernamePasswordCredentials("username","password");
    final DigestScheme authscheme = new DigestScheme();
    final HttpContext context = new BasicHttpContext();
    authscheme.processChallenge(authChallenge);
    final Header authResponse = authscheme.authenticate(cred, request, context);

    final Map<String, String> table = parseAuthResponse(authResponse);
    Assert.assertEquals("username", table.get("username"));
    Assert.assertEquals("realm1", table.get("realm"));
    Assert.assertEquals("/", table.get("uri"));
    Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
    Assert.assertEquals("e95a7ddf37c2eab009568b1ed134f89a", table.get("response"));
}
项目:purecloud-iot    文件:TestDigestScheme.java   
@Test
public void testDigestAuthenticationOverrideParameter() throws Exception {
    final String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
    final Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
    final HttpRequest request = new BasicHttpRequest("Simple", "/");
    final Credentials cred = new UsernamePasswordCredentials("username","password");
    final DigestScheme authscheme = new DigestScheme();
    final HttpContext context = new BasicHttpContext();
    authscheme.processChallenge(authChallenge);
    authscheme.overrideParamter("realm", "other realm");
    final Header authResponse = authscheme.authenticate(cred, request, context);

    final Map<String, String> table = parseAuthResponse(authResponse);
    Assert.assertEquals("username", table.get("username"));
    Assert.assertEquals("other realm", table.get("realm"));
    Assert.assertEquals("/", table.get("uri"));
    Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
    Assert.assertEquals("3f211de10463cbd055ab4cd9c5158eac", table.get("response"));
}
项目:purecloud-iot    文件:TestDigestScheme.java   
@Test
public void testDigestAuthenticationWithSHA() throws Exception {
    final String challenge = "Digest realm=\"realm1\", " +
            "nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " +
            "algorithm=SHA";
    final Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
    final HttpRequest request = new BasicHttpRequest("Simple", "/");
    final Credentials cred = new UsernamePasswordCredentials("username","password");
    final HttpContext context = new BasicHttpContext();
    final DigestScheme authscheme = new DigestScheme();
    authscheme.processChallenge(authChallenge);
    final Header authResponse = authscheme.authenticate(cred, request, context);

    final Map<String, String> table = parseAuthResponse(authResponse);
    Assert.assertEquals("username", table.get("username"));
    Assert.assertEquals("realm1", table.get("realm"));
    Assert.assertEquals("/", table.get("uri"));
    Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
    Assert.assertEquals("8769e82e4e28ecc040b969562b9050580c6d186d", table.get("response"));
}
项目:purecloud-iot    文件:TestDigestScheme.java   
@Test
public void testDigestAuthenticationWithQueryStringInDigestURI() throws Exception {
    final String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
    final Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
    final HttpRequest request = new BasicHttpRequest("Simple", "/?param=value");
    final Credentials cred = new UsernamePasswordCredentials("username","password");
    final HttpContext context = new BasicHttpContext();
    final DigestScheme authscheme = new DigestScheme();
    authscheme.processChallenge(authChallenge);
    final Header authResponse = authscheme.authenticate(cred, request, context);

    final Map<String, String> table = parseAuthResponse(authResponse);
    Assert.assertEquals("username", table.get("username"));
    Assert.assertEquals("realm1", table.get("realm"));
    Assert.assertEquals("/?param=value", table.get("uri"));
    Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
    Assert.assertEquals("a847f58f5fef0bc087bcb9c3eb30e042", table.get("response"));
}
项目:purecloud-iot    文件:TestDigestScheme.java   
@Test
public void testDigestAuthenticationQopAuthInt() throws Exception {
    final String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " +
            "qop=\"auth,auth-int\"";
    final Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
    final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("Post", "/");
    request.setEntity(new StringEntity("abc\u00e4\u00f6\u00fcabc", HTTP.DEF_CONTENT_CHARSET));
    final Credentials cred = new UsernamePasswordCredentials("username","password");
    final DigestScheme authscheme = new DigestScheme();
    final HttpContext context = new BasicHttpContext();
    authscheme.processChallenge(authChallenge);
    final Header authResponse = authscheme.authenticate(cred, request, context);

    Assert.assertEquals("Post:/:acd2b59cd01c7737d8069015584c6cac", authscheme.getA2());

    final Map<String, String> table = parseAuthResponse(authResponse);
    Assert.assertEquals("username", table.get("username"));
    Assert.assertEquals("realm1", table.get("realm"));
    Assert.assertEquals("/", table.get("uri"));
    Assert.assertEquals("auth-int", table.get("qop"));
    Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
}
项目:purecloud-iot    文件:TestDigestScheme.java   
@Test
public void testDigestAuthenticationQopAuthIntNullEntity() throws Exception {
    final String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " +
            "qop=\"auth,auth-int\"";
    final Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
    final HttpRequest request = new BasicHttpEntityEnclosingRequest("Post", "/");
    final Credentials cred = new UsernamePasswordCredentials("username","password");
    final DigestScheme authscheme = new DigestScheme();
    final HttpContext context = new BasicHttpContext();
    authscheme.processChallenge(authChallenge);
    final Header authResponse = authscheme.authenticate(cred, request, context);

    Assert.assertEquals("Post:/:d41d8cd98f00b204e9800998ecf8427e", authscheme.getA2());

    final Map<String, String> table = parseAuthResponse(authResponse);
    Assert.assertEquals("username", table.get("username"));
    Assert.assertEquals("realm1", table.get("realm"));
    Assert.assertEquals("/", table.get("uri"));
    Assert.assertEquals("auth-int", table.get("qop"));
    Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
}
项目:purecloud-iot    文件:TestDigestScheme.java   
@Test
public void testDigestAuthenticationQopAuthOrAuthIntNonRepeatableEntity() throws Exception {
    final String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " +
            "qop=\"auth,auth-int\"";
    final Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
    final HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("Post", "/");
    request.setEntity(new InputStreamEntity(new ByteArrayInputStream(new byte[] {'a'}), -1));
    final Credentials cred = new UsernamePasswordCredentials("username","password");
    final DigestScheme authscheme = new DigestScheme();
    final HttpContext context = new BasicHttpContext();
    authscheme.processChallenge(authChallenge);
    final Header authResponse = authscheme.authenticate(cred, request, context);

    Assert.assertEquals("Post:/", authscheme.getA2());

    final Map<String, String> table = parseAuthResponse(authResponse);
    Assert.assertEquals("username", table.get("username"));
    Assert.assertEquals("realm1", table.get("realm"));
    Assert.assertEquals("/", table.get("uri"));
    Assert.assertEquals("auth", table.get("qop"));
    Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
}
项目:purecloud-iot    文件:TestDigestScheme.java   
@Test
public void testSerialization() throws Exception {
    final String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " +
            "qop=\"auth,auth-int\"";
    final Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge);
    final DigestScheme digestScheme = new DigestScheme();
    digestScheme.processChallenge(authChallenge);

    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    final ObjectOutputStream out = new ObjectOutputStream(buffer);
    out.writeObject(digestScheme);
    out.flush();
    final byte[] raw = buffer.toByteArray();
    final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(raw));
    final DigestScheme authScheme = (DigestScheme) in.readObject();

    Assert.assertEquals(digestScheme.getSchemeName(), authScheme.getSchemeName());
    Assert.assertEquals(digestScheme.getRealm(), authScheme.getRealm());
    Assert.assertEquals(digestScheme.isComplete(), authScheme.isComplete());
    Assert.assertEquals(digestScheme.getA1(), authScheme.getA1());
    Assert.assertEquals(digestScheme.getA2(), authScheme.getA2());
    Assert.assertEquals(digestScheme.getCnonce(), authScheme.getCnonce());
}
项目:purecloud-iot    文件:TestBasicScheme.java   
@Test
public void testBasicAuthentication() throws Exception {
    final UsernamePasswordCredentials creds =
        new UsernamePasswordCredentials("testuser", "testpass");

    final Header challenge = new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\"");

    final BasicScheme authscheme = new BasicScheme();
    authscheme.processChallenge(challenge);

    final HttpRequest request = new BasicHttpRequest("GET", "/");
    final HttpContext context = new BasicHttpContext();
    final Header authResponse = authscheme.authenticate(creds, request, context);

    final String expected = "Basic " + EncodingUtils.getAsciiString(
        Base64.encodeBase64(EncodingUtils.getAsciiBytes("testuser:testpass")));
    Assert.assertEquals(AUTH.WWW_AUTH_RESP, authResponse.getName());
    Assert.assertEquals(expected, authResponse.getValue());
    Assert.assertEquals("test", authscheme.getRealm());
    Assert.assertTrue(authscheme.isComplete());
    Assert.assertFalse(authscheme.isConnectionBased());
}
项目:purecloud-iot    文件:TestBasicScheme.java   
@Test
public void testBasicProxyAuthentication() throws Exception {
    final UsernamePasswordCredentials creds =
        new UsernamePasswordCredentials("testuser", "testpass");

    final Header challenge = new BasicHeader(AUTH.PROXY_AUTH, "Basic realm=\"test\"");

    final BasicScheme authscheme = new BasicScheme();
    authscheme.processChallenge(challenge);

    final HttpRequest request = new BasicHttpRequest("GET", "/");
    final HttpContext context = new BasicHttpContext();
    final Header authResponse = authscheme.authenticate(creds, request, context);

    final String expected = "Basic " + EncodingUtils.getAsciiString(
        Base64.encodeBase64(EncodingUtils.getAsciiBytes("testuser:testpass")));
    Assert.assertEquals(AUTH.PROXY_AUTH_RESP, authResponse.getName());
    Assert.assertEquals(expected, authResponse.getValue());
    Assert.assertEquals("test", authscheme.getRealm());
    Assert.assertTrue(authscheme.isComplete());
    Assert.assertFalse(authscheme.isConnectionBased());
}
项目:purecloud-iot    文件:TestBasicScheme.java   
@Test
public void testSerialization() throws Exception {
    final Header challenge = new BasicHeader(AUTH.PROXY_AUTH, "Basic realm=\"test\"");

    final BasicScheme basicScheme = new BasicScheme();
    basicScheme.processChallenge(challenge);

    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    final ObjectOutputStream out = new ObjectOutputStream(buffer);
    out.writeObject(basicScheme);
    out.flush();
    final byte[] raw = buffer.toByteArray();
    final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(raw));
    final BasicScheme authScheme = (BasicScheme) in.readObject();

    Assert.assertEquals(basicScheme.getSchemeName(), authScheme.getSchemeName());
    Assert.assertEquals(basicScheme.getRealm(), authScheme.getRealm());
    Assert.assertEquals(basicScheme.isComplete(), authScheme.isComplete());
    Assert.assertEquals(true, basicScheme.isProxy());
}
项目:purecloud-iot    文件:TestAuthenticationStrategy.java   
@Test
public void testGetChallenges() throws Exception {
    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();
    final HttpClientContext context = HttpClientContext.create();
    final HttpHost host = new HttpHost("localhost", 80);
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    final Header h1 = new BasicHeader(AUTH.WWW_AUTH, "  Basic  realm=\"test\"");
    final Header h2 = new BasicHeader(AUTH.WWW_AUTH, "\t\tDigest   realm=\"realm1\", nonce=\"1234\"");
    final Header h3 = new BasicHeader(AUTH.WWW_AUTH, "WhatEver realm=\"realm1\", stuff=\"1234\"");
    response.addHeader(h1);
    response.addHeader(h2);
    response.addHeader(h3);

    final Map<String, Header> challenges = authStrategy.getChallenges(host, response, context);

    Assert.assertNotNull(challenges);
    Assert.assertEquals(3, challenges.size());
    Assert.assertSame(h1, challenges.get("basic"));
    Assert.assertSame(h2, challenges.get("digest"));
    Assert.assertSame(h3, challenges.get("whatever"));
}
项目:purecloud-iot    文件:TestAuthenticationStrategy.java   
@Test
public void testSelectNoCredentialsProvider() throws Exception {
    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    final HttpHost authhost = new HttpHost("locahost", 80);
    final HttpClientContext context = HttpClientContext.create();

    final Map<String, Header> challenges = new HashMap<String, Header>();
    challenges.put("basic", new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\""));
    challenges.put("digest", new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\""));

    final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
        .register("basic", new BasicSchemeFactory())
        .register("digest", new DigestSchemeFactory()).build();
    context.setAuthSchemeRegistry(authSchemeRegistry);

    final Queue<AuthOption> options = authStrategy.select(challenges, authhost, response, context);
    Assert.assertNotNull(options);
    Assert.assertEquals(0, options.size());
}
项目:purecloud-iot    文件:TestAuthenticationStrategy.java   
@Test
public void testNoCredentials() throws Exception {
    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    final HttpHost authhost = new HttpHost("locahost", 80);
    final HttpClientContext context = HttpClientContext.create();

    final Map<String, Header> challenges = new HashMap<String, Header>();
    challenges.put("basic", new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"realm1\""));
    challenges.put("digest", new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm2\", nonce=\"1234\""));

    final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
        .register("basic", new BasicSchemeFactory())
        .register("digest", new DigestSchemeFactory()).build();
    context.setAuthSchemeRegistry(authSchemeRegistry);

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    context.setCredentialsProvider(credentialsProvider);

    final Queue<AuthOption> options = authStrategy.select(challenges, authhost, response, context);
    Assert.assertNotNull(options);
    Assert.assertEquals(0, options.size());
}
项目:purecloud-iot    文件:TestWindowsNegotiateScheme.java   
@Before @Override
public void setUp() throws Exception {
    super.setUp();
    this.serverBootstrap.registerHandler("/", new HttpRequestHandler() {

        @Override
        public void handle(
                final HttpRequest request,
                final HttpResponse response,
                final HttpContext context) throws HttpException, IOException {
            response.addHeader(AUTH.WWW_AUTH, AuthSchemes.SPNEGO);
            response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
        }

    });
}
项目:streamsx.topology    文件:StreamingAnalyticsServiceV2.java   
/**
 * Submit an application bundle to execute as a job.
 */
protected JsonObject postJob(CloseableHttpClient httpClient,
        JsonObject service, File bundle, JsonObject jobConfigOverlay)
        throws IOException {

    String url = getJobSubmitUrl(httpClient, bundle);

    HttpPost postJobWithConfig = new HttpPost(url);
    postJobWithConfig.addHeader(AUTH.WWW_AUTH_RESP, getAuthorization());

    FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM);
    StringBody configBody = new StringBody(jobConfigOverlay.toString(), ContentType.APPLICATION_JSON);
    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addPart("bundle_file", bundleBody)
            .addPart("job_options", configBody).build();
    postJobWithConfig.setEntity(reqEntity);

    JsonObject jsonResponse = StreamsRestUtils.getGsonResponse(httpClient, postJobWithConfig);

    RemoteContext.REMOTE_LOGGER.info("Streaming Analytics service (" + getName() + "): submit job response:" + jsonResponse.toString());

    return jsonResponse;
}
项目:streamsx.topology    文件:AbstractStreamingAnalyticsConnection.java   
protected boolean delete(String deleteJobUrl) throws IOException {
    boolean rc = false;
    String sReturn = "";

    Request request = Request
            .Delete(deleteJobUrl)
            .addHeader(AUTH.WWW_AUTH_RESP, getAuthorization())
            .useExpectContinue();

    Response response = executor.execute(request);
    HttpResponse hResponse = response.returnResponse();
    int rcResponse = hResponse.getStatusLine().getStatusCode();

    if (HttpStatus.SC_OK == rcResponse) {
        sReturn = EntityUtils.toString(hResponse.getEntity());
        rc = true;
    } else {
        rc = false;
    }
    traceLog.finest("Request: [" + deleteJobUrl + "]");
    traceLog.finest(rcResponse + ": " + sReturn);
    return rc;
}
项目:streamsx.topology    文件:AbstractStreamingAnalyticsService.java   
@Override
public Result<StreamingAnalyticsService, JsonObject> checkStatus(boolean requireRunning) throws IOException {

    final CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        String url = getStatusUrl(httpClient);

        HttpGet getStatus = new HttpGet(url);
        getStatus.addHeader(AUTH.WWW_AUTH_RESP, getAuthorization());

        JsonObject response = StreamsRestUtils.getGsonResponse(httpClient, getStatus);

        boolean running =
                "true".equals(jstring(response, "enabled"))
                &&
                "running".equals(jstring(response, "status"));

        if (requireRunning && !running)
            throw new IllegalStateException("Service (" + serviceName + ") is not running!");

        return new ResultImpl<>(running, null, () -> this, response);            

    } finally {
        httpClient.close();
    }
}
项目:streamsx.topology    文件:StreamingAnalyticsServiceV1.java   
/**
 * Submit an application bundle to execute as a job.
 */
protected JsonObject postJob(CloseableHttpClient httpClient,
        JsonObject service, File bundle, JsonObject jobConfigOverlay)
        throws IOException {

    String url = getJobSubmitUrl(httpClient, bundle);

    HttpPost postJobWithConfig = new HttpPost(url);
    postJobWithConfig.addHeader(AUTH.WWW_AUTH_RESP, getAuthorization());
    FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM);
    StringBody configBody = new StringBody(jobConfigOverlay.toString(), ContentType.APPLICATION_JSON);

    HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("sab", bundleBody)
            .addPart(DeployKeys.JOB_CONFIG_OVERLAYS, configBody).build();

    postJobWithConfig.setEntity(reqEntity);

    JsonObject jsonResponse = StreamsRestUtils.getGsonResponse(httpClient, postJobWithConfig);

    RemoteContext.REMOTE_LOGGER.info("Streaming Analytics service (" + getName() + "): submit job response:" + jsonResponse.toString());

    return jsonResponse;
}
项目:gooddata-http-client    文件:GoodDataHttpClient.java   
private GoodDataChallengeType identifyGoodDataChallenge(final HttpResponse response) {
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        final Header[] headers = response.getHeaders(AUTH.WWW_AUTH);
        if (headers != null) {
            for (final Header header : headers) {
                final String challenge = header.getValue();
                if (challenge.contains(COOKIE_GDC_AUTH_SST)) {
                    // this is actually not used as in refreshTT() we rely on status code only
                    return GoodDataChallengeType.SST;
                } else if (challenge.contains(COOKIE_GDC_AUTH_TT)) {
                    return GoodDataChallengeType.TT;
                }
            }
        }
    }
    return GoodDataChallengeType.UNKNOWN;
}
项目:lams    文件:RequestTargetAuthentication.java   
public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (context == null) {
        throw new IllegalArgumentException("HTTP context may not be null");
    }

    String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase("CONNECT")) {
        return;
    }

    if (request.containsHeader(AUTH.WWW_AUTH_RESP)) {
        return;
    }

    // Obtain authentication state
    AuthState authState = (AuthState) context.getAttribute(
            ClientContext.TARGET_AUTH_STATE);
    if (authState == null) {
        this.log.debug("Target auth state not set in the context");
        return;
    }
    if (this.log.isDebugEnabled()) {
        this.log.debug("Target auth state: " + authState.getState());
    }
    process(authState, request, context);
}
项目:lams    文件:RequestProxyAuthentication.java   
public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (context == null) {
        throw new IllegalArgumentException("HTTP context may not be null");
    }

    if (request.containsHeader(AUTH.PROXY_AUTH_RESP)) {
        return;
    }

    HttpRoutedConnection conn = (HttpRoutedConnection) context.getAttribute(
            ExecutionContext.HTTP_CONNECTION);
    if (conn == null) {
        this.log.debug("HTTP connection not set in the context");
        return;
    }
    HttpRoute route = conn.getRoute();
    if (route.isTunnelled()) {
        return;
    }

    // Obtain authentication state
    AuthState authState = (AuthState) context.getAttribute(
            ClientContext.PROXY_AUTH_STATE);
    if (authState == null) {
        this.log.debug("Proxy auth state not set in the context");
        return;
    }
    if (this.log.isDebugEnabled()) {
        this.log.debug("Proxy auth state: " + authState.getState());
    }
    process(authState, request, context);
}
项目:lams    文件:BasicScheme.java   
/**
 * Returns a basic <tt>Authorization</tt> header value for the given
 * {@link Credentials} and charset.
 *
 * @param credentials The credentials to encode.
 * @param charset The charset to use for encoding the credentials
 *
 * @return a basic authorization header
 */
public static Header authenticate(
        final Credentials credentials,
        final String charset,
        boolean proxy) {
    if (credentials == null) {
        throw new IllegalArgumentException("Credentials may not be null");
    }
    if (charset == null) {
        throw new IllegalArgumentException("charset may not be null");
    }

    StringBuilder tmp = new StringBuilder();
    tmp.append(credentials.getUserPrincipal().getName());
    tmp.append(":");
    tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword());

    byte[] base64password = Base64.encodeBase64(
            EncodingUtils.getBytes(tmp.toString(), charset));

    CharArrayBuffer buffer = new CharArrayBuffer(32);
    if (proxy) {
        buffer.append(AUTH.PROXY_AUTH_RESP);
    } else {
        buffer.append(AUTH.WWW_AUTH_RESP);
    }
    buffer.append(": Basic ");
    buffer.append(base64password, 0, base64password.length);

    return new BufferedHeader(buffer);
}
项目:lams    文件:DefaultTargetAuthenticationHandler.java   
public Map<String, Header> getChallenges(
        final HttpResponse response,
        final HttpContext context) throws MalformedChallengeException {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }
    Header[] headers = response.getHeaders(AUTH.WWW_AUTH);
    return parseChallenges(headers);
}
项目:lams    文件:DefaultProxyAuthenticationHandler.java   
public Map<String, Header> getChallenges(
        final HttpResponse response,
        final HttpContext context) throws MalformedChallengeException {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }
    Header[] headers = response.getHeaders(AUTH.PROXY_AUTH);
    return parseChallenges(headers);
}
项目:remote-files-sync    文件:BasicSchemeHC4.java   
/**
 * Produces basic authorization header for the given set of {@link Credentials}.
 *
 * @param credentials The set of credentials to be used for authentication
 * @param request The request being authenticated
 * @throws org.apache.http.auth.InvalidCredentialsException if authentication
 *   credentials are not valid or not applicable for this authentication scheme
 * @throws AuthenticationException if authorization string cannot
 *   be generated due to an authentication failure
 *
 * @return a basic authorization string
 */
@Override
public Header authenticate(
        final Credentials credentials,
        final HttpRequest request,
        final HttpContext context) throws AuthenticationException {

    Args.notNull(credentials, "Credentials");
    Args.notNull(request, "HTTP request");
    final StringBuilder tmp = new StringBuilder();
    tmp.append(credentials.getUserPrincipal().getName());
    tmp.append(":");
    tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword());

    final byte[] base64password = Base64.decode(
            EncodingUtils.getBytes(tmp.toString(), getCredentialsCharset(request)),
            Base64.NO_WRAP);

    final CharArrayBuffer buffer = new CharArrayBuffer(32);
    if (isProxy()) {
        buffer.append(AUTH.PROXY_AUTH_RESP);
    } else {
        buffer.append(AUTH.WWW_AUTH_RESP);
    }
    buffer.append(": Basic ");
    buffer.append(base64password, 0, base64password.length);

    return new BufferedHeader(buffer);
}