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.hadoop.gateway.provider.federation.jwt.filter.JWTFederationFilter.java

private void continueWithEstablishedSecurityContext(Subject subject, final HttpServletRequest request,
        final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException {
    try {/*w ww .ja  v a  2  s .  c om*/
        Subject.doAs(subject, new PrivilegedExceptionAction<Object>() {
            @Override
            public Object run() throws Exception {
                chain.doFilter(request, response);
                return null;
            }
        });
    } catch (PrivilegedActionException e) {
        Throwable t = e.getCause();
        if (t instanceof IOException) {
            throw (IOException) t;
        } else if (t instanceof ServletException) {
            throw (ServletException) t;
        } else {
            throw new ServletException(t);
        }
    }
}

From source file:org.sakaiproject.component.kerberos.user.JassAuthenticate.java

public boolean attemptAuthentication(String username, String password) {
    LoginContext userLoginContext = null;
    LoginContext serverLoginContext = null;

    try {//from  w  ww .  jav a 2s .  c  om
        // This may well fail so run catch exceptions here.
        try {
            userLoginContext = new LoginContext(userPrincipal,
                    new UsernamePasswordCallback(username, password));
            userLoginContext.login();
        } catch (LoginException le) {
            if (log.isDebugEnabled()) {
                log.debug("Failed to authenticate " + username, le);
            }
            return false;
        }
        if (!verifyServiceTicket) {
            log.debug("Authenticated ok and not attempting service ticket verification");
            return true;
        }
        // Shouldn't ever fail
        serverLoginContext = new LoginContext(servicePrincipal, new NullCallbackHandler());
        serverLoginContext.login();

        GSSManager manager = GSSManager.getInstance();
        Oid kerberos = new Oid("1.2.840.113554.1.2.2");

        GSSName serverName = manager.createName(serverGSS, GSSName.NT_HOSTBASED_SERVICE);

        clientContext = manager.createContext(serverName, kerberos, null, GSSContext.DEFAULT_LIFETIME);

        serverContext = manager.createContext((GSSCredential) null);

        int exchanges = 0;
        while (!clientContext.isEstablished() && !serverContext.isEstablished()
                && !(initTokens == null && acceptTokens == null)) {
            Subject.doAs(userLoginContext.getSubject(), new InitiatorAction());
            Subject.doAs(serverLoginContext.getSubject(), new AcceptorAction());
            if (++exchanges > exchangeLimit) {
                throw new RuntimeException("Too many tickets exchanged (" + exchangeLimit + ").");
            }
        }
        log.debug("Authenticated ok and verified service ticket");
        return true;
    } catch (GSSException gsse) {
        log.warn("Failed to verify ticket.", gsse);
    } catch (LoginException le) {
        log.warn("Failed to login with keytab.", le);
    } finally {
        try {
            if (clientContext != null)
                clientContext.dispose();
            if (serverContext != null)
                serverContext.dispose();

            if (userLoginContext != null)
                userLoginContext.logout();
            if (serverLoginContext != null)
                serverLoginContext.logout();
        } catch (Exception e) {
            log.error("Failed to tidy up after attempting authentication.", e);
        }
    }
    return false;
}

From source file:io.druid.security.kerberos.DruidKerberosAuthenticationHandler.java

@Override
public void init(Properties config) throws ServletException {
    try {/*  w  w  w  .  j  a va  2s  .com*/
        String principal = config.getProperty(PRINCIPAL);
        if (principal == null || principal.trim().length() == 0) {
            throw new ServletException("Principal not defined in configuration");
        }
        keytab = config.getProperty(KEYTAB, keytab);
        if (keytab == null || keytab.trim().length() == 0) {
            throw new ServletException("Keytab not defined in configuration");
        }
        if (!new File(keytab).exists()) {
            throw new ServletException("Keytab does not exist: " + keytab);
        }

        // use all SPNEGO principals in the keytab if a principal isn't
        // specifically configured
        final String[] spnegoPrincipals;
        if (principal.equals("*")) {
            spnegoPrincipals = KerberosUtil.getPrincipalNames(keytab, Pattern.compile("HTTP/.*"));
            if (spnegoPrincipals.length == 0) {
                throw new ServletException("Principals do not exist in the keytab");
            }
        } else {
            spnegoPrincipals = new String[] { principal };
        }

        String nameRules = config.getProperty(NAME_RULES, null);
        if (nameRules != null) {
            KerberosName.setRules(nameRules);
        }

        for (String spnegoPrincipal : spnegoPrincipals) {
            log.info("Login using keytab %s, for principal %s", keytab, spnegoPrincipal);
            final KerberosAuthenticator.DruidKerberosConfiguration kerberosConfiguration = new KerberosAuthenticator.DruidKerberosConfiguration(
                    keytab, spnegoPrincipal);
            final LoginContext loginContext = new LoginContext("", serverSubject, null, kerberosConfiguration);
            try {
                loginContext.login();
            } catch (LoginException le) {
                log.warn(le, "Failed to login as [%s]", spnegoPrincipal);
                throw new AuthenticationException(le);
            }
            loginContexts.add(loginContext);
        }
        try {
            gssManager = Subject.doAs(serverSubject, new PrivilegedExceptionAction<GSSManager>() {

                @Override
                public GSSManager run() throws Exception {
                    return GSSManager.getInstance();
                }
            });
        } catch (PrivilegedActionException ex) {
            throw ex.getException();
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}

From source file:org.apache.nifi.security.krb.AbstractKerberosUser.java

/**
 * Executes the PrivilegedAction as this user.
 *
 * @param action the action to execute/*from  w  w  w  . j  av a2  s .c om*/
 * @param <T> the type of result
 * @return the result of the action
 * @throws IllegalStateException if this method is called while not logged in
 * @throws PrivilegedActionException if an exception is thrown from the action
 */
@Override
public <T> T doAs(final PrivilegedExceptionAction<T> action)
        throws IllegalStateException, PrivilegedActionException {
    if (!isLoggedIn()) {
        throw new IllegalStateException("Must login before executing actions");
    }

    return Subject.doAs(subject, action);
}

From source file:com.qut.middleware.esoe.authn.plugins.spnego.authenticator.KerberosV5Authenticator.java

@SuppressWarnings("unchecked")
private String loginAndAction(String loginContextName, KerberosAuthenticationAction actionToPerform) {
    LoginContext context = null;/*from ww w . j  a  v  a  2 s  . c  o m*/

    try {
        // Create a LoginContext 
        context = new LoginContext(loginContextName, null, null, this.config);

        this.logger.trace(Messages.getString("KerberosV5Authenticator.7") + loginContextName); //$NON-NLS-1$

        // Perform server authentication
        context.login();

        Subject subject = context.getSubject();
        this.logger.trace(subject.toString());
        this.logger.trace(Messages.getString("KerberosV5Authenticator.8") + subject.getPrincipals()); //$NON-NLS-1$

        // perform kerberos validation
        return (String) (Subject.doAs(subject, actionToPerform));

    } catch (LoginException e) {
        this.logger.warn(Messages.getString("KerberosV5Authenticator.9")); //$NON-NLS-1$
        this.logger.trace(e.getLocalizedMessage(), e);

        return null;
    } catch (PrivilegedActionException e) {
        this.logger.trace(e.getLocalizedMessage(), e);
        this.logger.trace(Messages.getString("KerberosV5Authenticator.10") + e.getCause().getMessage()); //$NON-NLS-1$

        return null;
    } catch (Exception e) {
        this.logger.debug(Messages.getString("KerberosV5Authenticator.11") + e.getCause().getMessage()); //$NON-NLS-1$
        this.logger.trace(e.getLocalizedMessage(), e);

        return null;
    }

}

From source file:org.apache.druid.security.kerberos.DruidKerberosAuthenticationHandler.java

@Override
public void init(Properties config) throws ServletException {
    try {/*  w  w  w .j  a  v  a  2  s  .co  m*/
        String principal = config.getProperty(PRINCIPAL);
        if (principal == null || principal.trim().length() == 0) {
            throw new ServletException("Principal not defined in configuration");
        }
        keytab = config.getProperty(KEYTAB, keytab);
        if (keytab == null || keytab.trim().length() == 0) {
            throw new ServletException("Keytab not defined in configuration");
        }
        if (!new File(keytab).exists()) {
            throw new ServletException("Keytab does not exist: " + keytab);
        }

        // use all SPNEGO principals in the keytab if a principal isn't
        // specifically configured
        final String[] spnegoPrincipals;
        if ("*".equals(principal)) {
            spnegoPrincipals = KerberosUtil.getPrincipalNames(keytab, Pattern.compile("HTTP/.*"));
            if (spnegoPrincipals.length == 0) {
                throw new ServletException("Principals do not exist in the keytab");
            }
        } else {
            spnegoPrincipals = new String[] { principal };
        }

        String nameRules = config.getProperty(NAME_RULES, null);
        if (nameRules != null) {
            KerberosName.setRules(nameRules);
        }

        for (String spnegoPrincipal : spnegoPrincipals) {
            log.info("Login using keytab %s, for principal %s", keytab, spnegoPrincipal);
            final KerberosAuthenticator.DruidKerberosConfiguration kerberosConfiguration = new KerberosAuthenticator.DruidKerberosConfiguration(
                    keytab, spnegoPrincipal);
            final LoginContext loginContext = new LoginContext("", serverSubject, null, kerberosConfiguration);
            try {
                loginContext.login();
            } catch (LoginException le) {
                log.warn(le, "Failed to login as [%s]", spnegoPrincipal);
                throw new AuthenticationException(le);
            }
            loginContexts.add(loginContext);
        }
        try {
            gssManager = Subject.doAs(serverSubject, new PrivilegedExceptionAction<GSSManager>() {

                @Override
                public GSSManager run() {
                    return GSSManager.getInstance();
                }
            });
        } catch (PrivilegedActionException ex) {
            throw ex.getException();
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}

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

public boolean getHBaseStatus() {
    boolean hbaseStatus = false;
    subj = getLoginSubject();//w  w  w  . j  a v  a  2  s  . c  o m
    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.";
    if (subj != null) {
        ClassLoader prevCl = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(getConfigHolder().getClassLoader());

            hbaseStatus = Subject.doAs(subj, new PrivilegedAction<Boolean>() {
                @Override
                public Boolean run() {
                    Boolean hbaseStatus1 = false;
                    try {
                        LOG.info("getHBaseStatus: creating default Hbase configuration");
                        Configuration conf = HBaseConfiguration.create();
                        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);
                        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);
                        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);
                        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);
                        throw hdpException;

                    } catch (Throwable e) {
                        String msgDesc = "getHBaseStatus: Unable to check availability of"
                                + " Hbase environment [" + getConfigHolder().getDatasourceName() + "].";
                        LOG.error(msgDesc);
                        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, "
                    + "current thread might not be able set the context ClassLoader.";
            HadoopException hdpException = new HadoopException(msgDesc, se);
            hdpException.generateResponseDataMap(false, getMessage(se), msgDesc + errMsg, null, null);
            throw hdpException;
        } finally {
            Thread.currentThread().setContextClassLoader(prevCl);
        }
    } else {
        LOG.error("getHBaseStatus: secure login not done, subject is null");
    }

    return hbaseStatus;
}

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();//w  ww. j  a v a  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("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.ranger.hive.client.HiveClient.java

public List<String> getTableList(String database, String tableNameMatching) {
    final String db = database;
    final String tblNameMatching = tableNameMatching;
    List<String> tableList = Subject.doAs(getLoginSubject(), new PrivilegedAction<List<String>>() {
        public List<String> run() {
            return getTblList(db, tblNameMatching);
        }// w w w  . j a  va 2 s  .  c  o m
    });
    return tableList;
}

From source file:org.jboss.test.kerberos.gss.GSSTestServer.java

/**
 * Authenticates this server in Kerberos KDC.
 * /* w  w w.j a va2  s.c o m*/
 * @throws LoginException
 * @throws PrivilegedActionException
 */
private void start() throws LoginException, PrivilegedActionException {
    System.out.println("Starting GSSTestServer - login");
    // Use our custom configuration to avoid reliance on external config
    Configuration.setConfiguration(new Configuration() {
        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            final Map<String, Object> options = new HashMap<String, Object>();
            options.put("refreshKrb5Config", "true");
            options.put("storeKey", "true");
            return new AppConfigurationEntry[] {
                    new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
                            AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options) };
        }
    });
    // 1. Authenticate to Kerberos.
    final LoginContext lc = new LoginContext("foo",
            new UsernamePasswordHandler(PRINCIPAL, PASSWORD != null ? PASSWORD.toCharArray() : null));
    lc.login();
    System.out.println("Authentication succeed");
    // 2. Perform the work as authenticated Subject.
    final String finishMsg = Subject.doAs(lc.getSubject(), new ServerAction());
    System.out.println("Server stopped with result: " + (finishMsg == null ? "OK" : finishMsg));
    lc.logout();

}