List of usage examples for javax.security.auth.login LoginContext LoginContext
public LoginContext(String name, Subject subject, CallbackHandler callbackHandler, Configuration config) throws LoginException
From source file:org.apache.ranger.audit.provider.MiscUtil.java
public static void authWithConfig(String appName, Configuration config) { try {/*from w ww.j a v a2s . c om*/ 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 ww . j av a2 s . c o 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); } }
From source file:org.apache.ranger.services.storm.client.StormClient.java
public static <T> T executeUnderKerberos(String userName, String password, String lookupPrincipal, String lookupKeytab, String nameRules, PrivilegedAction<T> action) throws IOException { final String errMsg = errMessage; class MySecureClientLoginConfiguration extends javax.security.auth.login.Configuration { private String userName; private String password; MySecureClientLoginConfiguration(String aUserName, String password) { this.userName = aUserName; this.password = password; }// w w w . j a va2s. c o m @Override public AppConfigurationEntry[] getAppConfigurationEntry(String appName) { Map<String, String> kerberosOptions = new HashMap<String, String>(); kerberosOptions.put("principal", this.userName); kerberosOptions.put("debug", "true"); kerberosOptions.put("useKeyTab", "false"); kerberosOptions.put(KrbPasswordSaverLoginModule.USERNAME_PARAM, this.userName); kerberosOptions.put(KrbPasswordSaverLoginModule.PASSWORD_PARAM, this.password); kerberosOptions.put("doNotPrompt", "false"); kerberosOptions.put("useFirstPass", "true"); kerberosOptions.put("tryFirstPass", "false"); kerberosOptions.put("storeKey", "true"); kerberosOptions.put("refreshKrb5Config", "true"); AppConfigurationEntry KEYTAB_KERBEROS_LOGIN = null; AppConfigurationEntry KERBEROS_PWD_SAVER = null; try { KEYTAB_KERBEROS_LOGIN = new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, kerberosOptions); KERBEROS_PWD_SAVER = new AppConfigurationEntry(KrbPasswordSaverLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, kerberosOptions); } catch (IllegalArgumentException e) { String msgDesc = "executeUnderKerberos: Exception while getting Storm TopologyList."; HadoopException hdpException = new HadoopException(msgDesc, e); LOG.error(msgDesc, e); hdpException.generateResponseDataMap(false, BaseClient.getMessage(e), msgDesc + errMsg, null, null); throw hdpException; } LOG.debug("getAppConfigurationEntry():" + kerberosOptions.get("principal")); return new AppConfigurationEntry[] { KERBEROS_PWD_SAVER, KEYTAB_KERBEROS_LOGIN }; } } ; T ret = null; Subject subject = null; LoginContext loginContext = null; try { Subject loginSubj = null; if (!StringUtils.isEmpty(lookupPrincipal) && !StringUtils.isEmpty(lookupKeytab)) { LOG.info("Init Lookup Login: security enabled, using lookupPrincipal/lookupKeytab"); if (StringUtils.isEmpty(nameRules)) { nameRules = "DEFAULT"; } loginSubj = SecureClientLogin.loginUserFromKeytab(lookupPrincipal, lookupKeytab, nameRules); } else { subject = new Subject(); LOG.debug("executeUnderKerberos():user=" + userName + ",pass="); LOG.debug("executeUnderKerberos():Creating config.."); MySecureClientLoginConfiguration loginConf = new MySecureClientLoginConfiguration(userName, password); LOG.debug("executeUnderKerberos():Creating Context.."); loginContext = new LoginContext("hadoop-keytab-kerberos", subject, null, loginConf); LOG.debug("executeUnderKerberos():Logging in.."); loginContext.login(); LOG.info("Init Login: using username/password"); loginSubj = loginContext.getSubject(); } if (loginSubj != null) { ret = Subject.doAs(loginSubj, action); } } catch (LoginException le) { String msgDesc = "executeUnderKerberos: Login failure using given" + " configuration parameters, username : `" + userName + "`."; HadoopException hdpException = new HadoopException(msgDesc, le); LOG.error(msgDesc, le); hdpException.generateResponseDataMap(false, BaseClient.getMessage(le), msgDesc + errMsg, null, null); throw hdpException; } catch (SecurityException se) { String msgDesc = "executeUnderKerberos: Exception while getting Storm TopologyList."; HadoopException hdpException = new HadoopException(msgDesc, se); LOG.error(msgDesc, se); hdpException.generateResponseDataMap(false, BaseClient.getMessage(se), msgDesc + errMsg, null, null); throw hdpException; } finally { if (loginContext != null) { if (subject != null) { try { loginContext.logout(); } catch (LoginException e) { throw new IOException("logout failure", e); } } } } return ret; }
From source file:org.apache.ranger.storm.client.StormClient.java
public static <T> T executeUnderKerberos(String userName, String password, PrivilegedAction<T> action) throws IOException { final String errMsg = " You can still save the repository and start creating " + "policies, but you would not be able to use autocomplete for " + "resource names. Check xa_portal.log for more info."; class MySecureClientLoginConfiguration extends javax.security.auth.login.Configuration { private String userName; private String password; MySecureClientLoginConfiguration(String aUserName, String password) { this.userName = aUserName; this.password = password; }// w w w. j ava 2s. c o m @Override public AppConfigurationEntry[] getAppConfigurationEntry(String appName) { Map<String, String> kerberosOptions = new HashMap<String, String>(); kerberosOptions.put("principal", this.userName); kerberosOptions.put("debug", "true"); kerberosOptions.put("useKeyTab", "false"); kerberosOptions.put(KrbPasswordSaverLoginModule.USERNAME_PARAM, this.userName); kerberosOptions.put(KrbPasswordSaverLoginModule.PASSWORD_PARAM, this.password); kerberosOptions.put("doNotPrompt", "false"); kerberosOptions.put("useFirstPass", "true"); kerberosOptions.put("tryFirstPass", "false"); kerberosOptions.put("storeKey", "true"); kerberosOptions.put("refreshKrb5Config", "true"); AppConfigurationEntry KEYTAB_KERBEROS_LOGIN = null; AppConfigurationEntry KERBEROS_PWD_SAVER = null; try { KEYTAB_KERBEROS_LOGIN = new AppConfigurationEntry(KerberosUtil.getKrb5LoginModuleName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, kerberosOptions); KERBEROS_PWD_SAVER = new AppConfigurationEntry(KrbPasswordSaverLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, kerberosOptions); } catch (IllegalArgumentException e) { String msgDesc = "executeUnderKerberos: Exception while getting Storm TopologyList."; HadoopException hdpException = new HadoopException(msgDesc, e); LOG.error(msgDesc, e); hdpException.generateResponseDataMap(false, BaseClient.getMessage(e), msgDesc + errMsg, null, null); throw hdpException; } LOG.debug("getAppConfigurationEntry():" + kerberosOptions.get("principal")); return new AppConfigurationEntry[] { KERBEROS_PWD_SAVER, KEYTAB_KERBEROS_LOGIN }; } } ; T ret = null; Subject subject = null; LoginContext loginContext = null; try { subject = new Subject(); LOG.debug("executeUnderKerberos():user=" + userName + ",pass="); LOG.debug("executeUnderKerberos():Creating config.."); MySecureClientLoginConfiguration loginConf = new MySecureClientLoginConfiguration(userName, password); LOG.debug("executeUnderKerberos():Creating Context.."); loginContext = new LoginContext("hadoop-keytab-kerberos", subject, null, loginConf); LOG.debug("executeUnderKerberos():Logging in.."); loginContext.login(); Subject loginSubj = loginContext.getSubject(); if (loginSubj != null) { ret = Subject.doAs(loginSubj, action); } } catch (LoginException le) { String msgDesc = "executeUnderKerberos: Login failure using given" + " configuration parameters, username : `" + userName + "`."; HadoopException hdpException = new HadoopException(msgDesc, le); LOG.error(msgDesc, le); hdpException.generateResponseDataMap(false, BaseClient.getMessage(le), msgDesc + errMsg, null, null); throw hdpException; } catch (SecurityException se) { String msgDesc = "executeUnderKerberos: Exception while getting Storm TopologyList."; HadoopException hdpException = new HadoopException(msgDesc, se); LOG.error(msgDesc, se); hdpException.generateResponseDataMap(false, BaseClient.getMessage(se), msgDesc + errMsg, null, null); throw hdpException; } finally { if (loginContext != null) { if (subject != null) { try { loginContext.logout(); } catch (LoginException e) { throw new IOException("logout failure", e); } } } } return ret; }
From source file:org.apache.sentry.api.service.thrift.TestSentryWebServerWithKerberos.java
@Test public void testPingWithUnauthorizedUser() throws Exception { // create an unauthorized User with Kerberos String userPrinciple = "user/" + SentryServiceIntegrationBase.SERVER_HOST; String userKerberosName = userPrinciple + "@" + SentryServiceIntegrationBase.REALM; Subject userSubject = new Subject(false, Sets.newHashSet(new KerberosPrincipal(userKerberosName)), new HashSet<Object>(), new HashSet<Object>()); File userKeytab = new File(SentryServiceIntegrationBase.kdcWorkDir, "user.keytab"); SentryServiceIntegrationBase.kdc.createPrincipal(userKeytab, userPrinciple); LoginContext userLoginContext = new LoginContext("", userSubject, null, KerberosConfiguration.createClientConfig(userKerberosName, userKeytab)); userLoginContext.login();/*from w ww . j a v a 2 s . co m*/ Subject.doAs(userLoginContext.getSubject(), new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { final URL url = new URL("http://" + SentryServiceIntegrationBase.SERVER_HOST + ":" + SentryServiceIntegrationBase.webServerPort + "/ping"); try { new AuthenticatedURL(new KerberosAuthenticator()).openConnection(url, new AuthenticatedURL.Token()); fail("Here should fail."); } catch (AuthenticationException e) { String expectedError = "status code: 403"; if (!exceptionContainsMessage(e, expectedError)) { LOG.error("UnexpectedError: " + e.getMessage(), e); fail("UnexpectedError: " + e.getMessage()); } } return null; } }); }
From source file:org.apache.sentry.api.service.thrift.TestSentryWebServerWithKerberos.java
@Test public void testPingWithCaseSensitiveUser() throws Exception { // USER1 is present in the list of users who are allowed to connect to sentry web ui. String userPrinciple = "user1/" + SentryServiceIntegrationBase.SERVER_HOST; String userKerberosName = userPrinciple + "@" + SentryServiceIntegrationBase.REALM; Subject userSubject = new Subject(false, Sets.newHashSet(new KerberosPrincipal(userKerberosName)), new HashSet<Object>(), new HashSet<Object>()); File userKeytab = new File(SentryServiceIntegrationBase.kdcWorkDir, "user1.keytab"); SentryServiceIntegrationBase.kdc.createPrincipal(userKeytab, userPrinciple); LoginContext userLoginContext = new LoginContext("", userSubject, null, KerberosConfiguration.createClientConfig(userKerberosName, userKeytab)); userLoginContext.login();// www . j ava 2 s. c o m Subject.doAs(userLoginContext.getSubject(), new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { final URL url = new URL("http://" + SentryServiceIntegrationBase.SERVER_HOST + ":" + SentryServiceIntegrationBase.webServerPort + "/ping"); try { new AuthenticatedURL(new KerberosAuthenticator()).openConnection(url, new AuthenticatedURL.Token()); fail("Login with user1 should fail"); } catch (AuthenticationException e) { String expectedError = "status code: 403"; if (!exceptionContainsMessage(e, expectedError)) { LOG.error("UnexpectedError: " + e.getMessage(), e); fail("UnexpectedError: " + e.getMessage()); } } return null; } }); }
From source file:org.apache.sentry.provider.db.service.thrift.TestSentryWebServerWithKerberos.java
@Test public void testPingWithUnauthorizedUser() throws Exception { // create an unauthorized User with Kerberos String userPrinciple = "user/" + SERVER_HOST; String userKerberosName = userPrinciple + "@" + REALM; Subject userSubject = new Subject(false, Sets.newHashSet(new KerberosPrincipal(userKerberosName)), new HashSet<Object>(), new HashSet<Object>()); File userKeytab = new File(kdcWorkDir, "user.keytab"); kdc.createPrincipal(userKeytab, userPrinciple); LoginContext userLoginContext = new LoginContext("", userSubject, null, KerberosConfiguration.createClientConfig(userKerberosName, userKeytab)); userLoginContext.login();/*from w w w . j a v a2 s . co m*/ Subject.doAs(userLoginContext.getSubject(), new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { final URL url = new URL("http://" + SERVER_HOST + ":" + webServerPort + "/ping"); try { new AuthenticatedURL(new KerberosAuthenticator()).openConnection(url, new AuthenticatedURL.Token()); fail("Here should fail."); } catch (AuthenticationException e) { String expectedError = "status code: 403"; if (!e.getMessage().contains(expectedError)) { LOG.error("UnexpectedError: " + e.getMessage(), e); fail("UnexpectedError: " + e.getMessage()); } } return null; } }); }
From source file:org.apache.sentry.service.thrift.SentryServiceIntegrationBase.java
public static void setupConf() throws Exception { if (kerberos) { setupKdc();/*from w ww . j a va 2s .c om*/ kdc = getKdc(); kdcWorkDir = getWorkDir(); serverKeytab = new File(kdcWorkDir, "server.keytab"); clientKeytab = new File(kdcWorkDir, "client.keytab"); kdc.createPrincipal(serverKeytab, SERVER_PRINCIPAL); kdc.createPrincipal(clientKeytab, CLIENT_PRINCIPAL); conf.set(ServerConfig.PRINCIPAL, getServerKerberosName()); conf.set(ServerConfig.KEY_TAB, serverKeytab.getPath()); conf.set(ServerConfig.ALLOW_CONNECT, CLIENT_KERBEROS_SHORT_NAME); conf.set(ServerConfig.SERVER_HA_ZOOKEEPER_CLIENT_PRINCIPAL, getServerKerberosName()); conf.set(ServerConfig.SERVER_HA_ZOOKEEPER_CLIENT_KEYTAB, serverKeytab.getPath()); conf.set(ServerConfig.SECURITY_USE_UGI_TRANSPORT, "false"); clientSubject = new Subject(false, Sets.newHashSet(new KerberosPrincipal(CLIENT_KERBEROS_NAME)), new HashSet<Object>(), new HashSet<Object>()); clientLoginContext = new LoginContext("", clientSubject, null, KerberosConfiguration.createClientConfig(CLIENT_KERBEROS_NAME, clientKeytab)); clientLoginContext.login(); clientSubject = clientLoginContext.getSubject(); } else { LOGGER.info("Stopped KDC"); conf.set(ServerConfig.SECURITY_MODE, ServerConfig.SECURITY_MODE_NONE); } if (haEnabled) { zkServer = getZKServer(); conf.set(ServerConfig.SENTRY_HA_ENABLED, "true"); conf.set(ServerConfig.SENTRY_HA_ZOOKEEPER_QUORUM, zkServer.getConnectString()); conf.set(ServerConfig.SENTRY_HA_ZOOKEEPER_NAMESPACE, "sentry-test-case"); if (kerberos) { conf.set(ServerConfig.SENTRY_HA_ZOOKEEPER_SECURITY, "true"); } } if (webServerEnabled) { conf.set(ServerConfig.SENTRY_WEB_ENABLE, "true"); conf.set(ServerConfig.SENTRY_WEB_PORT, String.valueOf(webServerPort)); if (webSecurity) { httpKeytab = new File(kdcWorkDir, "http.keytab"); kdc.createPrincipal(httpKeytab, HTTP_PRINCIPAL); conf.set(ServerConfig.SENTRY_WEB_SECURITY_TYPE, ServerConfig.SENTRY_WEB_SECURITY_TYPE_KERBEROS); conf.set(ServerConfig.SENTRY_WEB_SECURITY_PRINCIPAL, HTTP_PRINCIPAL); conf.set(ServerConfig.SENTRY_WEB_SECURITY_KEYTAB, httpKeytab.getPath()); } else { conf.set(ServerConfig.SENTRY_WEB_SECURITY_TYPE, ServerConfig.SENTRY_WEB_SECURITY_TYPE_NONE); } } else { conf.set(ServerConfig.SENTRY_WEB_ENABLE, "false"); } if (pooled) { conf.set(ClientConfig.SENTRY_POOL_ENABLED, "true"); } conf.set(ServerConfig.SENTRY_VERIFY_SCHEM_VERSION, "false"); conf.set(ServerConfig.ADMIN_GROUPS, ADMIN_GROUP); conf.set(ServerConfig.RPC_ADDRESS, SERVER_HOST); conf.set(ServerConfig.RPC_PORT, String.valueOf(0)); dbDir = new File(Files.createTempDir(), "sentry_policy_db"); conf.set(ServerConfig.SENTRY_STORE_JDBC_URL, "jdbc:derby:;databaseName=" + dbDir.getPath() + ";create=true"); conf.set(ServerConfig.SENTRY_STORE_JDBC_PASS, "dummy"); server = new SentryServiceFactory().create(conf); conf.set(ClientConfig.SERVER_RPC_ADDRESS, server.getAddress().getHostName()); conf.set(ClientConfig.SERVER_RPC_PORT, String.valueOf(server.getAddress().getPort())); conf.set(ServerConfig.SENTRY_STORE_GROUP_MAPPING, ServerConfig.SENTRY_STORE_LOCAL_GROUP_MAPPING); }
From source file:org.apache.zeppelin.submarine.hadoop.YarnClient.java
public HttpResponse callRestUrl(final String url, final String userId, HTTP operation) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(String.format("Calling YarnClient %s %s %s", this.principal, this.keytab, url)); }/*from w ww . ja v a2 s . c om*/ javax.security.auth.login.Configuration config = new javax.security.auth.login.Configuration() { @SuppressWarnings("serial") @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { return new AppConfigurationEntry[] { new AppConfigurationEntry( "com.sun.security.auth.module.Krb5LoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, new HashMap<String, Object>() { { put("useTicketCache", "false"); put("useKeyTab", "true"); put("keyTab", keytab); // Krb5 in GSS API needs to be refreshed so it does not throw the error // Specified version of key is not available put("refreshKrb5Config", "true"); put("principal", principal); put("storeKey", "true"); put("doNotPrompt", "true"); put("isInitiator", "true"); if (LOGGER.isDebugEnabled()) { put("debug", "true"); } } }) }; } }; Set<Principal> principals = new HashSet<Principal>(1); principals.add(new KerberosPrincipal(userId)); Subject sub = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>()); try { // Authentication module: Krb5Login LoginContext loginContext = new LoginContext("Krb5Login", sub, null, config); loginContext.login(); Subject serviceSubject = loginContext.getSubject(); return Subject.doAs(serviceSubject, new PrivilegedAction<HttpResponse>() { HttpResponse httpResponse = null; @Override public HttpResponse run() { try { HttpUriRequest request = null; switch (operation) { case DELETE: request = new HttpDelete(url); break; case POST: request = new HttpPost(url); break; default: request = new HttpGet(url); break; } HttpClient spengoClient = buildSpengoHttpClient(); httpResponse = spengoClient.execute(request); return httpResponse; } catch (IOException e) { LOGGER.error(e.getMessage(), e); } return httpResponse; } }); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return null; }
From source file:org.getobjects.appserver.publisher.GoSimpleNamePasswordLogin.java
/** * Called by userInContext() of GoHTTPAuthenticator, or by the 'other' login() * method which can be triggered by custom login panels. * /*from www . j ava 2s. c o m*/ * @param _login - username * @param _pwd - password * @param _realm - realm * @return returns a logged-in LoginContext, or null if login failed */ public LoginContext loginInJaas(String _login, String _pwd, String _realm) { if (_login == null /* not allowed in JAAS */) { log.warn("attempt to login with a 'null' login name"); return null; } LoginContext lc = null; try { lc = new LoginContext(_realm != null ? _realm : "Go", null, /* subject (create one if missing) */ new NamePasswordCallbackHandler(_login, _pwd), this.jaasCfg); } catch (LoginException le) { log.error("could not create JAAS LoginContext", le); } if (lc != null) { try { lc.login(); } catch (LoginException le) { if (log.isInfoEnabled()) log.info("login failed: " + _login, le); lc = null; } } return lc; }