Example usage for org.apache.hadoop.security UserGroupInformation loginUserFromKeytabAndReturnUGI

List of usage examples for org.apache.hadoop.security UserGroupInformation loginUserFromKeytabAndReturnUGI

Introduction

In this page you can find the example usage for org.apache.hadoop.security UserGroupInformation loginUserFromKeytabAndReturnUGI.

Prototype

public static UserGroupInformation loginUserFromKeytabAndReturnUGI(String user, String path)
        throws IOException 

Source Link

Document

Log a user in from a keytab file.

Usage

From source file:org.apache.phoenix.jdbc.SecureUserConnectionsIT.java

License:Apache License

@Test
public void testAlternatingLogins() throws Exception {
    final HashSet<ConnectionInfo> connections = new HashSet<>();
    final String princ1 = getUserPrincipal(1);
    final File keytab1 = getUserKeytabFile(1);
    final String princ2 = getUserPrincipal(2);
    final File keytab2 = getUserKeytabFile(2);

    UserGroupInformation ugi1 = UserGroupInformation.loginUserFromKeytabAndReturnUGI(princ1, keytab1.getPath());
    UserGroupInformation ugi2 = UserGroupInformation.loginUserFromKeytabAndReturnUGI(princ2, keytab2.getPath());

    // Using the same UGI should result in two equivalent ConnectionInfo objects
    ugi1.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            String url = joinUserAuthentication(BASE_URL, princ1, keytab1);
            connections.add(ConnectionInfo.create(url).normalize(ReadOnlyProps.EMPTY_PROPS, EMPTY_PROPERTIES));
            return null;
        }//  w w  w . j  ava 2 s  .  co  m
    });
    assertEquals(1, connections.size());
    // Sanity check
    verifyAllConnectionsAreKerberosBased(connections);

    ugi2.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            String url = joinUserAuthentication(BASE_URL, princ2, keytab2);
            connections.add(ConnectionInfo.create(url).normalize(ReadOnlyProps.EMPTY_PROPS, EMPTY_PROPERTIES));
            return null;
        }
    });
    assertEquals(2, connections.size());
    verifyAllConnectionsAreKerberosBased(connections);

    ugi1.doAs(new PrivilegedExceptionAction<Void>() {
        public Void run() throws Exception {
            String url = joinUserAuthentication(BASE_URL, princ1, keytab1);
            connections.add(ConnectionInfo.create(url).normalize(ReadOnlyProps.EMPTY_PROPS, EMPTY_PROPERTIES));
            return null;
        }
    });
    assertEquals(2, connections.size());
    verifyAllConnectionsAreKerberosBased(connections);
}

From source file:org.apache.ranger.audit.provider.MiscUtil.java

License:Apache License

public static void authWithKerberos(String keytab, String principal, String nameRules) {

    if (keytab == null || principal == null) {
        return;//from   w w  w  . j  a  v  a 2  s  .com
    }
    Subject serverSubject = new Subject();
    int successLoginCount = 0;
    String[] spnegoPrincipals = null;
    try {
        if (principal.equals("*")) {
            spnegoPrincipals = KerberosUtil.getPrincipalNames(keytab, Pattern.compile("HTTP/.*"));
            if (spnegoPrincipals.length == 0) {
                logger.error("No principals found in keytab=" + keytab);
            }
        } else {
            spnegoPrincipals = new String[] { principal };
        }

        if (nameRules != null) {
            KerberosName.setRules(nameRules);
        }

        boolean useKeytab = true;
        if (!useKeytab) {
            logger.info("Creating UGI with subject");
            List<LoginContext> loginContexts = new ArrayList<LoginContext>();
            for (String spnegoPrincipal : spnegoPrincipals) {
                try {
                    logger.info("Login using keytab " + keytab + ", for principal " + spnegoPrincipal);
                    final KerberosConfiguration kerberosConfiguration = new KerberosConfiguration(keytab,
                            spnegoPrincipal);
                    final LoginContext loginContext = new LoginContext("", serverSubject, null,
                            kerberosConfiguration);
                    loginContext.login();
                    successLoginCount++;
                    logger.info("Login success keytab " + keytab + ", for principal " + spnegoPrincipal);
                    loginContexts.add(loginContext);
                } catch (Throwable t) {
                    logger.error("Login failed keytab " + keytab + ", for principal " + spnegoPrincipal, t);
                }
                if (successLoginCount > 0) {
                    logger.info("Total login success count=" + successLoginCount);
                    try {
                        UserGroupInformation.loginUserFromSubject(serverSubject);
                        // UserGroupInformation ugi =
                        // createUGIFromSubject(serverSubject);
                        // if (ugi != null) {
                        // setUGILoginUser(ugi, serverSubject);
                        // }
                    } catch (Throwable e) {
                        logger.error("Error creating UGI from subject. subject=" + serverSubject);
                    }
                } else {
                    logger.error(
                            "Total logins were successfull from keytab=" + keytab + ", principal=" + principal);
                }
            }
        } else {
            logger.info("Creating UGI from keytab directly. keytab=" + keytab + ", principal="
                    + spnegoPrincipals[0]);
            UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(spnegoPrincipals[0],
                    keytab);
            MiscUtil.setUGILoginUser(ugi, null);
        }

    } catch (Throwable t) {
        logger.error("Failed to login with given keytab and principal", t);
    }

}

From source file:org.apache.sentry.tests.e2e.hdfs.TestDbHdfsBase.java

License:Apache License

private static void createGgis() throws Exception {
    if (dfsType.equals(DFSType.MiniDFS.name())) {
        adminUgi = UserGroupInformation.createUserForTesting(System.getProperty("user.name"),
                new String[] { "supergroup" });
        hiveUgi = UserGroupInformation.createUserForTesting("hive", new String[] { "hive" });
    } else if (dfsType.equals(DFSType.ClusterDFS.name())) {
        adminUgi = UserGroupInformation.loginUserFromKeytabAndReturnUGI("hdfs",
                KEYTAB_LOCATION + "/hdfs.keytab");
        hiveUgi = UserGroupInformation.loginUserFromKeytabAndReturnUGI("hive",
                KEYTAB_LOCATION + "/hive.keytab");
    }/*from   ww w.  ja  va  2s .  c  om*/
}

From source file:org.apache.sentry.tests.e2e.hive.fs.ClusterDFS.java

License:Apache License

ClusterDFS() throws Exception {
    ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(TEST_USER,
            KEYTAB_LOCATION + "/" + TEST_USER + ".keytab");
    fileSystem = getFS(ugi);//from  w  ww  .  j  av  a  2 s.  c  o m
    LOGGER.info("File system uri for policy files: " + fileSystem.getUri());
    LOGGER.info("Creating basedir as user : " + TEST_USER);
    String policyDir = System.getProperty("sentry.e2etest.hive.policy.location", "/user/hive/sentry");
    sentryDir = super.assertCreateDfsDir(new Path(fileSystem.getUri() + policyDir));
    dfsBaseDir = super.assertCreateDfsDir(new Path(fileSystem.getUri() + "/tmp/" + (new Random()).nextInt()));
}

From source file:org.apache.sentry.tests.e2e.hive.fs.S3DFS.java

License:Apache License

S3DFS() throws Exception {
    ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(TEST_USER,
            KEYTAB_LOCATION + "/" + TEST_USER + ".keytab");
    fileSystem = getFS(ugi);//w  w w .ja  v a2s  . c o m
    LOGGER.info("fileSystem URI = " + fileSystem.getUri());
    LOGGER.info("Kinited as testUser = " + TEST_USER);
}

From source file:org.apache.sentry.tests.e2e.hive.fs.TestFSBase.java

License:Apache License

protected void createPath(Path relativePath) throws Exception {
    Path fullPath = getFullPathWithSchemeAndAuthority(relativePath);
    FileSystem adminFS = storageFileSystem;
    LOGGER.info("Creating path " + fullPath);
    if (storageDFSType.equals(DFSType.ClusterDFS)) {
        UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(dfsAdmin,
                KEYTAB_LOCATION + "/" + dfsAdmin + ".keytab");
        adminFS = getFS(ugi);//from  ww w.j  a v  a  2s  .c  o m
    }
    if (adminFS.exists(fullPath)) {
        adminFS.delete(fullPath, true);
    }
    adminFS.mkdirs(fullPath);
}

From source file:org.apache.slider.client.TokensOperation.java

License:Apache License

public int actionTokens(ActionTokensArgs args, FileSystem fs, Configuration conf, YarnClientImpl yarnClient)
        throws IOException, YarnException {
    Credentials credentials;//from  ww w  . j av  a  2  s .c o  m
    String footnote = "";
    UserGroupInformation user = UserGroupInformation.getCurrentUser();
    boolean isSecure = UserGroupInformation.isSecurityEnabled();
    if (args.keytab != null) {
        File keytab = args.keytab;
        if (!keytab.isFile()) {
            throw new NotFoundException(E_NO_KEYTAB + keytab.getAbsolutePath());
        }
        String principal = args.principal;
        log.info("Logging in as {} from keytab {}", principal, keytab);
        user = UserGroupInformation.loginUserFromKeytabAndReturnUGI(principal, keytab.getCanonicalPath());
    }
    Credentials userCredentials = user.getCredentials();
    File output = args.output;
    if (output != null) {
        if (!isSecure) {
            throw new BadClusterStateException(E_INSECURE);
        }
        credentials = new Credentials(userCredentials);
        // filesystem
        addRMRenewableFSDelegationTokens(conf, fs, credentials);
        addRMDelegationToken(yarnClient, credentials);
        if (maybeAddTimelineToken(conf, credentials) != null) {
            log.debug("Added timeline token");
        }
        saveTokens(output, credentials);
        String filename = output.getCanonicalPath();
        footnote = String.format(
                "%d tokens saved to %s\n" + "To use these in the environment:\n" + "export %s=%s",
                credentials.numberOfTokens(), filename, UserGroupInformation.HADOOP_TOKEN_FILE_LOCATION,
                filename);
    } else if (args.source != null) {
        File source = args.source;
        log.info("Reading credentials from file {}", source);
        if (!source.isFile()) {
            throw new NotFoundException(E_MISSING_SOURCE_FILE + source.getAbsolutePath());
        }
        credentials = Credentials.readTokenStorageFile(args.source, conf);
    } else {
        StringBuffer origin = new StringBuffer();
        File file = locateEnvCredentials(System.getenv(), conf, origin);
        if (file != null) {
            log.info("Credential Source {}", origin);
        } else {
            log.info("Credential source: logged in user");
        }
        credentials = userCredentials;
    }
    // list the tokens
    log.info("\n{}", dumpTokens(credentials, "\n"));
    if (!footnote.isEmpty()) {
        log.info(footnote);
    }
    return 0;
}

From source file:org.apache.slider.server.services.security.FsDelegationTokenManager.java

License:Apache License

private void createRemoteUser(Configuration configuration) throws IOException {
    Configuration loginConfig = new Configuration(configuration);
    loginConfig.set(DFSConfigKeys.HADOOP_SECURITY_AUTHENTICATION, "kerberos");
    // using HDFS principal...
    this.remoteUser = UserGroupInformation.loginUserFromKeytabAndReturnUGI(
            SecurityUtil.getServerPrincipal(loginConfig.get(DFSConfigKeys.DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY),
                    InetAddress.getLocalHost().getCanonicalHostName()),
            loginConfig.get(DFSConfigKeys.DFS_NAMENODE_KEYTAB_FILE_KEY));
    log.info("Created remote user {}.  UGI reports current user is {}", this.remoteUser,
            UserGroupInformation.getCurrentUser());
}