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:com.srotya.collectd.storm.StormNimbusMetrics.java
@Override public int read() { Gson gson = new Gson(); login();/*from ww w .ja v a2s . c om*/ for (String nimbus : nimbusAddresses) { Subject.doAs(subject, new PrivilegedAction<Void>() { @Override public Void run() { HttpGet request = new HttpGet(nimbus + "/api/v1/topology/summary"); CloseableHttpClient client = builder.build(); try { HttpResponse response = client.execute(request, context); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); JsonObject topologySummary = gson.fromJson(result, JsonObject.class); List<String> ids = extractTopologyIds( topologySummary.get("topologies").getAsJsonArray()); if (ids.isEmpty()) { Collectd.logInfo("No storm topologies deployed"); } for (String id : ids) { PluginData pd = new PluginData(); pd.setPluginInstance(id); pd.setTime(System.currentTimeMillis()); try { pd.setHost(new URI(nimbus).getHost()); } catch (URISyntaxException e) { continue; } ValueList values = new ValueList(pd); fetchTopologyMetrics(nimbus, id, values, builder, gson); } } else { Collectd.logError("Unable to fetch Storm metrics:" + response.getStatusLine() + "\t" + EntityUtils.toString(response.getEntity())); } client.close(); } catch (Exception e) { e.printStackTrace(); Collectd.logError( "Failed to fetch metrics from Nimbus:" + nimbus + "\treason:" + e.getMessage()); } return null; } }); } return 0; }
From source file:com.teradata.tempto.internal.hadoop.hdfs.SpnegoHttpRequestsExecutor.java
@Override public CloseableHttpResponse execute(HttpUriRequest request) throws IOException { Subject authenticationSubject = kerberosAuthentication.authenticate(); return Subject.doAs(authenticationSubject, (PrivilegedAction<CloseableHttpResponse>) () -> { try {/*from ww w.j a va 2s . c o m*/ return httpClient.execute(request, spnegoAwareHttpContext); } catch (IOException e) { throw Throwables.propagate(e); } }); }
From source file:org.apache.qpid.server.management.plugin.HttpManagementUtil.java
public static void assertManagementAccess(final SecurityManager securityManager, Subject subject) { Subject.doAs(subject, new PrivilegedAction<Void>() { @Override//from ww w . jav a2s . c o m public Void run() { securityManager.accessManagement(); return null; } }); }
From source file:com.hortonworks.streamline.streams.storm.common.StormRestAPIClient.java
private Map doPostRequestWithEmptyBody(String requestUrl) { try {//ww w . j a v a 2s . c o m LOG.debug("POST request to Storm cluster: " + requestUrl); return Subject.doAs(subject, new PrivilegedAction<Map>() { @Override public Map run() { return JsonClientUtil.postForm(client.target(requestUrl), new MultivaluedHashMap<>(), STORM_REST_API_MEDIA_TYPE, Map.class); } }); } catch (javax.ws.rs.ProcessingException e) { if (e.getCause() instanceof IOException) { throw new StormNotReachableException("Exception while requesting " + requestUrl, e); } throw e; } catch (WebApplicationException e) { throw WrappedWebApplicationException.of(e); } }
From source file:org.adeptnet.auth.kerberos.Krb5.java
public String isTicketValid(String spn, byte[] ticket) { checkCreds();//w ww.ja va2 s. c o m LoginContext ctx = null; try { if (!config.getKeytab().exists()) { throw new LoginException( String.format("KeyTab does not exist: %s", config.getKeytab().getAbsolutePath())); } final Principal principal = new KerberosPrincipal(spn, KerberosPrincipal.KRB_NT_SRV_INST); Set<Principal> principals = new HashSet<>(); principals.add(principal); final Subject subject = new Subject(false, principals, new HashSet<>(), new HashSet<>()); ctx = new LoginContext(config.getContextName(), subject, null, getJaasKrb5TicketCfg(spn)); ctx.login(); final Krb5TicketValidateAction validateAction = new Krb5TicketValidateAction(ticket, spn); final String username = Subject.doAs(subject, validateAction); return username; } catch (java.security.PrivilegedActionException | LoginException e) { LOG.fatal(spn, e); } finally { try { if (ctx != null) { ctx.logout(); } } catch (LoginException e2) { LOG.fatal(spn, e2); } } return FAILED; }
From source file:org.apache.atlas.web.filters.AtlasAuthenticationKerberosFilterTest.java
@Test(enabled = false) public void testKerberosBasedLogin() throws Exception { String originalConf = System.getProperty("atlas.conf"); setupKDCAndPrincipals();// w w w . j ava 2 s.com TestEmbeddedServer server = null; try { // setup the atlas-application.properties file String confDirectory = generateKerberosTestProperties(); System.setProperty("atlas.conf", confDirectory); // need to create the web application programmatically in order to control the injection of the test // application properties server = new TestEmbeddedServer(23000, "webapp/target/apache-atlas"); startEmbeddedServer(server.getServer()); final URLConnectionFactory connectionFactory = URLConnectionFactory.DEFAULT_SYSTEM_CONNECTION_FACTORY; // attempt to hit server and get rejected URL url = new URL("http://localhost:23000/"); HttpURLConnection connection = (HttpURLConnection) connectionFactory.openConnection(url, false); connection.setRequestMethod("GET"); connection.connect(); assertEquals(connection.getResponseCode(), 401); // need to populate the ticket cache with a local user, so logging in... Subject subject = loginTestUser(); Subject.doAs(subject, new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { // attempt to hit server and get rejected URL url = new URL("http://localhost:23000/"); HttpURLConnection connection = (HttpURLConnection) connectionFactory.openConnection(url, true); connection.setRequestMethod("GET"); connection.connect(); assertEquals(connection.getResponseCode(), 200); assertEquals(RequestContext.get().getUser(), TESTUSER); return null; } }); } finally { server.getServer().stop(); kdc.stop(); if (originalConf != null) { System.setProperty("atlas.conf", originalConf); } else { System.clearProperty("atlas.conf"); } } }
From source file:org.apache.ranger.services.sqoop.client.SqoopClient.java
public List<String> getConnectorList(final String connectorMatching, final List<String> existingConnectors) { if (LOG.isDebugEnabled()) { LOG.debug("Get sqoop connector list for connectorMatching: " + connectorMatching + ", existingConnectors: " + existingConnectors); }//w w w . ja v a 2 s.co m Subject subj = getLoginSubject(); if (subj == null) { return Collections.emptyList(); } List<String> ret = Subject.doAs(subj, new PrivilegedAction<List<String>>() { @Override public List<String> run() { ClientResponse response = getClientResponse(sqoopUrl, SQOOP_CONNECTOR_API_ENDPOINT, userName); SqoopConnectorsResponse sqoopConnectorsResponse = getSqoopResourceResponse(response, SqoopConnectorsResponse.class); if (sqoopConnectorsResponse == null || CollectionUtils.isEmpty(sqoopConnectorsResponse.getConnectors())) { return Collections.emptyList(); } List<String> connectorResponses = new ArrayList<>(); for (SqoopConnectorResponse sqoopConnectorResponse : sqoopConnectorsResponse.getConnectors()) { connectorResponses.add(sqoopConnectorResponse.getName()); } List<String> connectors = null; if (CollectionUtils.isNotEmpty(connectorResponses)) { connectors = filterResourceFromResponse(connectorMatching, existingConnectors, connectorResponses); } return connectors; } }); if (LOG.isDebugEnabled()) { LOG.debug("Get sqoop connector list result: " + ret); } return ret; }
From source file:org.apache.nifi.security.krb.AbstractKerberosUser.java
/** * Executes the PrivilegedAction as this user. * * @param action the action to execute/* w w w. ja v a 2s. co m*/ * @param <T> the type of result * @return the result of the action * @throws IllegalStateException if this method is called while not logged in */ @Override public <T> T doAs(final PrivilegedAction<T> action) throws IllegalStateException { if (!isLoggedIn()) { throw new IllegalStateException("Must login before executing actions"); } return Subject.doAs(subject, action); }
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 ww w . j ava2s.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.pentaho.di.trans.ael.websocket.SessionConfigurator.java
private Header getAuthenticationHeader(URI uri) throws RuntimeException { try {//from www . j a v a 2 s .c om ClientLoginConfig loginConfig = new ClientLoginConfig(this.keytab, this.principal); Subject serviceSubject = getServiceSubject(loginConfig); return Subject.doAs(serviceSubject, new PrivilegedAction<Header>() { public Header run() { // First try without stripping the port RuntimeException saveFirstException; try { return spnegoAuthenticate(false, uri); } catch (Exception e) { saveFirstException = new RuntimeException(e); } // if fails let's try stripping the port try { return spnegoAuthenticate(true, uri); } catch (Exception e) { //let's send the first exception throw saveFirstException; } } }); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(ERROR_MSG, e); } }