Example usage for org.apache.hadoop.security.authentication.client AuthenticatedURL extractToken

List of usage examples for org.apache.hadoop.security.authentication.client AuthenticatedURL extractToken

Introduction

In this page you can find the example usage for org.apache.hadoop.security.authentication.client AuthenticatedURL extractToken.

Prototype

public static void extractToken(HttpURLConnection conn, Token token)
        throws IOException, AuthenticationException 

Source Link

Document

Helper method that extracts an authentication token received from a connection.

Usage

From source file:com.bigstep.datalake.KerberosIdentityAuthenticator.java

License:Apache License

/**
 * Performs SPNEGO authentication against the specified URL.
 * <p>//www .j ava2  s.  c o  m
 * 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);
        }
    }
}

From source file:com.bigstep.datalake.KerberosIdentityAuthenticator.java

License:Apache License

/**
 * Implements the SPNEGO authentication sequence interaction using the current default principal
 * in the Kerberos cache (normally set via kinit).
 *
 * @param atoken the authentication token being used for the user.
 * @throws IOException             if an IO error occurred.
 * @throws AuthenticationException if an authentication error occurred.
 */// w  w w.  j a  v a  2  s .  co m
private void doSpnegoSequence(AuthenticatedURL.Token atoken) throws IOException, AuthenticationException {
    try {

        kerberosIdentity.doAsPriviledged(new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                final Oid KERB_V5_OID = new Oid("1.2.840.113554.1.2.2");

                GSSContext gssContext = null;
                try {
                    GSSManager gssManager = GSSManager.getInstance();

                    final GSSName clientName = gssManager.createName(kerberosIdentity.getPrincipalName(),
                            GSSName.NT_USER_NAME);
                    LOG.info("doSpnegoSequence() using principal:" + kerberosIdentity.getPrincipalName());
                    final GSSCredential clientCred = gssManager.createCredential(clientName, 8 * 3600,
                            KERB_V5_OID, GSSCredential.INITIATE_ONLY);

                    final String applicationPrincipal = "HTTP@" + kerberosIdentity.getRealm();

                    final GSSName serverName = gssManager.createName(applicationPrincipal,
                            GSSName.NT_HOSTBASED_SERVICE);

                    gssContext = gssManager.createContext(serverName, KERB_V5_OID, clientCred,
                            GSSContext.DEFAULT_LIFETIME);

                    gssContext.requestCredDeleg(true);
                    gssContext.requestMutualAuth(true);
                    gssContext.requestConf(false);
                    gssContext.requestInteg(true);

                    byte[] inToken = new byte[0];
                    byte[] outToken;
                    boolean established = false;

                    // Loop while the context is still not established
                    while (!established) {
                        LOG.info("doSpnegoSequence() using token:" + new BASE64Encoder().encode(inToken));
                        outToken = gssContext.initSecContext(inToken, 0, 0);
                        LOG.info("initSecContext() out token:" + new BASE64Encoder().encode(outToken));
                        if (outToken != null) {
                            sendToken(outToken);
                        }

                        if (!gssContext.isEstablished()) {
                            inToken = readToken();
                        } else {
                            established = true;
                        }
                    }
                } finally {
                    if (gssContext != null) {
                        gssContext.dispose();
                        gssContext = null;
                    }
                }
                return null;
            }
        });
    } catch (PrivilegedActionException ex) {
        throw new AuthenticationException(ex.getException());
    }
    AuthenticatedURL.extractToken(conn, atoken);
}

From source file:com.flipkart.fdp.migration.distcp.security.KerberosAuthenticator2.java

License:Apache License

/**
 * Implements the SPNEGO authentication sequence interaction using the
 * current default principal in the Kerberos cache (normally set via kinit).
 * //from ww  w  .j  a v a2  s.c  om
 * @param token
 *            the authentication token being used for the user.
 * 
 * @throws IOException
 *             if an IO error occurred.
 * @throws AuthenticationException
 *             if an authentication error occurred.
 */
private void doSpnegoSequence(AuthenticatedURL.Token token) throws IOException, AuthenticationException {
    try {

        /*
         * // AccessControlContext context = AccessController.getContext();
         * Subject subject = Subject.getSubject(context); if (subject ==
         * null) { subject = new Subject(); LoginContext login = new
         * LoginContext("", subject, null, new KerberosConfiguration());
         * login.login(); }
         */

        LoginContext loginContext = new LoginContext("", null,
                new KerberosClientCallbackHandler(username, password), new LoginConfig(this.debug));
        loginContext.login();
        // if (LOG.isDebugEnabled()) {
        // LOG.debug("Kerberos authenticated user: "
        // + loginContext.getSubject());
        // }
        Subject subject = loginContext.getSubject();

        Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {

            public Void run() throws Exception {
                GSSContext gssContext = null;
                try {
                    GSSManager gssManager = GSSManager.getInstance();
                    Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                    String sp = KerberosAuthenticator2.this.servicePrincipal;
                    if (sp == null) {
                        sp = "HTTP/" + KerberosAuthenticator2.this.url.getHost();
                    }
                    GSSName serviceName = gssManager.createName(sp, oid);
                    oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                    gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME);
                    gssContext.requestCredDeleg(true);
                    gssContext.requestMutualAuth(true);

                    byte[] inToken = new byte[0];
                    byte[] outToken;
                    boolean established = false;

                    // Loop while the context is still not established
                    while (!established) {
                        outToken = gssContext.initSecContext(inToken, 0, inToken.length);
                        if (outToken != null) {
                            sendToken(outToken);
                        }

                        if (!gssContext.isEstablished()) {
                            inToken = readToken();
                        } else {
                            established = true;
                        }
                    }
                } finally {
                    if (gssContext != null) {
                        gssContext.dispose();
                        gssContext = null;
                    }
                }
                return null;
            }
        });
    } catch (PrivilegedActionException ex) {
        throw new AuthenticationException(ex.getException());
    } catch (LoginException ex) {
        throw new AuthenticationException(ex);
    }
    AuthenticatedURL.extractToken(conn, token);
}

From source file:com.flipkart.fdp.migration.distcp.security.PseudoAuthenticator2.java

License:Apache License

/**
 * Performs simple authentication against the specified URL.
 * <p/>/*from   w w  w.ja  v  a2 s.co m*/
 * If a token is given it does a NOP and returns the given token.
 * <p/>
 * If no token is given, it will perform an HTTP <code>OPTIONS</code>
 * request injecting an additional parameter {@link #USER_NAME} in the query
 * string with the value returned by the {@link #getUserName()} method.
 * <p/>
 * If the response is successful it will update the authentication token.
 * 
 * @param url
 *            the URl to authenticate against.
 * @param token
 *            the authencation 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 {
    String strUrl = url.toString();
    String paramSeparator = (strUrl.contains("?")) ? "&" : "?";
    strUrl += paramSeparator + USER_NAME_EQ + getUserName();
    url = new URL(strUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("OPTIONS");
    conn.connect();
    AuthenticatedURL.extractToken(conn, token);
}

From source file:main.client.http.KerberosAuthenticator2.java

License:Apache License

/**
 * Implements the SPNEGO authentication sequence interaction using the
 * current default principal in the Kerberos cache (normally set via kinit).
 * /*from   w  w  w . j a v a2  s .  c o  m*/
 * @param token
 *            the authentication token being used for the user.
 * 
 * @throws IOException
 *             if an IO error occurred.
 * @throws AuthenticationException
 *             if an authentication error occurred.
 */
private void doSpnegoSequence(AuthenticatedURL.Token token) throws IOException, AuthenticationException {
    try {

        /*      //   
                   AccessControlContext context = AccessController.getContext();
                 Subject subject = Subject.getSubject(context);
                 if (subject == null) {
                    subject = new Subject();
                    LoginContext login = new LoginContext("", subject, null,
          new KerberosConfiguration());
                    login.login();
                 }
        */

        LoginContext loginContext = new LoginContext("", null,
                new KerberosClientCallbackHandler(username, password), new LoginConfig(this.debug));
        loginContext.login();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Kerberos authenticated user: " + loginContext.getSubject());
        }
        Subject subject = loginContext.getSubject();

        Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                GSSContext gssContext = null;
                try {
                    GSSManager gssManager = GSSManager.getInstance();
                    String servicePrincipal = "HTTP/" + KerberosAuthenticator2.this.url.getHost();
                    Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                    GSSName serviceName = gssManager.createName(servicePrincipal, oid);
                    oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                    gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME);
                    gssContext.requestCredDeleg(true);
                    gssContext.requestMutualAuth(true);

                    byte[] inToken = new byte[0];
                    byte[] outToken;
                    boolean established = false;

                    // Loop while the context is still not established
                    while (!established) {
                        outToken = gssContext.initSecContext(inToken, 0, inToken.length);
                        if (outToken != null) {
                            sendToken(outToken);
                        }

                        if (!gssContext.isEstablished()) {
                            inToken = readToken();
                        } else {
                            established = true;
                        }
                    }
                } finally {
                    if (gssContext != null) {
                        gssContext.dispose();
                        gssContext = null;
                    }
                }
                return null;
            }
        });
    } catch (PrivilegedActionException ex) {
        throw new AuthenticationException(ex.getException());
    } catch (LoginException ex) {
        throw new AuthenticationException(ex);
    }
    AuthenticatedURL.extractToken(conn, token);
}