Example usage for java.security PrivilegedActionException getException

List of usage examples for java.security PrivilegedActionException getException

Introduction

In this page you can find the example usage for java.security PrivilegedActionException getException.

Prototype

public Exception getException() 

Source Link

Document

Returns the exception thrown by the privileged computation that resulted in this PrivilegedActionException .

Usage

From source file:com.lucidworks.security.authentication.client.KerberosAuthenticator.java

/**
 * Implements the SPNEGO authentication sequence interaction using the current default principal
 * in the Kerberos cache (normally set via kinit).
 *
 * @param token the authentication token being used for the user.
 *
 * @throws IOException if an IO error occurred.
 * @throws AuthenticationException if an authentication error occurred.
 *//*from w  w w.  j av  a 2  s  . c om*/
private void doSpnegoSequence(AuthenticatedURL.Token token) throws IOException, AuthenticationException {
    try {
        AccessControlContext context = AccessController.getContext();
        Subject subject = Subject.getSubject(context);
        if (subject == null) {
            LOG.debug("No subject in context, logging in");
            subject = new Subject();
            LoginContext login = new LoginContext("", subject, null, new KerberosConfiguration());
            login.login();
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Using subject: " + subject);
        }
        Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                GSSContext gssContext = null;
                try {
                    GSSManager gssManager = GSSManager.getInstance();
                    String servicePrincipal = KerberosUtil.getServicePrincipal("HTTP",
                            KerberosAuthenticator.this.url.getHost());
                    Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                    GSSName serviceName = gssManager.createName(servicePrincipal, oid);
                    oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                    gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME);
                    gssContext.requestCredDeleg(true);
                    gssContext.requestMutualAuth(true);

                    byte[] inToken = new byte[0];
                    byte[] outToken;
                    boolean established = false;

                    // Loop while the context is still not established
                    while (!established) {
                        outToken = gssContext.initSecContext(inToken, 0, inToken.length);
                        if (outToken != null) {
                            sendToken(outToken);
                        }

                        if (!gssContext.isEstablished()) {
                            inToken = readToken();
                        } else {
                            established = true;
                        }
                    }
                } finally {
                    if (gssContext != null) {
                        gssContext.dispose();
                        gssContext = null;
                    }
                }
                return null;
            }
        });
    } catch (PrivilegedActionException ex) {
        throw new AuthenticationException(ex.getException());
    } catch (LoginException ex) {
        throw new AuthenticationException(ex);
    }
    AuthenticatedURL.extractToken(conn, token);
}

From source file:org.nebulaframework.deployment.classloading.GridArchiveClassLoader.java

/**
 * Creates a temporary file which consists of the {@code byte[]} of a given
 * {@code GridArchive}.// w  ww  .j  a v  a  2 s. co  m
 * 
 * @param archive
 *            {@code GridArchive}
 * @return A {@code File} reference for new temporary file
 * 
 * @throws IOException
 *             if IOException occurs during {@code File} handling
 */
protected File createTempArchiveFile(final GridArchive archive) throws Exception {

    try {
        // Run with Privileges
        return AccessController.doPrivileged(new PrivilegedExceptionAction<File>() {

            @Override
            public File run() throws IOException {
                // Create Temp File
                File archiveFile = File.createTempFile("archivetemp", "nar");
                archiveFile.deleteOnExit(); // Mark to delete

                // Write the byte[]
                FileOutputStream fout = new FileOutputStream(archiveFile);
                fout.write(archive.getBytes());
                fout.flush();
                fout.close();

                return archiveFile;
            }

        });
    } catch (PrivilegedActionException e) {
        throw e.getException();
    }
}

From source file:org.apache.river.container.classloading.VirtualFileSystemClassLoader.java

@Override
protected Class<?> findClass(final String name) throws ClassNotFoundException {
    try {/*www . j  a v  a 2 s  .  c  o  m*/
        return (Class) Security.doPrivileged(new PrivilegedExceptionAction<Class>() {

            public Class run() throws ClassNotFoundException {
                String resourceName = classToResourceName(name);
                FileObject resourceFileObject = findResourceFileObject(resourceName);
                if (resourceFileObject == null) {
                    throw new ClassNotFoundException(name + "(" + resourceName + ")");
                }
                try {
                    byte[] bytes = FileUtil.getContent(resourceFileObject);
                    return defineClass(name, bytes, 0, bytes.length);
                } catch (IOException ioe) {
                    throw new ClassNotFoundException(name, ioe);
                }

            }
        });
    } catch (PrivilegedActionException ex) {
        throw (ClassNotFoundException) ex.getException();
    }
}

From source file:com.lucidworks.security.authentication.server.KerberosAuthenticationHandler.java

/**
 * It enforces the the Kerberos SPNEGO authentication sequence returning an {@link AuthenticationToken} only
 * after the Kerberos SPNEGO sequence has completed successfully.
 * <p/>/*from   ww w  .  java2  s . c  o  m*/
 *
 * @param request the HTTP client request.
 * @param response the HTTP client response.
 *
 * @return an authentication token if the Kerberos SPNEGO sequence is complete and valid,
 *         <code>null</code> if it is in progress (in this case the handler handles the response to the client).
 *
 * @throws IOException thrown if an IO error occurred.
 * @throws AuthenticationException thrown if Kerberos SPNEGO sequence failed.
 */
@Override
public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response)
        throws IOException, AuthenticationException {
    AuthenticationToken token = null;
    String authorization = request.getHeader(KerberosAuthenticator.AUTHORIZATION);

    if (authorization == null || !authorization.startsWith(KerberosAuthenticator.NEGOTIATE)) {
        response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        if (authorization == null) {
            LOG.trace("SPNEGO starting");
        } else {
            LOG.warn("'" + KerberosAuthenticator.AUTHORIZATION + "' does not start with '"
                    + KerberosAuthenticator.NEGOTIATE + "' :  {}", authorization);
        }
    } else {
        authorization = authorization.substring(KerberosAuthenticator.NEGOTIATE.length()).trim();
        final Base64 base64 = new Base64(0);
        final byte[] clientToken = base64.decode(authorization);
        Subject serverSubject = loginContext.getSubject();
        try {
            token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() {

                @Override
                public AuthenticationToken run() throws Exception {
                    AuthenticationToken token = null;
                    GSSContext gssContext = null;
                    GSSCredential gssCreds = null;
                    try {
                        if (PlatformName.IBM_JAVA) {
                            // IBM JDK needs non-null credentials to be passed to createContext here, with
                            // SPNEGO mechanism specified, otherwise JGSS will use its default mechanism
                            // only, which is Kerberos V5.
                            gssCreds = gssManager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME,
                                    new Oid[] { KerberosUtil.getOidInstance("GSS_SPNEGO_MECH_OID"),
                                            KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID") },
                                    GSSCredential.ACCEPT_ONLY);
                        }
                        gssContext = gssManager.createContext(gssCreds);
                        byte[] serverToken = gssContext.acceptSecContext(clientToken, 0, clientToken.length);
                        if (serverToken != null && serverToken.length > 0) {
                            String authenticate = base64.encodeToString(serverToken);
                            response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE,
                                    KerberosAuthenticator.NEGOTIATE + " " + authenticate);
                        }
                        if (!gssContext.isEstablished()) {
                            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                            LOG.trace("SPNEGO in progress");
                        } else {
                            String clientPrincipal = gssContext.getSrcName().toString();
                            KerberosName kerberosName = new KerberosName(clientPrincipal);
                            String userName = kerberosName.getShortName();
                            token = new AuthenticationToken(userName, clientPrincipal, getType());
                            response.setStatus(HttpServletResponse.SC_OK);
                            LOG.trace("SPNEGO completed for principal [{}]", clientPrincipal);
                        }
                    } finally {
                        if (gssContext != null) {
                            gssContext.dispose();
                        }
                        if (gssCreds != null) {
                            gssCreds.dispose();
                        }
                    }
                    return token;
                }
            });
        } catch (PrivilegedActionException ex) {
            if (ex.getException() instanceof IOException) {
                throw (IOException) ex.getException();
            } else {
                throw new AuthenticationException(ex.getException());
            }
        }
    }
    return token;
}

From source file:org.wso2.carbon.user.core.common.DefaultRealmService.java

@Override
public UserRealm getUserRealm(final RealmConfiguration tenantRealmConfig) throws UserStoreException {

    try {/*from  w  w  w. j  a  v  a2s .c o  m*/
        return AccessController.doPrivileged(new PrivilegedExceptionAction<UserRealm>() {
            @Override
            public UserRealm run() throws Exception {
                return getUserRealmInternal(tenantRealmConfig);
            }
        });
    } catch (PrivilegedActionException e) {
        throw (UserStoreException) e.getException();
    }
}

From source file:org.springframework.beans.factory.support.DisposableBeanAdapter.java

/**
 * Invoke the specified custom destroy method on the given bean.
 * <p>This implementation invokes a no-arg method if found, else checking
 * for a method with a single boolean argument (passing in "true",
 * assuming a "force" parameter), else logging an error.
 *//*from  www.j  a v  a 2  s  .co  m*/
private void invokeCustomDestroyMethod(final Method destroyMethod) {
    Class<?>[] paramTypes = destroyMethod.getParameterTypes();
    final Object[] args = new Object[paramTypes.length];
    if (paramTypes.length == 1) {
        args[0] = Boolean.TRUE;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Invoking destroy method '" + this.destroyMethodName + "' on bean with name '"
                + this.beanName + "'");
    }
    try {
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                ReflectionUtils.makeAccessible(destroyMethod);
                return null;
            });
            try {
                AccessController.doPrivileged(
                        (PrivilegedExceptionAction<Object>) () -> destroyMethod.invoke(bean, args), acc);
            } catch (PrivilegedActionException pax) {
                throw (InvocationTargetException) pax.getException();
            }
        } else {
            ReflectionUtils.makeAccessible(destroyMethod);
            destroyMethod.invoke(bean, args);
        }
    } catch (InvocationTargetException ex) {
        String msg = "Invocation of destroy method '" + this.destroyMethodName + "' failed on bean with name '"
                + this.beanName + "'";
        if (logger.isDebugEnabled()) {
            logger.warn(msg, ex.getTargetException());
        } else {
            logger.warn(msg + ": " + ex.getTargetException());
        }
    } catch (Throwable ex) {
        logger.error("Couldn't invoke destroy method '" + this.destroyMethodName + "' on bean with name '"
                + this.beanName + "'", ex);
    }
}

From source file:com.flipkart.fdp.migration.distcp.security.KerberosAuthenticator2.java

/**
 * Implements the SPNEGO authentication sequence interaction using the
 * current default principal in the Kerberos cache (normally set via kinit).
 * /*  w  w  w.  j a  v  a2s  . c o  m*/
 * @param token
 *            the authentication token being used for the user.
 * 
 * @throws IOException
 *             if an IO error occurred.
 * @throws AuthenticationException
 *             if an authentication error occurred.
 */
private void doSpnegoSequence(AuthenticatedURL.Token token) throws IOException, AuthenticationException {
    try {

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

        LoginContext loginContext = new LoginContext("", null,
                new KerberosClientCallbackHandler(username, password), new LoginConfig(this.debug));
        loginContext.login();
        // if (LOG.isDebugEnabled()) {
        // LOG.debug("Kerberos authenticated user: "
        // + loginContext.getSubject());
        // }
        Subject subject = loginContext.getSubject();

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

            public Void run() throws Exception {
                GSSContext gssContext = null;
                try {
                    GSSManager gssManager = GSSManager.getInstance();
                    Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                    String sp = KerberosAuthenticator2.this.servicePrincipal;
                    if (sp == null) {
                        sp = "HTTP/" + KerberosAuthenticator2.this.url.getHost();
                    }
                    GSSName serviceName = gssManager.createName(sp, oid);
                    oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                    gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME);
                    gssContext.requestCredDeleg(true);
                    gssContext.requestMutualAuth(true);

                    byte[] inToken = new byte[0];
                    byte[] outToken;
                    boolean established = false;

                    // Loop while the context is still not established
                    while (!established) {
                        outToken = gssContext.initSecContext(inToken, 0, inToken.length);
                        if (outToken != null) {
                            sendToken(outToken);
                        }

                        if (!gssContext.isEstablished()) {
                            inToken = readToken();
                        } else {
                            established = true;
                        }
                    }
                } finally {
                    if (gssContext != null) {
                        gssContext.dispose();
                        gssContext = null;
                    }
                }
                return null;
            }
        });
    } catch (PrivilegedActionException ex) {
        throw new AuthenticationException(ex.getException());
    } catch (LoginException ex) {
        throw new AuthenticationException(ex);
    }
    AuthenticatedURL.extractToken(conn, token);
}

From source file:main.client.http.KerberosAuthenticator2.java

/**
 * Implements the SPNEGO authentication sequence interaction using the
 * current default principal in the Kerberos cache (normally set via kinit).
 * // w  w  w . j a va  2s.  co m
 * @param token
 *            the authentication token being used for the user.
 * 
 * @throws IOException
 *             if an IO error occurred.
 * @throws AuthenticationException
 *             if an authentication error occurred.
 */
private void doSpnegoSequence(AuthenticatedURL.Token token) throws IOException, AuthenticationException {
    try {

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

        LoginContext loginContext = new LoginContext("", null,
                new KerberosClientCallbackHandler(username, password), new LoginConfig(this.debug));
        loginContext.login();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Kerberos authenticated user: " + loginContext.getSubject());
        }
        Subject subject = loginContext.getSubject();

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

            @Override
            public Void run() throws Exception {
                GSSContext gssContext = null;
                try {
                    GSSManager gssManager = GSSManager.getInstance();
                    String servicePrincipal = "HTTP/" + KerberosAuthenticator2.this.url.getHost();
                    Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                    GSSName serviceName = gssManager.createName(servicePrincipal, oid);
                    oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                    gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME);
                    gssContext.requestCredDeleg(true);
                    gssContext.requestMutualAuth(true);

                    byte[] inToken = new byte[0];
                    byte[] outToken;
                    boolean established = false;

                    // Loop while the context is still not established
                    while (!established) {
                        outToken = gssContext.initSecContext(inToken, 0, inToken.length);
                        if (outToken != null) {
                            sendToken(outToken);
                        }

                        if (!gssContext.isEstablished()) {
                            inToken = readToken();
                        } else {
                            established = true;
                        }
                    }
                } finally {
                    if (gssContext != null) {
                        gssContext.dispose();
                        gssContext = null;
                    }
                }
                return null;
            }
        });
    } catch (PrivilegedActionException ex) {
        throw new AuthenticationException(ex.getException());
    } catch (LoginException ex) {
        throw new AuthenticationException(ex);
    }
    AuthenticatedURL.extractToken(conn, token);
}

From source file:org.apache.openjpa.kernel.ResultPacker.java

/**
 * Pack the given result into the user-defined result class.
 *///  w w  w. ja  v a 2 s .  c om
private Object packUserType(Object[] result) {
    try {
        // use the constructor first, if we have one
        if (_constructor != null)
            return _constructor.newInstance(result);

        Object user = AccessController.doPrivileged(J2DoPrivHelper.newInstanceAction(_resultClass));
        for (int i = 0; i < _aliases.length; i++) {
            if (_sets[i] instanceof Method) {
                Method meth = (Method) _sets[i];
                meth.invoke(user, new Object[] { Filters.convert(result[i], meth.getParameterTypes()[0]) });
            } else if (_sets[i] instanceof Field) {
                Field field = (Field) _sets[i];
                field.set(user, Filters.convert(result[i], field.getType()));
            } else if (_put != null) {
                _put.invoke(user, new Object[] { _aliases[i], result[i] });
            }
        }
        return user;
    } catch (OpenJPAException ke) {
        throw ke;
    } catch (PrivilegedActionException pae) {
        throw new UserException(_loc.get("pack-instantiation-err", _resultClass), pae.getException());
    } catch (InstantiationException ie) {
        throw new UserException(_loc.get("pack-instantiation-err", _resultClass), ie);
    } catch (Exception e) {
        throw new UserException(_loc.get("pack-err", _resultClass), e);
    }
}

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();//ww w.  java2 s.co 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();
    }
}