Example usage for javax.security.auth Subject doAs

List of usage examples for javax.security.auth Subject doAs

Introduction

In this page you can find the example usage for javax.security.auth Subject doAs.

Prototype

public static <T> T doAs(final Subject subject, final java.security.PrivilegedExceptionAction<T> action)
        throws java.security.PrivilegedActionException 

Source Link

Document

Perform work as a particular Subject .

Usage

From source file:org.apache.ranger.services.hive.client.HiveClient.java

public void initHive() throws Exception {
    isKerberosAuth = getConfigHolder().isKerberosAuthentication();
    if (isKerberosAuth) {
        LOG.info("Secured Mode: JDBC Connection done with preAuthenticated Subject");
        Subject.doAs(getLoginSubject(), new PrivilegedExceptionAction<Void>() {
            public Void run() throws Exception {
                initConnection();/*from ww w  .  jav  a  2  s .co m*/
                return null;
            }
        });
    } else {
        LOG.info("Since Password is NOT provided, Trying to use UnSecure client with username and password");
        final String userName = getConfigHolder().getUserName();
        final String password = getConfigHolder().getPassword();
        Subject.doAs(getLoginSubject(), new PrivilegedExceptionAction<Void>() {
            public Void run() throws Exception {
                initConnection(userName, password);
                return null;
            }
        });
    }
}

From source file:com.mycompany.kerberosbyip.NewMain.java

private void runPrivileged() throws Exception {
    final CallbackHandler handler = new ProvidedAuthCallback(username, password);
    final LoginContext lc = new LoginContext("KrbLogin", handler);
    lc.login();/* w  ww .  jav  a2 s. c om*/

    PrivilegedAction<Void> sendAction = new PrivilegedAction<Void>() {
        @Override
        public Void run() {
            try {
                doSendRequest();
                return null;
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }

        }
    };

    Subject.doAs(lc.getSubject(), sendAction);
}

From source file:com.redhat.tools.kerberos.SunJaasKerberosTicketValidator.java

public String validateTicket(byte[] token) {
    String username = null;//from   ww  w .  j a va2  s  . c o  m
    try {
        username = Subject.doAs(this.serviceSubject, new KerberosValidateAction(token));
    } catch (PrivilegedActionException e) {
        e.printStackTrace();
    }
    return username;
}

From source file:com.hortonworks.streamline.streams.storm.common.StormRestAPIClient.java

private Map doGetRequest(String requestUrl) {
    try {//from  w w w. j a v  a2  s . com
        LOG.debug("GET request to Storm cluster: " + requestUrl);
        return Subject.doAs(subject, new PrivilegedAction<Map>() {
            @Override
            public Map run() {
                return JsonClientUtil.getEntity(client.target(requestUrl), STORM_REST_API_MEDIA_TYPE,
                        Map.class);
            }
        });
    } catch (RuntimeException ex) {
        // JsonClientUtil wraps exception, so need to compare
        if (ex.getCause() instanceof javax.ws.rs.ProcessingException) {
            if (ex.getCause().getCause() instanceof IOException) {
                throw new StormNotReachableException("Exception while requesting " + requestUrl, ex);
            }
        } else if (ex.getCause() instanceof WebApplicationException) {
            throw WrappedWebApplicationException.of((WebApplicationException) ex.getCause());
        }

        throw ex;
    }
}

From source file:org.apache.ranger.hive.client.HiveClient.java

public List<String> getDatabaseList(String databaseMatching) {
    final String dbMatching = databaseMatching;
    List<String> dblist = Subject.doAs(getLoginSubject(), new PrivilegedAction<List<String>>() {
        public List<String> run() {
            return getDBList(dbMatching);
        }/*from  ww  w .  j a va 2  s  .c  o  m*/
    });
    return dblist;
}

From source file:org.apache.ws.security.spnego.SpnegoTokenContext.java

/**
 * Retrieve a service ticket from a KDC using the Kerberos JAAS module, and set it in this
 * BinarySecurityToken./*from ww w . ja va  2  s.  c o m*/
 * @param jaasLoginModuleName the JAAS Login Module name to use
 * @param callbackHandler a CallbackHandler instance to retrieve a password (optional)
 * @param serviceName the desired Kerberized service
 * @throws WSSecurityException
 */
public void retrieveServiceTicket(String jaasLoginModuleName, CallbackHandler callbackHandler,
        String serviceName) throws WSSecurityException {
    // Get a TGT from the KDC using JAAS
    LoginContext loginContext = null;
    try {
        if (callbackHandler == null) {
            loginContext = new LoginContext(jaasLoginModuleName);
        } else {
            loginContext = new LoginContext(jaasLoginModuleName, callbackHandler);
        }
        loginContext.login();
    } catch (LoginException ex) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(ex.getMessage(), ex);
        }
        throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosLoginError",
                new Object[] { ex.getMessage() }, ex);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Successfully authenticated to the TGT");
    }

    Subject clientSubject = loginContext.getSubject();
    Set<Principal> clientPrincipals = clientSubject.getPrincipals();
    if (clientPrincipals.isEmpty()) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosLoginError",
                new Object[] { "No Client principals found after login" });
    }

    // Get the service ticket
    clientAction.setServiceName(serviceName);
    clientAction.setMutualAuth(mutualAuth);
    token = (byte[]) Subject.doAs(clientSubject, clientAction);
    if (token == null) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosServiceTicketError");
    }

    secContext = clientAction.getContext();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Successfully retrieved a service ticket");
    }

}

From source file:org.apache.atlas.web.filters.MetadataAuthenticationKerberosFilterIT.java

@Test(enabled = false)
public void testKerberosBasedLogin() throws Exception {
    String originalConf = System.getProperty("metadata.conf");
    System.setProperty("metadata.conf", System.getProperty("user.dir"));

    setupKDCAndPrincipals();/*from  w  w  w.j  a v a2  s .c o m*/
    TestEmbeddedServer server = null;

    try {
        // setup the application.properties file
        generateKerberosTestProperties();

        // 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();

        Assert.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();

                Assert.assertEquals(connection.getResponseCode(), 200);

                return null;
            }
        });
    } finally {
        server.getServer().stop();
        kdc.stop();

        if (originalConf != null) {
            System.setProperty("metadata.conf", originalConf);
        } else {
            System.clearProperty("metadata.conf");
        }

    }

}

From source file:org.apache.hadoop.io.crypto.tool.kerberos.SpnegoRestCli.java

public StringBuffer getResult() throws Exception {
    AccessControlContext context = AccessController.getContext();
    Subject subject = Subject.getSubject(context);
    if (subject == null) {
        subject = new Subject();
        LoginContext login = new LoginContext("", subject, null, new KerberosConfiguration());
        login.login();//  w  ww  .j av a  2  s  . com
    }
    Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            sb = new RestClient(url).getResult();
            return null;
        }
    });
    return sb;
}

From source file:io.undertow.server.security.SpnegoAuthenticationTestCase.java

@Test
public void testSpnegoSuccess() throws Exception {

    final TestHttpClient client = new TestHttpClient();
    HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL());
    HttpResponse result = client.execute(get);
    assertEquals(StatusCodes.UNAUTHORIZED, result.getStatusLine().getStatusCode());
    Header[] values = result.getHeaders(WWW_AUTHENTICATE.toString());
    String header = getAuthHeader(NEGOTIATE, values);
    assertEquals(NEGOTIATE.toString(), header);
    HttpClientUtils.readResponse(result);

    Subject clientSubject = login("jduke", "theduke".toCharArray());

    Subject.doAs(clientSubject, new PrivilegedExceptionAction<Void>() {

        @Override/* w w  w  . jav a  2 s .  co m*/
        public Void run() throws Exception {
            GSSManager gssManager = GSSManager.getInstance();
            GSSName serverName = gssManager
                    .createName("HTTP/" + DefaultServer.getDefaultServerAddress().getHostString(), null);

            GSSContext context = gssManager.createContext(serverName, SPNEGO, null,
                    GSSContext.DEFAULT_LIFETIME);

            byte[] token = new byte[0];

            boolean gotOur200 = false;
            while (!context.isEstablished()) {
                token = context.initSecContext(token, 0, token.length);

                if (token != null && token.length > 0) {
                    HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL());
                    get.addHeader(AUTHORIZATION.toString(),
                            NEGOTIATE + " " + FlexBase64.encodeString(token, false));
                    HttpResponse result = client.execute(get);

                    Header[] headers = result.getHeaders(WWW_AUTHENTICATE.toString());
                    if (headers.length > 0) {
                        String header = getAuthHeader(NEGOTIATE, headers);

                        byte[] headerBytes = header.getBytes(StandardCharsets.US_ASCII);
                        // FlexBase64.decode() returns byte buffer, which can contain backend array of greater size.
                        // when on such ByteBuffer is called array(), it returns the underlying byte array including the 0 bytes
                        // at the end, which makes the token invalid. => using Base64 mime decoder, which returnes directly properly sized byte[].
                        token = Base64.getMimeDecoder().decode(ArrayUtils.subarray(headerBytes,
                                NEGOTIATE.toString().length() + 1, headerBytes.length));
                    }

                    if (result.getStatusLine().getStatusCode() == StatusCodes.OK) {
                        Header[] values = result.getHeaders("ProcessedBy");
                        assertEquals(1, values.length);
                        assertEquals("ResponseHandler", values[0].getValue());
                        HttpClientUtils.readResponse(result);
                        assertSingleNotificationType(EventType.AUTHENTICATED);
                        gotOur200 = true;
                    } else if (result.getStatusLine().getStatusCode() == StatusCodes.UNAUTHORIZED) {
                        assertTrue("We did get a header.", headers.length > 0);

                        HttpClientUtils.readResponse(result);

                    } else {
                        fail(String.format("Unexpected status code %d",
                                result.getStatusLine().getStatusCode()));
                    }
                }
            }

            assertTrue(gotOur200);
            assertTrue(context.isEstablished());
            return null;
        }
    });
}

From source file:org.apache.ranger.services.hive.client.HiveClient.java

public List<String> getDatabaseList(String databaseMatching, final List<String> databaseList)
        throws HadoopException {
    final String dbMatching = databaseMatching;
    final List<String> dbList = databaseList;
    List<String> dblist = Subject.doAs(getLoginSubject(), new PrivilegedAction<List<String>>() {
        public List<String> run() {
            List<String> ret = null;
            try {
                ret = getDBList(dbMatching, dbList);
            } catch (HadoopException he) {
                LOG.error("<== HiveClient getDatabaseList() :Unable to get the Database List", he);
                throw he;
            }/*from w w  w.ja  v  a  2 s  .co m*/
            return ret;
        }
    });
    return dblist;
}