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.wso2.carbon.mediator.kerberos.KerberosMediator.java

/**
 * Create GSSCredential for the user./*from   w ww. j av a  2 s  .c  om*/
 *
 * @param callbackHandler callback handler.
 * @param mechanismOId    Oid for the mechanism.
 * @return GSSCredential.
 * @throws LoginException
 * @throws PrivilegedActionException
 * @throws GSSException
 */
private GSSCredential createClientCredentials(CallbackHandler callbackHandler, final Oid mechanismOId)
        throws LoginException, PrivilegedActionException, GSSException {

    LoginContext loginContext;
    String loginName;
    if (StringUtils.isNotEmpty(getLoginContextName())) {
        loginName = getLoginContextName();
    } else {
        loginName = "com.sun.security.auth.module.Krb5LoginModule";
    }
    if (callbackHandler != null) {
        loginContext = new LoginContext(loginName, callbackHandler);
    } else {
        loginContext = new LoginContext(loginName);
    }
    loginContext.login();
    if (log.isDebugEnabled()) {
        log.debug("Pre-authentication successful for with Kerberos Server.");
    }

    // Create client credentials from pre authentication with the AD
    final GSSName clientName = gssManager.createName(clientPrincipalValue, GSSName.NT_USER_NAME);
    final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() {
        public GSSCredential run() throws GSSException {

            return gssManager.createCredential(clientName.canonicalize(mechanismOId),
                    GSSCredential.DEFAULT_LIFETIME, mechanismOId, GSSCredential.INITIATE_ONLY);
        }
    };

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

From source file:com.openkm.jcr.JCRUtils.java

/**
 * Get JCR Session//w  w w. ja va  2  s  .c om
 */
public static Session getSession()
        throws javax.jcr.LoginException, javax.jcr.RepositoryException, DatabaseException {
    Object obj = null;

    try {
        InitialContext ctx = new InitialContext();
        Subject subject = (Subject) ctx.lookup("java:comp/env/security/subject");
        obj = Subject.doAs(subject, new PrivilegedAction<Object>() {
            public Object run() {
                Session s = null;

                try {
                    s = DirectRepositoryModule.getRepository().login();
                } catch (javax.jcr.LoginException e) {
                    return e;
                } catch (javax.jcr.RepositoryException e) {
                    return e;
                }

                return s;
            }
        });
    } catch (NamingException e) {
        throw new javax.jcr.LoginException(e.getMessage());
    }

    if (obj instanceof javax.jcr.LoginException) {
        throw (javax.jcr.LoginException) obj;
    } else if (obj instanceof javax.jcr.RepositoryException) {
        throw (javax.jcr.LoginException) obj;
    } else if (obj instanceof javax.jcr.Session) {
        Session session = (javax.jcr.Session) obj;
        log.debug("#{} - {} Create session {} from {}", new Object[] { ++sessionCreationCount, ++activeSessions,
                session, StackTraceUtils.whoCalledMe() });
        DirectAuthModule.loadUserData(session);
        return session;
    } else {
        return null;
    }
}

From source file:org.wildfly.test.integration.elytron.sasl.mgmt.AbstractKerberosMgmtSaslTestBase.java

protected void assertKerberosSaslMechFails(String mech, String user, String password, boolean withSsl)
        throws MalformedURLException, LoginException, Exception {
    // 1. Authenticate to Kerberos.
    final LoginContext lc = KerberosTestUtils.loginWithKerberos(KRB5_CONFIGURATION, user, password);
    try {/*  ww  w. ja  v a 2 s  .c o m*/
        AuthenticationConfiguration authCfg = AuthenticationConfiguration.empty()
                .setSaslMechanismSelector(SaslMechanismSelector.fromString(mech))
                .useGSSCredential(getGSSCredential(lc.getSubject()));

        AuthenticationContext authnCtx = AuthenticationContext.empty().with(MatchRule.ALL, authCfg);
        if (withSsl) {
            authnCtx = authnCtx.withSsl(MatchRule.ALL, sslFactory);
        }
        final AuthenticationContext authnCtxFinal = authnCtx;
        Subject.doAs(lc.getSubject(), (PrivilegedAction<Void>) () -> {
            authnCtxFinal.run(() -> assertAuthenticationFails(null, null, withSsl));
            return null;
        });
    } finally {
        lc.logout();
    }
}

From source file:org.jboss.as.test.integration.security.picketlink.SAML2KerberosAuthenticationTestCase.java

/**
 * Returns response body for the given URL request as a String. It also checks if the returned HTTP status code is the
 * expected one. If the server returns {@link HttpServletResponse#SC_UNAUTHORIZED} and an username is provided, then the
 * given user is authenticated against Kerberos and a new request is executed under the new subject.
 *
 * @param uri  URI to which the request should be made
 * @param user Username//from  w  w w . j  ava 2s .c  o  m
 * @param pass Password
 * @return HTTP response body
 * @throws IOException
 * @throws URISyntaxException
 * @throws PrivilegedActionException
 * @throws LoginException
 */
public static String makeCallWithKerberosAuthn(URI uri, URI idpUri, final String user, final String pass)
        throws IOException, URISyntaxException, PrivilegedActionException, LoginException {

    final String canonicalHost = Utils.getDefaultHost(true);
    uri = Utils.replaceHost(uri, canonicalHost);
    idpUri = Utils.replaceHost(idpUri, canonicalHost);

    LOGGER.trace("Making call to: " + uri);
    LOGGER.trace("Expected IDP: " + idpUri);

    final Krb5LoginConfiguration krb5configuration = new Krb5LoginConfiguration(Utils.getLoginConfiguration());
    // Use our custom configuration to avoid reliance on external config
    Configuration.setConfiguration(krb5configuration);

    // 1. Authenticate to Kerberos.
    final LoginContext lc = Utils.loginWithKerberos(krb5configuration, user, pass);

    // 2. Perform the work as authenticated Subject.
    final String responseBody = Subject.doAs(lc.getSubject(), new HttpGetInKerberos(uri, idpUri));
    lc.logout();
    krb5configuration.resetConfiguration();
    return responseBody;
}

From source file:org.apache.ranger.biz.KmsKeyMgr.java

public void deleteKey(String provider, String name) throws Exception {
    String providers[] = null;// ww w.ja  v  a  2  s . c  o  m
    try {
        providers = getKMSURL(provider);
    } catch (Exception e) {
        logger.error("deleteKey(" + provider + ", " + name + ") failed", e);
    }
    boolean isKerberos = false;
    try {
        isKerberos = checkKerberos();
    } catch (Exception e1) {
        logger.error("checkKerberos(" + provider + ") failed", e1);
    }
    if (providers != null) {
        for (int i = 0; i < providers.length; i++) {
            Client c = getClient();
            String deleteRest = KMS_DELETE_KEY_URI.replaceAll(Pattern.quote("${alias}"), name);
            String currentUserLoginId = ContextUtil.getCurrentUserLoginId();
            String uri = providers[i] + (providers[i].endsWith("/") ? deleteRest : ("/" + deleteRest));
            if (!isKerberos) {
                uri = uri.concat("?user.name=" + currentUserLoginId);
            } else {
                uri = uri.concat("?doAs=" + currentUserLoginId);
            }
            final WebResource r = c.resource(uri);
            try {
                String response = null;
                if (!isKerberos) {
                    response = r.delete(String.class);
                } else {
                    Subject sub = getSubjectForKerberos(provider);
                    response = Subject.doAs(sub, new PrivilegedAction<String>() {
                        @Override
                        public String run() {
                            return r.delete(String.class);
                        }
                    });
                }
                logger.debug("delete RESPONSE: [" + response + "]");
                break;
            } catch (Exception e) {
                if (e instanceof UniformInterfaceException || i == providers.length - 1)
                    throw e;
                else
                    continue;
            }
        }
    }
}

From source file:org.wildfly.test.integration.elytron.sasl.mgmt.AbstractKerberosMgmtSaslTestBase.java

/**
 * Retrieves {@link GSSCredential} from given Subject
 *//*ww  w .ja  v a 2 s  .  co  m*/
protected GSSCredential getGSSCredential(Subject subject) {
    return Subject.doAs(subject, new PrivilegedAction<GSSCredential>() {
        @Override
        public GSSCredential run() {
            try {
                GSSManager gssManager = GSSManager.getInstance();
                return gssManager.createCredential(GSSCredential.INITIATE_ONLY);
            } catch (Exception e) {
                LOGGER.warn("Unable to retrieve GSSCredential from given Subject.", e);
            }
            return null;
        }
    });
}

From source file:org.apache.sentry.service.thrift.SentryServiceIntegrationBase.java

protected void runTestAsSubject(final TestOperation test) throws Exception {
    if (kerberos) {
        Subject.doAs(clientSubject, new PrivilegedExceptionAction<Void>() {
            @Override//from w  w w  .j a v  a  2s  . c o  m
            public Void run() throws Exception {
                test.runTestAsSubject();
                return null;
            }
        });
    } else {
        test.runTestAsSubject();
    }
}

From source file:it.staiger.jmeter.protocol.http.sampler.HTTPHC4DynamicFilePost.java

/**
 * Execute request either as is or under PrivilegedAction 
 * if a Subject is available for url//from   w  w w.  j  a v a  2  s  . c  o m
 * @param httpClient
 * @param httpRequest
 * @param localContext
 * @param url
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 */
private HttpResponse executeRequest(final HttpClient httpClient, final HttpRequestBase httpRequest,
        final HttpContext localContext, final URL url) throws IOException, ClientProtocolException {
    AuthManager authManager = getAuthManager();
    if (authManager != null) {
        Subject subject = authManager.getSubjectForUrl(url);
        if (subject != null) {
            try {
                return Subject.doAs(subject, new PrivilegedExceptionAction<HttpResponse>() {

                    @Override
                    public HttpResponse run() throws Exception {
                        return httpClient.execute(httpRequest, localContext);
                    }
                });
            } catch (PrivilegedActionException e) {
                log.error("Can't execute httpRequest with subject:" + subject, e);
                throw new RuntimeException("Can't execute httpRequest with subject:" + subject, e);
            }
        }
    }
    return httpClient.execute(httpRequest, localContext);
}

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

public List<String> getColumnFamilyList(final String tableName, final String columnFamilyMatching) {
    List<String> ret = null;
    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.";

    subj = getLoginSubject();/*from   w  w  w  .  ja  va 2  s  . com*/
    if (subj != null) {
        ClassLoader prevCl = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(getConfigHolder().getClassLoader());

            ret = Subject.doAs(subj, new PrivilegedAction<List<String>>() {

                @Override
                public List<String> run() {

                    List<String> colfList = new ArrayList<String>();
                    HBaseAdmin admin = null;
                    try {
                        Configuration conf = HBaseConfiguration.create();
                        admin = new HBaseAdmin(conf);
                        HTableDescriptor htd = admin.getTableDescriptor(tableName.getBytes());
                        if (htd != null) {
                            for (HColumnDescriptor hcd : htd.getColumnFamilies()) {
                                String colf = hcd.getNameAsString();
                                if (colf.matches(columnFamilyMatching)) {
                                    if (!colfList.contains(colf)) {
                                        colfList.add(colf);
                                    }
                                }
                            }
                        }
                    } catch (ZooKeeperConnectionException zce) {
                        String msgDesc = "getColumnFamilyList: 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 = "getColumnFamilyList: 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 (IOException io) {
                        String msgDesc = "getColumnFamilyList: Unable to get HBase ColumnFamilyList for "
                                + "[repository:" + getConfigHolder().getDatasourceName() + ",table:" + tableName
                                + ", table-match:" + columnFamilyMatching + "], "
                                + "current thread might not be able set the context ClassLoader.";
                        HadoopException hdpException = new HadoopException(msgDesc, io);
                        hdpException.generateResponseDataMap(false, getMessage(io), msgDesc + errMsg, null,
                                null);
                        throw hdpException;
                    } catch (SecurityException se) {
                        String msgDesc = "getColumnFamilyList: Unable to get HBase ColumnFamilyList for "
                                + "[repository:" + getConfigHolder().getDatasourceName() + ",table:" + tableName
                                + ", table-match:" + columnFamilyMatching + "], "
                                + "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;

                    } catch (Throwable e) {
                        String msgDesc = "getColumnFamilyList: Unable to get HBase ColumnFamilyList for "
                                + "[repository:" + getConfigHolder().getDatasourceName() + ",table:" + tableName
                                + ", table-match:" + columnFamilyMatching + "], "
                                + "current thread might not be able set the context ClassLoader.";
                        LOG.error(msgDesc);
                        HadoopException hdpException = new HadoopException(msgDesc, e);
                        hdpException.generateResponseDataMap(false, getMessage(e), msgDesc + errMsg, null,
                                null);
                        throw hdpException;
                    } finally {
                        if (admin != null) {
                            try {
                                admin.close();
                            } catch (IOException e) {
                                LOG.error("Unable to close HBase connection ["
                                        + getConfigHolder().getDatasourceName() + "]", e);
                            }
                        }
                    }
                    return colfList;
                }

            });
        } catch (SecurityException se) {
            String msgDesc = "getColumnFamilyList: 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);
        }
    }
    return ret;
}

From source file:com.stimulus.archiva.security.realm.ADRealm.java

public ArrayList<AttributeValue> getADAttributes(Config config, ADIdentity identity, String username,
        String password) throws ArchivaException {
    logger.debug("getADAttributes()");
    validateLoginName(username);//from w ww  . j av  a 2s . c o m
    validatePassword(password);
    LoginContext serverLC = kereberosLogin(config, identity, identity.getServiceDN(),
            identity.getServicePassword());
    Hashtable<String, String> env = new Hashtable<String, String>(11);
    String ldapAddress = identity.getLDAPAddress();
    if (!ldapAddress.toLowerCase(Locale.ENGLISH).startsWith("ldap://"))
        ldapAddress = "ldap://" + ldapAddress;
    logger.debug("finding DN of user from LDAP using Kereberos token {ldapAddress='" + ldapAddress
            + "', username='" + username + "'}");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapAddress);
    env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");
    int at = username.indexOf('@');
    String uname = username;
    if (uname.indexOf("@") != -1) {
        uname = username.substring(0, at).toLowerCase(Locale.ENGLISH);
    }
    logger.debug("findUserDN {loginname='" + uname + "'}");
    String bindDN = null;
    try {
        bindDN = (String) Subject.doAs(serverLC.getSubject(), new FindDNAction(identity, uname, env));
    } catch (Exception e) {
        throw new ArchivaException("failed to bind to ldap server {uname='" + username + "''}", e, logger);
    }
    try {
        serverLC.logout();
    } catch (Exception e) {
        throw new ArchivaException("failed to logout from kerberos server:" + e.getMessage() + " {uname='"
                + username + "',kdcAddress='" + identity.getKDCAddress() + "'}", e, logger);
    }
    ArrayList<AttributeValue> attributes = new ArrayList<AttributeValue>();
    serverLC = kereberosLogin(config, identity, username, password);
    if (bindDN != null) {
        env.clear();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ldapAddress);
        env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");

        try {
            attributes = (ArrayList<AttributeValue>) Subject.doAs(serverLC.getSubject(),
                    new GetAttributesAction(identity, username, env, bindDN));
        } catch (Exception e) {
            throw new ArchivaException("failed to bind to ldap server:" + e.getMessage() + " {uname='"
                    + username + "',ldapAddress='" + identity.getLDAPAddress() + "'}", e, logger);
        }
    }
    try {
        serverLC.logout();
    } catch (Exception e) {
        throw new ArchivaException("failed to logout from kerberos server:" + e.getMessage() + " {uname='"
                + username + "',kdcAddress='" + identity.getKDCAddress() + "'}", e, logger);
    }
    logger.debug("getADAttributes() return");
    return attributes;

}