List of usage examples for javax.security.auth Subject doAs
public static <T> T doAs(final Subject subject, final java.security.PrivilegedExceptionAction<T> action) throws java.security.PrivilegedActionException
From source file:org.apache.coheigea.cxf.kerberos.authentication.TokenPreAuthTest.java
private void validateServiceTicket(byte[] ticket) throws Exception { // Get the TGT for the service LoginContext loginContext = new LoginContext("bob", new KerberosCallbackHandler()); loginContext.login();/* w w w .j a v a 2 s.c o m*/ Subject serviceSubject = loginContext.getSubject(); Set<Principal> servicePrincipals = serviceSubject.getPrincipals(); assertFalse(servicePrincipals.isEmpty()); // Handle the service ticket KerberosServiceExceptionAction serviceAction = new KerberosServiceExceptionAction(ticket, "bob@service.ws.apache.org"); Subject.doAs(serviceSubject, serviceAction); }
From source file:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java
@Test public void testSaslGssapiLdapAuth() throws Exception { final Hashtable<String, String> env = new Hashtable<>(); env.put(Context.PROVIDER_URL, "ldap://localhost:1024"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI"); LoginContext loginContext = new LoginContext("broker-sasl-gssapi"); loginContext.login();/*from w w w . jav a2s.c o m*/ try { Subject.doAs(loginContext.getSubject(), (PrivilegedExceptionAction<Object>) () -> { HashSet<String> set = new HashSet<>(); DirContext ctx = new InitialDirContext(env); NamingEnumeration<NameClassPair> list = ctx.list("ou=system"); while (list.hasMore()) { NameClassPair ncp = list.next(); set.add(ncp.getName()); } Assert.assertTrue(set.contains("uid=first")); Assert.assertTrue(set.contains("cn=users")); Assert.assertTrue(set.contains("ou=configuration")); Assert.assertTrue(set.contains("prefNodeName=sysPrefRoot")); ctx.close(); return null; }); } catch (PrivilegedActionException e) { throw e.getException(); } }
From source file:org.apache.ranger.biz.KmsKeyMgr.java
public VXKmsKey createKey(String provider, VXKmsKey vXKey) throws Exception { String providers[] = null;/*from w ww. j ava 2s. c o m*/ try { providers = getKMSURL(provider); } catch (Exception e) { logger.error("createKey(" + provider + ", " + vXKey.getName() + ") failed", e); } VXKmsKey ret = null; boolean isKerberos = false; try { isKerberos = checkKerberos(); } catch (Exception e1) { logger.error("checkKerberos(" + provider + ") failed", e1); } if (providers != null) { for (int i = 0; i < providers.length; i++) { Client c = getClient(); String currentUserLoginId = ContextUtil.getCurrentUserLoginId(); String uri = providers[i] + (providers[i].endsWith("/") ? KMS_ADD_KEY_URI : ("/" + KMS_ADD_KEY_URI)); if (!isKerberos) { uri = uri.concat("?user.name=" + currentUserLoginId); } else { uri = uri.concat("?doAs=" + currentUserLoginId); } final WebResource r = c.resource(uri); Gson gson = new GsonBuilder().create(); final String jsonString = gson.toJson(vXKey); try { String response = null; if (!isKerberos) { response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE) .post(String.class, jsonString); } else { Subject sub = getSubjectForKerberos(provider); response = Subject.doAs(sub, new PrivilegedAction<String>() { @Override public String run() { return r.accept(MediaType.APPLICATION_JSON_TYPE) .type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString); } }); } logger.debug("Create RESPONSE: [" + response + "]"); ret = gson.fromJson(response, VXKmsKey.class); return ret; } catch (Exception e) { if (e instanceof UniformInterfaceException || i == providers.length - 1) throw e; else continue; } } } return ret; }
From source file:com.xebialabs.overthere.winrm.WinRmClient.java
/** * Performs the JAAS login and run the sendRequest method within a privileged scope. *///w w w.ja va 2 s. c o m private Document runPrivileged(final PrivilegedSendMessage privilegedSendMessage) { final CallbackHandler handler = new ProvidedAuthCallback(username, password); Document result; try { final LoginContext lc = new LoginContext("", null, handler, new KerberosJaasConfiguration(kerberosDebug, kerberosTicketCache)); lc.login(); result = Subject.doAs(lc.getSubject(), privilegedSendMessage); } catch (LoginException e) { throw new WinRmRuntimeIOException( "Login failure sending message on " + targetURL + " error: " + e.getMessage(), privilegedSendMessage.getRequestDocument(), null, e); } catch (PrivilegedActionException e) { throw new WinRmRuntimeIOException( "Failure sending message on " + targetURL + " error: " + e.getMessage(), privilegedSendMessage.getRequestDocument(), null, e.getException()); } return result; }
From source file:org.apache.ranger.services.hbase.client.HBaseClient.java
public List<String> getColumnFamilyList(final String columnFamilyMatching, final List<String> tableList, final List<String> existingColumnFamilies) { if (LOG.isDebugEnabled()) { LOG.debug("==> HbaseClient.getColumnFamilyList() columnFamilyMatching " + columnFamilyMatching + " ExisitingTableList " + tableList + "existingColumnFamilies " + existingColumnFamilies); }/*from w ww . j a v a 2 s . c om*/ List<String> ret = null; 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 ranger_admin.log for more info."; subj = getLoginSubject(); if (subj != null) { try { ret = Subject.doAs(subj, new PrivilegedAction<List<String>>() { String tblName = null; @Override public List<String> run() { List<String> colfList = new ArrayList<String>(); HBaseAdmin admin = null; try { LOG.info("getColumnFamilyList: setting config values from client"); setClientConfigValues(conf); LOG.info("getColumnFamilyList: checking HbaseAvailability with the new config"); HBaseAdmin.checkHBaseAvailable(conf); LOG.info("getColumnFamilyList: no exception: HbaseAvailability true"); admin = new HBaseAdmin(conf); if (tableList != null) { for (String tableName : tableList) { tblName = tableName; HTableDescriptor htd = admin.getTableDescriptor(tblName.getBytes()); if (htd != null) { for (HColumnDescriptor hcd : htd.getColumnFamilies()) { String colf = hcd.getNameAsString(); if (colf.matches(columnFamilyMatching)) { if (existingColumnFamilies != null && existingColumnFamilies.contains(colf)) { continue; } else { colfList.add(colf); } } } } } } } catch (ZooKeeperConnectionException zce) { String msgDesc = "getColumnFamilyList: Unable to connect to `ZooKeeper` " + "using given config parameters."; HadoopException hdpException = new HadoopException(msgDesc, zce); hdpException.generateResponseDataMap(false, getMessage(zce), msgDesc + errMsg, null, null); LOG.error(msgDesc + zce); throw hdpException; } catch (MasterNotRunningException mnre) { String msgDesc = "getColumnFamilyList: Looks like `Master` is not running, " + "so couldn't check that running HBase is available or not, " + "Please try again later."; HadoopException hdpException = new HadoopException(msgDesc, mnre); hdpException.generateResponseDataMap(false, getMessage(mnre), msgDesc + errMsg, null, null); LOG.error(msgDesc + mnre); throw hdpException; } catch (IOException io) { String msgDesc = "getColumnFamilyList: Unable to get HBase ColumnFamilyList for " + "[repository:" + getConfigHolder().getDatasourceName() + ",table:" + tblName + ", table-match:" + columnFamilyMatching + "] "; HadoopException hdpException = new HadoopException(msgDesc, io); hdpException.generateResponseDataMap(false, getMessage(io), msgDesc + errMsg, null, null); LOG.error(msgDesc + io); throw hdpException; } catch (SecurityException se) { String msgDesc = "getColumnFamilyList: Unable to get HBase ColumnFamilyList for " + "[repository:" + getConfigHolder().getDatasourceName() + ",table:" + tblName + ", table-match:" + columnFamilyMatching + "] "; HadoopException hdpException = new HadoopException(msgDesc, se); hdpException.generateResponseDataMap(false, getMessage(se), msgDesc + errMsg, null, null); LOG.error(msgDesc + se); throw hdpException; } catch (Throwable e) { String msgDesc = "getColumnFamilyList: Unable to get HBase ColumnFamilyList for " + "[repository:" + getConfigHolder().getDatasourceName() + ",table:" + tblName + ", table-match:" + columnFamilyMatching + "] "; LOG.error(msgDesc); HadoopException hdpException = new HadoopException(msgDesc, e); hdpException.generateResponseDataMap(false, getMessage(e), msgDesc + errMsg, null, null); LOG.error(msgDesc + e); throw hdpException; } finally { if (admin != null) { try { admin.close(); } catch (IOException e) { LOG.error("Unable to close HBase connection [" + getConfigHolder().getDatasourceName() + "]", e); } } } return colfList; } }); } catch (SecurityException se) { String msgDesc = "getColumnFamilyList: Unable to connect to HBase Server instance "; HadoopException hdpException = new HadoopException(msgDesc, se); hdpException.generateResponseDataMap(false, getMessage(se), msgDesc + errMsg, null, null); LOG.error(msgDesc + se); throw hdpException; } } if (LOG.isDebugEnabled()) { LOG.debug("<== HbaseClient.getColumnFamilyList() " + ret); } return ret; }
From source file:com.xebialabs.overthere.cifs.winrm.WinRmClient.java
/** * Performs the JAAS login and run the sendRequest method within a privileged scope. */// w ww . j ava 2 s . com private Document runPrivileged(final PrivilegedSendMessage privilegedSendMessage) { final CallbackHandler handler = new ProvidedAuthCallback(username, password); Document result; try { final LoginContext lc = new LoginContext("", null, handler, new KerberosJaasConfiguration(kerberosDebug)); lc.login(); result = Subject.doAs(lc.getSubject(), privilegedSendMessage); } catch (LoginException e) { throw new WinRmRuntimeIOException( "Login failure sending message on " + targetURL + " error: " + e.getMessage(), privilegedSendMessage.getRequestDocument(), null, e); } catch (PrivilegedActionException e) { throw new WinRmRuntimeIOException( "Failure sending message on " + targetURL + " error: " + e.getMessage(), privilegedSendMessage.getRequestDocument(), null, e.getException()); } return result; }
From source file:org.alfresco.repo.webdav.auth.BaseKerberosAuthenticationFilter.java
/** * Perform a Kerberos login and return an SPNEGO response * //from w w w . jav a2 s . co m * @param negToken NegTokenInit * @param req HttpServletRequest * @param resp HttpServletResponse * @param httpSess HttpSession * @return NegTokenTarg */ private final NegTokenTarg doKerberosLogon(NegTokenInit negToken, HttpServletRequest req, HttpServletResponse resp, HttpSession httpSess) { // Authenticate the user KerberosDetails krbDetails = null; String userName = null; NegTokenTarg negTokenTarg = null; try { // Run the session setup as a privileged action SessionSetupPrivilegedAction sessSetupAction = new SessionSetupPrivilegedAction(m_accountName, negToken.getMechtoken()); Object result = Subject.doAs(m_loginContext.getSubject(), sessSetupAction); if (result != null) { // Access the Kerberos response krbDetails = (KerberosDetails) result; userName = m_stripKerberosUsernameSuffix ? krbDetails.getUserName() : krbDetails.getSourceName(); // Create the NegTokenTarg response blob negTokenTarg = new NegTokenTarg(SPNEGO.AcceptCompleted, OID.KERBEROS5, krbDetails.getResponseToken()); // Check if the user has been authenticated, if so then setup the user environment if (negTokenTarg != null) { // Create and store the user authentication context SessionUser user = createUserEnvironment(httpSess, userName); // Debug if (getLogger().isDebugEnabled()) getLogger().debug("User " + user.getUserName() + " logged on via Kerberos"); } } else { // Debug if (getLogger().isDebugEnabled()) getLogger().debug("No SPNEGO response, Kerberos logon failed"); } } catch (AuthenticationException ex) { // Pass on validation failures if (getLogger().isDebugEnabled()) getLogger().debug("Failed to validate user " + userName, ex); throw ex; } catch (Exception ex) { // Log the error if (getLogger().isDebugEnabled()) getLogger().debug("Kerberos logon error", ex); } // Return the response SPNEGO blob return negTokenTarg; }
From source file:org.apache.ranger.biz.KmsKeyMgr.java
public VXKmsKey getKey(String provider, String name) throws Exception { String providers[] = null;/*from ww w . j a va 2 s . c o m*/ try { providers = getKMSURL(provider); } catch (Exception e) { logger.error("getKey(" + provider + ", " + name + ") failed", e); } boolean isKerberos = false; try { isKerberos = checkKerberos(); } catch (Exception e1) { logger.error("checkKerberos(" + provider + ") failed", e1); } if (providers != null) { for (int i = 0; i < providers.length; i++) { Client c = getClient(); String keyRest = KMS_KEY_METADATA_URI.replaceAll(Pattern.quote("${alias}"), name); String currentUserLoginId = ContextUtil.getCurrentUserLoginId(); String uri = providers[i] + (providers[i].endsWith("/") ? keyRest : ("/" + keyRest)); if (!isKerberos) { uri = uri.concat("?user.name=" + currentUserLoginId); } else { uri = uri.concat("?doAs=" + currentUserLoginId); } final WebResource r = c.resource(uri); try { String response = null; if (!isKerberos) { response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE) .get(String.class); } else { Subject sub = getSubjectForKerberos(provider); response = Subject.doAs(sub, new PrivilegedAction<String>() { @Override public String run() { return r.accept(MediaType.APPLICATION_JSON_TYPE) .type(MediaType.APPLICATION_JSON_TYPE).get(String.class); } }); } Gson gson = new GsonBuilder().create(); logger.debug("RESPONSE: [" + response + "]"); VXKmsKey key = gson.fromJson(response, VXKmsKey.class); return key; } catch (Exception e) { if (e instanceof UniformInterfaceException || i == providers.length - 1) throw e; else continue; } } } return null; }
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 w w. j a v a 2 s . c o m*/ 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; }