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:com.jivesoftware.authHelper.customescheme.negotiate.CustomNegotiateScheme.java

/**
 * Init GSSContext for negotiation.//from   ww w. j  a v  a 2 s  .co  m
 *
 * @param server servername only (e.g: radar.it.su.se)
 */
protected void init(String server, UsernamePasswordCredentials credentials) throws GSSException {
    LOG.info("init " + server);

    // Create a callback handler
    Configuration.setConfiguration(null);
    CallbackHandler callbackHandler = new CustomNegotiateCallbackHandler(credentials.getUserName(),
            credentials.getPassword());
    PrivilegedExceptionAction action = new MyAction(server);
    LoginContext con = null;

    try {
        CustomConfiguration cc = getCustomConfiguration(credentials);

        // Create a LoginContext with a callback handler
        con = new LoginContext("com.sun.security.jgss.login", null, callbackHandler, cc);

        Configuration.setConfiguration(cc);
        // Perform authentication
        con.login();
    } catch (LoginException e) {
        System.err.println("Login failed");
        e.printStackTrace();
        // System.exit(-1);
        throw new RuntimeException(e);
    } catch (Exception e) {
        System.err.println("Login failed");
        e.printStackTrace();
        // System.exit(-1);
        throw new RuntimeException(e);
    }

    // Perform action as authenticated user
    Subject subject = con.getSubject();
    //LOG.trace("Subject is :"+ subject.toString());

    LOG.info("Authenticated principal:**** " + subject.getPrincipals());

    try {
        Subject.doAs(subject, action);
    } catch (PrivilegedActionException e) {
        e.printStackTrace();

    } catch (Exception e) {
        e.printStackTrace();

    }

}

From source file:org.apache.ranger.services.hbase.client.HBaseClient.java

public boolean getHBaseStatus() throws HadoopException {
    boolean hbaseStatus = false;
    subj = getLoginSubject();/*  w  w  w .j  a  v a2  s. c om*/
    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.";
    if (subj != null) {
        try {

            hbaseStatus = Subject.doAs(subj, new PrivilegedAction<Boolean>() {
                @Override
                public Boolean run() {
                    Boolean hbaseStatus1 = false;
                    try {
                        LOG.info("getHBaseStatus: creating default Hbase configuration");

                        LOG.info("getHBaseStatus: setting config values from client");
                        setClientConfigValues(conf);
                        LOG.info("getHBaseStatus: checking HbaseAvailability with the new config");
                        HBaseAdmin.checkHBaseAvailable(conf);
                        LOG.info("getHBaseStatus: no exception: HbaseAvailability true");
                        hbaseStatus1 = true;
                    } catch (ZooKeeperConnectionException zce) {
                        String msgDesc = "getHBaseStatus: 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 = "getHBaseStatus: 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 (ServiceException se) {
                        String msgDesc = "getHBaseStatus: Unable to check availability of "
                                + "Hbase environment [" + getConfigHolder().getDatasourceName() + "].";
                        HadoopException hdpException = new HadoopException(msgDesc, se);
                        hdpException.generateResponseDataMap(false, getMessage(se), msgDesc + errMsg, null,
                                null);
                        LOG.error(msgDesc + se);
                        throw hdpException;

                    } catch (IOException io) {
                        String msgDesc = "getHBaseStatus: Unable to check availability of"
                                + " Hbase environment [" + getConfigHolder().getDatasourceName() + "].";
                        HadoopException hdpException = new HadoopException(msgDesc, io);
                        hdpException.generateResponseDataMap(false, getMessage(io), msgDesc + errMsg, null,
                                null);
                        LOG.error(msgDesc + io);
                        throw hdpException;

                    } catch (Throwable e) {
                        String msgDesc = "getHBaseStatus: Unable to check availability of"
                                + " Hbase environment [" + getConfigHolder().getDatasourceName() + "].";
                        LOG.error(msgDesc + e);
                        hbaseStatus1 = false;
                        HadoopException hdpException = new HadoopException(msgDesc, e);
                        hdpException.generateResponseDataMap(false, getMessage(e), msgDesc + errMsg, null,
                                null);
                        throw hdpException;
                    }
                    return hbaseStatus1;
                }
            });
        } catch (SecurityException se) {
            String msgDesc = "getHBaseStatus: 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;
        }
    } else {
        LOG.error("getHBaseStatus: secure login not done, subject is null");
    }

    return hbaseStatus;
}

From source file:org.apache.ws.security.message.token.KerberosSecurity.java

/**
 * Retrieve a service ticket from a KDC using the Kerberos JAAS module, and set it in this
 * BinarySecurityToken./*  w  ww  .j av  a 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" });
    }
    // Store the TGT
    KerberosTicket tgt = getKerberosTicket(clientSubject, null);

    // Get the service ticket
    KerberosClientAction action = new KerberosClientAction(clientPrincipals.iterator().next(), serviceName);
    byte[] ticket = (byte[]) Subject.doAs(clientSubject, action);
    if (ticket == null) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosServiceTicketError");
    }
    if (log.isDebugEnabled()) {
        log.debug("Successfully retrieved a service ticket");
    }

    // Get the Service Ticket (private credential)
    KerberosTicket serviceTicket = getKerberosTicket(clientSubject, tgt);
    if (serviceTicket != null) {
        secretKey = serviceTicket.getSessionKey();
    }

    setToken(ticket);

    if ("".equals(getValueType())) {
        setValueType(WSConstants.WSS_GSS_KRB_V5_AP_REQ);
    }
}

From source file:com.zimbra.cs.security.sasl.GssAuthenticator.java

@Override
public boolean initialize() throws IOException {
    Krb5Keytab keytab = getKeytab(LC.krb5_keytab.value());
    if (keytab == null) {
        sendFailed("mechanism not supported");
        return false;
    }/*from   w  w  w  .j a  v  a 2 s.  c o m*/
    debug("keytab file = %s", keytab.getFile());

    final String host;
    if (LC.krb5_service_principal_from_interface_address.booleanValue()) {
        String localSocketHostname = localAddress.getCanonicalHostName().toLowerCase();
        if (localSocketHostname.length() == 0 || Character.isDigit(localSocketHostname.charAt(0)))
            localSocketHostname = LC.zimbra_server_hostname.value();
        host = localSocketHostname;
    } else {
        host = LC.zimbra_server_hostname.value();
    }

    KerberosPrincipal kp = new KerberosPrincipal(getProtocol() + '/' + host);
    debug("kerberos principal = %s", kp);
    Subject subject = getSubject(keytab, kp);
    if (subject == null) {
        sendFailed();
        return false;
    }
    debug("subject = %s", subject);

    final Map<String, String> props = getSaslProperties();
    if (DEBUG && props != null) {
        String qop = props.get(Sasl.QOP);
        debug("Sent QOP = " + (qop != null ? qop : "auth"));
    }

    try {
        mSaslServer = (SaslServer) Subject.doAs(subject, new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws SaslException {
                return Sasl.createSaslServer(getMechanism(), getProtocol(), host, props,
                        new GssCallbackHandler());
            }
        });
    } catch (PrivilegedActionException e) {
        sendFailed();
        getLog().warn("Could not create SaslServer", e.getCause());
        return false;
    }
    return true;
}

From source file:org.jolokia.jvmagent.JolokiaHttpHandler.java

/**
 * Handle a request. If the handler is not yet started, an exception is thrown. If running with JAAS
 * security enabled it will run as the given subject.
 *
 * @param pHttpExchange the request/response object
 * @throws IOException if something fails during handling
 * @throws IllegalStateException if the handler has not yet been started
 *//*from  w  w  w.j  ava  2  s.  co  m*/
public void handle(final HttpExchange pHttpExchange) throws IOException {
    Subject subject = (Subject) pHttpExchange.getAttribute(ConfigKey.JAAS_SUBJECT_REQUEST_ATTRIBUTE);
    if (subject != null) {
        try {
            Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {
                public Void run() throws IOException {
                    doHandle(pHttpExchange);
                    return null;
                }
            });
        } catch (PrivilegedActionException e) {
            throw new SecurityException("Security exception: " + e.getCause(), e.getCause());
        }
    } else {
        doHandle(pHttpExchange);
    }
}

From source file:org.apache.ranger.hadoop.client.HadoopFS.java

public List<String> listFiles(final String baseDir, final String fileMatching) {

    PrivilegedAction<List<String>> action = new PrivilegedAction<List<String>>() {
        @Override//from w w  w . j a  v a  2s  . co m
        public List<String> run() {
            return listFilesInternal(baseDir, fileMatching);
        }

    };
    return Subject.doAs(getLoginSubject(), action);
}

From source file:org.wso2.carbon.identity.application.authenticator.iwa.IWAAuthenticationUtil.java

/**
 * Create GSSCredential as Subject//  w w w  . j a  v  a2 s .  c  o  m
 *
 * @param subject login context subject
 * @return GSSCredential
 * @throws PrivilegedActionException
 */
private static GSSCredential createCredentialsForSubject(final Subject subject)
        throws PrivilegedActionException {
    final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() {
        public GSSCredential run() throws GSSException {
            return gssManager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME,
                    GSSUtil.GSS_SPNEGO_MECH_OID, GSSCredential.ACCEPT_ONLY);
        }
    };

    if (log.isDebugEnabled()) {
        Set<Principal> principals = subject.getPrincipals();
        String principalName = null;
        if (principals != null) {
            principalName = principals.toString();
        }
        log.debug("Creating gss credentials as principal : " + principalName);
    }
    return Subject.doAs(subject, action);
}

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

/**
 * Validate a service ticket.//ww  w. j  a v  a  2 s . co m
 * @param jaasLoginModuleName
 * @param callbackHandler
 * @param serviceName
 * @param ticket
 * @throws WSSecurityException
 */
public void validateServiceTicket(String jaasLoginModuleName, CallbackHandler callbackHandler,
        String serviceName, byte[] ticket) 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");
    }

    // Get the service name to use - fall back on the principal
    Subject subject = loginContext.getSubject();
    String service = serviceName;
    if (service == null) {
        Set<Principal> principals = subject.getPrincipals();
        if (principals.isEmpty()) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosLoginError",
                    new Object[] { "No Client principals found after login" });
        }
        service = principals.iterator().next().getName();
    }

    // Validate the ticket
    serviceAction.setTicket(ticket);
    serviceAction.setServiceName(service);
    token = (byte[]) Subject.doAs(subject, serviceAction);

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

}

From source file:org.apache.hadoop.gateway.identityasserter.function.UsernameFunctionProcessorTest.java

@Test
public void testResolve() throws Exception {
    final UsernameFunctionProcessor processor = new UsernameFunctionProcessor();
    assertThat(processor.resolve(null, null), nullValue());
    assertThat(processor.resolve(null, Arrays.asList("test-input")), contains("test-input"));
    Subject subject = new Subject();
    subject.getPrincipals().add(new PrimaryPrincipal("test-username"));
    subject.setReadOnly();/*from  ww  w  . ja v  a2 s.  co  m*/
    Subject.doAs(subject, new PrivilegedExceptionAction<Object>() {
        @Override
        public Object run() throws Exception {
            assertThat(processor.resolve(null, null), contains("test-username"));
            assertThat(processor.resolve(null, Arrays.asList("test-ignored")), contains("test-username"));
            return null;
        }
    });
}

From source file:org.apache.lens.client.SpnegoClientFilter.java

private byte[] getToken(String spn, Oid oid) throws GSSException, LoginException {
    LoginContext lc = buildLoginContext();
    lc.login();/*w w  w. java 2  s .c  om*/
    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 {
        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;
    }
}