List of usage examples for javax.security.auth.login LoginContext login
public void login() throws LoginException
From source file:org.apache.hadoop.security.token.delegation.web.TestWebDelegationToken.java
public static <T> T doAsKerberosUser(String principal, String keytab, final Callable<T> callable) throws Exception { LoginContext loginContext = null; try {/*from w w w . j a v a 2s . c o m*/ Set<Principal> principals = new HashSet<Principal>(); principals.add(new KerberosPrincipal(principal)); Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>()); loginContext = new LoginContext("", subject, null, new KerberosConfiguration(principal, keytab)); loginContext.login(); subject = loginContext.getSubject(); return Subject.doAs(subject, new PrivilegedExceptionAction<T>() { @Override public T run() throws Exception { return callable.call(); } }); } catch (PrivilegedActionException ex) { throw ex.getException(); } finally { if (loginContext != null) { loginContext.logout(); } } }
From source file:org.apache.hadoop.security.UserGroupInformation.java
/** * Get the currently logged in user.//from ww w . j a va2s . c o m * @return the logged in user * @throws IOException if login fails */ public synchronized static UserGroupInformation getLoginUser() throws IOException { if (loginUser == null) { try { Subject subject = new Subject(); LoginContext login; if (isSecurityEnabled()) { login = newLoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, subject); } else { login = newLoginContext(HadoopConfiguration.SIMPLE_CONFIG_NAME, subject); } login.login(); loginUser = new UserGroupInformation(subject); loginUser.setLogin(login); loginUser.setAuthenticationMethod( isSecurityEnabled() ? AuthenticationMethod.KERBEROS : AuthenticationMethod.SIMPLE); loginUser = new UserGroupInformation(login.getSubject()); String fileLocation = System.getenv(HADOOP_TOKEN_FILE_LOCATION); if (fileLocation != null && isSecurityEnabled()) { // load the token storage file and put all of the tokens into the // user. Credentials cred = Credentials.readTokenStorageFile(new Path("file:///" + fileLocation), conf); for (Token<?> token : cred.getAllTokens()) { loginUser.addToken(token); } } loginUser.spawnAutoRenewalThreadForUserCreds(); } catch (LoginException le) { throw new IOException("failure to login", le); } if (LOG.isDebugEnabled()) { LOG.debug("UGI loginUser:" + loginUser); } } return loginUser; }
From source file:org.apache.hadoop.security.UserGroupInformation.java
/** * Log a user in from a keytab file. Loads a user identity from a keytab * file and logs them in. They become the currently logged-in user. * @param user the principal name to load from the keytab * @param path the path to the keytab file * @throws IOException if the keytab file can't be read *//*w w w . j av a 2 s .c o m*/ public synchronized static void loginUserFromKeytab(String user, String path) throws IOException { if (!isSecurityEnabled()) { return; } keytabFile = path; keytabPrincipal = user; Subject subject = new Subject(); LoginContext login; long start = 0; // The renewer thread might have been spawned earlier if getLoginUser // was called with the loginUser as null. // Just kill the thread. BTW loginUser is not null anymore and any // future call to getLoginUser will not spawn the thread. if (renewerThread != null) { renewerThread.interrupt(); shouldRunRenewerThread = false; renewerThread = null; LOG.info("Asked the TGT renewer thread to terminate"); } try { login = newLoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, subject); start = System.currentTimeMillis(); login.login(); metrics.addLoginSuccess(System.currentTimeMillis() - start); loginUser = new UserGroupInformation(subject); loginUser.setLogin(login); loginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS); } catch (LoginException le) { if (start > 0) { metrics.addLoginFailure(System.currentTimeMillis() - start); } throw new IOException("Login failure for " + user + " from keytab " + path, le); } LOG.info("Login successful for user " + keytabPrincipal + " using keytab file " + keytabFile); }
From source file:org.apache.hadoop.security.UserGroupInformation.java
/** * Re-Login a user in from the ticket cache. This * method assumes that login had happened already. * The Subject field of this UserGroupInformation object is updated to have * the new credentials.//from www . j a v a2s . c o m * @throws IOException on a failure */ public synchronized void reloginFromTicketCache() throws IOException { if (!isSecurityEnabled() || user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS || !isKrbTkt) return; LoginContext login = getLogin(); if (login == null) { throw new IOException("login must be done first"); } if (!hasSufficientTimeElapsed()) { return; } try { LOG.info("Initiating logout for " + getUserName()); //clear up the kerberos state. But the tokens are not cleared! As per //the Java kerberos login module code, only the kerberos credentials //are cleared login.logout(); //login and also update the subject field of this instance to //have the new credentials (pass it to the LoginContext constructor) login = newLoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, getSubject()); LOG.info("Initiating re-login for " + getUserName()); login.login(); setLogin(login); } catch (LoginException le) { throw new IOException("Login failure for " + getUserName(), le); } }
From source file:org.apache.hadoop.security.UserGroupInformation.java
/** * Log a user in from a keytab file. Loads a user identity from a keytab * file and login them in. This new user does not affect the currently * logged-in user.//w w w. j a v a 2 s.c o m * @param user the principal name to load from the keytab * @param path the path to the keytab file * @throws IOException if the keytab file can't be read */ public synchronized static UserGroupInformation loginUserFromKeytabAndReturnUGI(String user, String path) throws IOException { if (!isSecurityEnabled()) return UserGroupInformation.getCurrentUser(); String oldKeytabFile = null; String oldKeytabPrincipal = null; long start = 0; try { oldKeytabFile = keytabFile; oldKeytabPrincipal = keytabPrincipal; keytabFile = path; keytabPrincipal = user; Subject subject = new Subject(); LoginContext login = newLoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, subject); start = System.currentTimeMillis(); login.login(); metrics.addLoginSuccess(System.currentTimeMillis() - start); UserGroupInformation newLoginUser = new UserGroupInformation(subject); newLoginUser.setLogin(login); newLoginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS); return newLoginUser; } catch (LoginException le) { if (start > 0) { metrics.addLoginFailure(System.currentTimeMillis() - start); } throw new IOException("Login failure for " + user + " from keytab " + path, le); } finally { if (oldKeytabFile != null) keytabFile = oldKeytabFile; if (oldKeytabPrincipal != null) keytabPrincipal = oldKeytabPrincipal; } }
From source file:org.apache.hadoop.security.UserGroupInformation.java
/** * Re-Login a user in from a keytab file. Loads a user identity from a keytab * file and logs them in. They become the currently logged-in user. This * method assumes that {@link #loginUserFromKeytab(String, String)} had * happened already.//ww w. ja va 2 s.c o m * The Subject field of this UserGroupInformation object is updated to have * the new credentials. * @throws IOException on a failure */ public synchronized void reloginFromKeytab() throws IOException { if (!isSecurityEnabled() || user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS || !isKeytab) return; LoginContext login = getLogin(); if (login == null || keytabFile == null) { throw new IOException("loginUserFromKeyTab must be done first"); } if (!hasSufficientTimeElapsed()) { return; } long start = 0; try { LOG.info("Initiating logout for " + getUserName()); synchronized (UserGroupInformation.class) { //clear up the kerberos state. But the tokens are not cleared! As per //the Java kerberos login module code, only the kerberos credentials //are cleared login.logout(); //login and also update the subject field of this instance to //have the new credentials (pass it to the LoginContext constructor) login = newLoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, getSubject()); LOG.info("Initiating re-login for " + keytabPrincipal); start = System.currentTimeMillis(); login.login(); metrics.addLoginSuccess(System.currentTimeMillis() - start); setLogin(login); } } catch (LoginException le) { if (start > 0) { metrics.addLoginFailure(System.currentTimeMillis() - start); } throw new IOException("Login failure for " + keytabPrincipal + " from keytab " + keytabFile, le); } }
From source file:org.apache.lens.client.SpnegoClientFilter.java
private byte[] getToken(String spn, Oid oid) throws GSSException, LoginException { LoginContext lc = buildLoginContext(); lc.login(); Subject subject = lc.getSubject(); GSSManager manager = GSSManager.getInstance(); GSSName serverName = manager.createName(spn, null); // 2nd oid GSSContext context = manager.createContext(serverName.canonicalize(oid), oid, null, GSSContext.DEFAULT_LIFETIME); final byte[] token = new byte[0]; try {//w ww. ja v a2s . c o m return Subject.doAs(subject, new CreateServiceTicketAction(context, token)); } catch (PrivilegedActionException e) { if (e.getCause() instanceof GSSException) { throw (GSSException) e.getCause(); } log.error("initSecContext", e); return null; } }
From source file:org.apache.lens.server.auth.SpnegoAuthenticationFilter.java
private Subject loginAndGetSubject() throws LoginException { // The login without a callback can work if // - Kerberos keytabs are used with a principal name set in the JAAS config // - Kerberos is integrated into the OS logon process // meaning that a process which runs this code has the // user identity LoginContext lc = null; if (loginConfig != null) { lc = new LoginContext("", null, null, loginConfig); } else {//ww w .ja v a 2 s . co m log.info("LoginContext can not be initialized"); throw new LoginException(); } lc.login(); return lc.getSubject(); }
From source file:org.apache.ranger.audit.provider.MiscUtil.java
public static void authWithConfig(String appName, Configuration config) { try {// ww w . j a v a 2 s .com if (config != null) { logger.info( "Getting AppConfigrationEntry[] for appName=" + appName + ", config=" + config.toString()); AppConfigurationEntry[] entries = config.getAppConfigurationEntry(appName); if (entries != null) { logger.info("Got " + entries.length + " AppConfigrationEntry elements for appName=" + appName); for (AppConfigurationEntry appEntry : entries) { logger.info("APP_ENTRY:getLoginModuleName()=" + appEntry.getLoginModuleName()); logger.info("APP_ENTRY:getControlFlag()=" + appEntry.getControlFlag()); logger.info("APP_ENTRY.getOptions()=" + appEntry.getOptions()); } } LoginContext loginContext = new LoginContext(appName, new Subject(), null, config); logger.info("Login in for appName=" + appName); loginContext.login(); logger.info("Principals after login=" + loginContext.getSubject().getPrincipals()); logger.info("UserGroupInformation.loginUserFromSubject(): appName=" + appName + ", principals=" + loginContext.getSubject().getPrincipals()); UserGroupInformation ugi = MiscUtil.createUGIFromSubject(loginContext.getSubject()); if (ugi != null) { MiscUtil.setUGILoginUser(ugi, loginContext.getSubject()); } // UserGroupInformation.loginUserFromSubject(loginContext // .getSubject()); logger.info("POST UserGroupInformation.loginUserFromSubject UGI=" + UserGroupInformation.getLoginUser()); } } catch (Throwable t) { logger.fatal("Error logging as appName=" + appName + ", config=" + config.toString() + ", error=" + t.getMessage()); } }
From source file:org.apache.ranger.audit.provider.MiscUtil.java
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 . co m } 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); } }