Search in sources :

Example 71 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project hadoop by apache.

the class TestMultiSchemeAuthenticationHandler method testRequestWithInvalidAuthorization.

@Test(timeout = 60000)
public void testRequestWithInvalidAuthorization() throws Exception {
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    final Base64 base64 = new Base64(0);
    String credentials = "bjones:invalidpassword";
    Mockito.when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn(base64.encodeToString(credentials.getBytes()));
    Assert.assertNull(handler.authenticate(request, response));
    Mockito.verify(response).addHeader(WWW_AUTHENTICATE_HEADER, BASIC);
    Mockito.verify(response).addHeader(WWW_AUTHENTICATE_HEADER, NEGOTIATE);
    Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Base64(org.apache.commons.codec.binary.Base64) HttpServletResponse(javax.servlet.http.HttpServletResponse) Test(org.junit.Test)

Example 72 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project hadoop by apache.

the class TestMultiSchemeAuthenticationHandler method testRequestWithLdapAuthorization.

@Test(timeout = 60000)
public void testRequestWithLdapAuthorization() throws Exception {
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    final Base64 base64 = new Base64(0);
    String credentials = base64.encodeToString("bjones:p@ssw0rd".getBytes());
    String authHeader = BASIC + " " + credentials;
    Mockito.when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn(authHeader);
    AuthenticationToken token = handler.authenticate(request, response);
    Assert.assertNotNull(token);
    Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);
    Assert.assertEquals(TYPE, token.getType());
    Assert.assertEquals("bjones", token.getUserName());
    Assert.assertEquals("bjones", token.getName());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Base64(org.apache.commons.codec.binary.Base64) HttpServletResponse(javax.servlet.http.HttpServletResponse) Test(org.junit.Test)

Example 73 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project hadoop by apache.

the class KerberosAuthenticationHandler method authenticate.

/**
   * It enforces the the Kerberos SPNEGO authentication sequence returning an
   * {@link AuthenticationToken} only after the Kerberos SPNEGO sequence has
   * completed successfully.
   *
   * @param request the HTTP client request.
   * @param response the HTTP client response.
   *
   * @return an authentication token if the Kerberos SPNEGO sequence is complete
   * and valid, <code>null</code> if it is in progress (in this case the handler
   * handles the response to the client).
   *
   * @throws IOException thrown if an IO error occurred.
   * @throws AuthenticationException thrown if Kerberos SPNEGO sequence failed.
   */
@Override
public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response) throws IOException, AuthenticationException {
    AuthenticationToken token = null;
    String authorization = request.getHeader(KerberosAuthenticator.AUTHORIZATION);
    if (authorization == null || !authorization.startsWith(KerberosAuthenticator.NEGOTIATE)) {
        response.setHeader(WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        if (authorization == null) {
            LOG.trace("SPNEGO starting for url: {}", request.getRequestURL());
        } else {
            LOG.warn("'" + KerberosAuthenticator.AUTHORIZATION + "' does not start with '" + KerberosAuthenticator.NEGOTIATE + "' :  {}", authorization);
        }
    } else {
        authorization = authorization.substring(KerberosAuthenticator.NEGOTIATE.length()).trim();
        final Base64 base64 = new Base64(0);
        final byte[] clientToken = base64.decode(authorization);
        final String serverName = InetAddress.getByName(request.getServerName()).getCanonicalHostName();
        try {
            token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() {

                private Set<String> serverPrincipals = serverPrincipalMap.get(serverName);

                @Override
                public AuthenticationToken run() throws Exception {
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("SPNEGO with server principals: {} for {}", serverPrincipals.toString(), serverName);
                    }
                    AuthenticationToken token = null;
                    Exception lastException = null;
                    for (String serverPrincipal : serverPrincipals) {
                        try {
                            token = runWithPrincipal(serverPrincipal, clientToken, base64, response);
                        } catch (Exception ex) {
                            lastException = ex;
                            LOG.trace("Auth {} failed with {}", serverPrincipal, ex);
                        } finally {
                            if (token != null) {
                                LOG.trace("Auth {} successfully", serverPrincipal);
                                break;
                            }
                        }
                    }
                    if (token != null) {
                        return token;
                    } else {
                        throw new AuthenticationException(lastException);
                    }
                }
            });
        } catch (PrivilegedActionException ex) {
            if (ex.getException() instanceof IOException) {
                throw (IOException) ex.getException();
            } else {
                throw new AuthenticationException(ex.getException());
            }
        }
    }
    return token;
}
Also used : Base64(org.apache.commons.codec.binary.Base64) Set(java.util.Set) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) PrivilegedActionException(java.security.PrivilegedActionException) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) IOException(java.io.IOException) LoginException(javax.security.auth.login.LoginException) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) ServletException(javax.servlet.ServletException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) GSSException(org.ietf.jgss.GSSException)

Example 74 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project hadoop by apache.

the class KerberosAuthenticator method authenticate.

/**
   * Performs SPNEGO authentication against the specified URL.
   * <p>
   * If a token is given it does a NOP and returns the given token.
   * <p>
   * If no token is given, it will perform the SPNEGO authentication sequence using an
   * HTTP <code>OPTIONS</code> request.
   *
   * @param url the URl to authenticate against.
   * @param token the authentication token being used for the user.
   *
   * @throws IOException if an IO error occurred.
   * @throws AuthenticationException if an authentication error occurred.
   */
@Override
public void authenticate(URL url, AuthenticatedURL.Token token) throws IOException, AuthenticationException {
    if (!token.isSet()) {
        this.url = url;
        base64 = new Base64(0);
        conn = (HttpURLConnection) url.openConnection();
        if (connConfigurator != null) {
            conn = connConfigurator.configure(conn);
        }
        conn.setRequestMethod(AUTH_HTTP_METHOD);
        conn.connect();
        boolean needFallback = false;
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            LOG.debug("JDK performed authentication on our behalf.");
            // If the JDK already did the SPNEGO back-and-forth for
            // us, just pull out the token.
            AuthenticatedURL.extractToken(conn, token);
            if (isTokenKerberos(token)) {
                return;
            }
            needFallback = true;
        }
        if (!needFallback && isNegotiate()) {
            LOG.debug("Performing our own SPNEGO sequence.");
            doSpnegoSequence(token);
        } else {
            LOG.debug("Using fallback authenticator sequence.");
            Authenticator auth = getFallBackAuthenticator();
            // Make sure that the fall back authenticator have the same
            // ConnectionConfigurator, since the method might be overridden.
            // Otherwise the fall back authenticator might not have the information
            // to make the connection (e.g., SSL certificates)
            auth.setConnectionConfigurator(connConfigurator);
            auth.authenticate(url, token);
        }
    }
}
Also used : Base64(org.apache.commons.codec.binary.Base64)

Example 75 with Base64.encodeBase64String

use of org.apache.commons.codec.binary.Base64.encodeBase64String in project hadoop by apache.

the class Token method decodeWritable.

/**
   * Modify the writable to the value from the newValue.
   * @param obj the object to read into
   * @param newValue the string with the url-safe base64 encoded bytes
   * @throws IOException
   */
private static void decodeWritable(Writable obj, String newValue) throws IOException {
    Base64 decoder = new Base64(0, null, true);
    DataInputBuffer buf = new DataInputBuffer();
    byte[] decoded = decoder.decode(newValue);
    buf.reset(decoded, decoded.length);
    obj.readFields(buf);
}
Also used : Base64(org.apache.commons.codec.binary.Base64)

Aggregations

Base64 (org.apache.commons.codec.binary.Base64)135 IOException (java.io.IOException)30 Test (org.junit.Test)29 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)12 InputStream (java.io.InputStream)11 HttpServletRequest (javax.servlet.http.HttpServletRequest)11 HttpServletResponse (javax.servlet.http.HttpServletResponse)11 Base64.encodeBase64String (org.apache.commons.codec.binary.Base64.encodeBase64String)11 ByteArrayInputStream (java.io.ByteArrayInputStream)10 HashMap (java.util.HashMap)10 SecretKeySpec (javax.crypto.spec.SecretKeySpec)9 MessageDigest (java.security.MessageDigest)8 File (java.io.File)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)7 URL (java.net.URL)7 Mac (javax.crypto.Mac)7 ServletException (javax.servlet.ServletException)7 X509Certificate (java.security.cert.X509Certificate)6 FileNotFoundException (java.io.FileNotFoundException)5 Signature (java.security.Signature)5