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.cloudera.alfredo.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 authencation token being used for the user.
 * @throws IOException if an IO error occurred.
 * @throws AuthenticationException if an authentication error occurred.
 *///from w  w  w  . java2  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) {
            subject = new Subject();
            LoginContext login = new LoginContext("", subject);
            login.login();
        }
        Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                GSSContext gssContext = null;
                try {
                    GSSManager gssManager = GSSManager.getInstance();
                    String servicePrincipal = "HTTP/" + KerberosAuthenticator.this.url.getHost();
                    GSSName serviceName = gssManager.createName(servicePrincipal,
                            GSSUtil.NT_GSS_KRB5_PRINCIPAL);
                    gssContext = gssManager.createContext(serviceName, GSSUtil.GSS_KRB5_MECH_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();
                    }
                }
                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.ranger.services.sqoop.client.SqoopClient.java

public List<String> getJobList(final String jobMatching, final List<String> existingJobs) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Get sqoop job list for jobMatching: " + jobMatching + ", existingJobs: " + existingJobs);
    }/*from   w  ww. j a  v a 2s  .co m*/
    Subject subj = getLoginSubject();
    if (subj == null) {
        return Collections.emptyList();
    }

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

        @Override
        public List<String> run() {

            ClientResponse response = getClientResponse(sqoopUrl, SQOOP_JOB_API_ENDPOINT, userName);

            SqoopJobsResponse sqoopJobsResponse = getSqoopResourceResponse(response, SqoopJobsResponse.class);
            if (sqoopJobsResponse == null || CollectionUtils.isEmpty(sqoopJobsResponse.getJobs())) {
                return Collections.emptyList();
            }
            List<String> jobResponses = new ArrayList<>();
            for (SqoopJobResponse sqoopJobResponse : sqoopJobsResponse.getJobs()) {
                jobResponses.add(sqoopJobResponse.getName());
            }

            List<String> jobs = null;
            if (CollectionUtils.isNotEmpty(jobResponses)) {
                jobs = filterResourceFromResponse(jobMatching, existingJobs, jobResponses);
            }
            return jobs;
        }
    });

    if (LOG.isDebugEnabled()) {
        LOG.debug("Get sqoop job list result: " + ret);
    }
    return ret;
}

From source file:graphql.servlet.GraphQLServlet.java

private void query(String query, String operationName, Map<String, Object> variables, GraphQLSchema schema,
        HttpServletRequest req, HttpServletResponse resp, GraphQLContext context) throws IOException {
    if (Subject.getSubject(AccessController.getContext()) == null && context.getSubject().isPresent()) {
        Subject.doAs(context.getSubject().get(), new PrivilegedAction<Void>() {
            @Override/*  w  ww.  ja  v  a2 s  .  c  o  m*/
            @SneakyThrows
            public Void run() {
                query(query, operationName, variables, schema, req, resp, context);
                return null;
            }
        });
    } else {
        Map<String, Object> vars = transformVariables(schema, query, variables);
        operationListeners.forEach(l -> l.beforeGraphQLOperation(context, operationName, query, vars));

        ExecutionResult result = new GraphQL(schema, getExecutionStrategy()).execute(query, operationName,
                context, vars);
        resp.setContentType("application/json;charset=utf-8");
        if (result.getErrors().isEmpty()) {
            Map<String, Object> dict = new HashMap<>();
            dict.put("data", result.getData());
            resp.getWriter().write(new ObjectMapper().writeValueAsString(dict));
            operationListeners.forEach(
                    l -> l.onSuccessfulGraphQLOperation(context, operationName, query, vars, result.getData()));
        } else {
            resp.setStatus(500);
            List<GraphQLError> errors = getGraphQLErrors(result);
            Map<String, Object> dict = new HashMap<>();
            dict.put("errors", errors);

            resp.getWriter().write(new ObjectMapper().writeValueAsString(dict));
            operationListeners.forEach(
                    l -> l.onFailedGraphQLOperation(context, operationName, query, vars, result.getErrors()));
        }
    }
}

From source file:org.apache.qpid.server.management.plugin.servlet.rest.AbstractServlet.java

private void doWithSubjectAndActor(PrivilegedExceptionAction<Void> privilegedExceptionAction,
        final HttpServletRequest request, final HttpServletResponse resp) {
    Subject subject;// ww w.  j a  v a  2  s.com
    try {
        subject = getAndCacheAuthorizedSubject(request);
    } catch (AccessControlException e) {
        sendError(resp, HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    SecurityManager.setThreadSubject(subject);
    try {
        HttpManagementActor logActor = getLogActorAndCacheInSession(request);
        CurrentActor.set(logActor);
        try {
            Subject.doAs(subject, privilegedExceptionAction);
        } catch (RuntimeException e) {
            LOGGER.error("Unable to perform action", e);
            throw e;
        } catch (PrivilegedActionException e) {
            LOGGER.error("Unable to perform action", e);
            throw new RuntimeException(e.getCause());
        } finally {
            CurrentActor.remove();
        }
    } finally {
        try {
            SecurityManager.setThreadSubject(null);
        } finally {
            AMQShortString.clearLocalCache();
        }
    }
}

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

/**
 * Initializes the authentication handler instance.
 * <p/>// w w  w.j a  va  2  s  . co m
 * It creates a Kerberos context using the principal and keytab specified in the configuration.
 * <p/>
 * This method is invoked by the {@link AuthenticationFilter#init} method.
 *
 * @param config configuration properties to initialize the handler.
 *
 * @throws ServletException thrown if the handler could not be initialized.
 */
@Override
public void init(Properties config) throws ServletException {
    try {
        principal = config.getProperty(PRINCIPAL, 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);
        }

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

        Set<Principal> principals = new HashSet<Principal>();
        principals.add(new KerberosPrincipal(principal));
        Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());

        KerberosConfiguration kerberosConfiguration = new KerberosConfiguration(keytab, principal);

        LOG.info("Login using keytab " + keytab + ", for principal " + principal);
        loginContext = new LoginContext("", subject, null, kerberosConfiguration);
        loginContext.login();

        Subject serverSubject = loginContext.getSubject();
        try {
            gssManager = Subject.doAs(serverSubject, new PrivilegedExceptionAction<GSSManager>() {

                @Override
                public GSSManager run() throws Exception {
                    return GSSManager.getInstance();
                }
            });
        } catch (PrivilegedActionException ex) {
            throw ex.getException();
        }
        LOG.info("Initialized, principal [{}] from keytab [{}]", principal, keytab);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}

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

public List<String> getColumnList(String database, String tableName, String columnNameMatching) {
    final String db = database;
    final String tblName = tableName;
    final String clmNameMatching = columnNameMatching;
    List<String> columnList = Subject.doAs(getLoginSubject(), new PrivilegedAction<List<String>>() {
        public List<String> run() {
            return getClmList(db, tblName, clmNameMatching);
        }/*w w  w  .j a  va2 s . com*/
    });
    return columnList;
}

From source file:org.apache.hadoop.hbase.http.TestSpnegoHttpServer.java

@Test
public void testAllowedClient() throws Exception {
    // Create the subject for the client
    final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(CLIENT_PRINCIPAL, clientKeytab);
    final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
    // Make sure the subject has a principal
    assertFalse(clientPrincipals.isEmpty());

    // Get a TGT for the subject (might have many, different encryption types). The first should
    // be the default encryption type.
    Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class);
    assertFalse(privateCredentials.isEmpty());
    KerberosTicket tgt = privateCredentials.iterator().next();
    assertNotNull(tgt);// w w  w. j  a va2 s.  co m

    // The name of the principal
    final String principalName = clientPrincipals.iterator().next().getName();

    // Run this code, logged in as the subject (the client)
    HttpResponse resp = Subject.doAs(clientSubject, new PrivilegedExceptionAction<HttpResponse>() {
        @Override
        public HttpResponse run() throws Exception {
            // Logs in with Kerberos via GSS
            GSSManager gssManager = GSSManager.getInstance();
            // jGSS Kerberos login constant
            Oid oid = new Oid("1.2.840.113554.1.2.2");
            GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME);
            GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME,
                    oid, GSSCredential.INITIATE_ONLY);

            HttpClientContext context = HttpClientContext.create();
            Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                    .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build();

            HttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry).build();
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));

            URL url = new URL(getServerURL(server), "/echo?a=b");
            context.setTargetHost(new HttpHost(url.getHost(), url.getPort()));
            context.setCredentialsProvider(credentialsProvider);
            context.setAuthSchemeRegistry(authRegistry);

            HttpGet get = new HttpGet(url.toURI());
            return client.execute(get, context);
        }
    });

    assertNotNull(resp);
    assertEquals(HttpURLConnection.HTTP_OK, resp.getStatusLine().getStatusCode());
    assertEquals("a:b", EntityUtils.toString(resp.getEntity()).trim());
}

From source file:com.telefonica.iot.cygnus.backends.http.HttpBackend.java

private JsonResponse doPrivilegedRequest(String method, String url, ArrayList<Header> headers,
        StringEntity entity) throws CygnusRuntimeError {
    try {/*from  w w  w.  j av  a  2s .  c  om*/
        LoginContext loginContext = new LoginContext("cygnus_krb5_login",
                new KerberosCallbackHandler(krb5User, krb5Password));
        loginContext.login();
        PrivilegedRequest req = new PrivilegedRequest(method, url, headers, entity);
        return createJsonResponse((HttpResponse) Subject.doAs(loginContext.getSubject(), req));
    } catch (LoginException e) {
        throw new CygnusRuntimeError("Privileged request error", "LoginException", e.getMessage());
    } // try catch
}

From source file:org.apache.storm.security.auth.kerberos.KerberosSaslTransportPlugin.java

@Override
public TTransport connect(TTransport transport, String serverHost, String asUser)
        throws TTransportException, IOException {
    //create an authentication callback handler
    ClientCallbackHandler client_callback_handler = new ClientCallbackHandler(login_conf);

    //login our user
    LoginCacheKey key = new LoginCacheKey(login_conf, AuthUtils.LOGIN_CONTEXT_CLIENT);
    Login login = loginCache.get(key);//from w w w.ja v a  2 s . c  o m
    if (login == null) {
        LOG.debug("Kerberos Login was not found in the Login Cache, attempting to contact the Kerberos Server");
        synchronized (loginCache) {
            login = loginCache.get(key);
            if (login == null) {
                try {
                    //specify a configuration object to be used
                    Configuration.setConfiguration(login_conf);
                    //now login
                    login = new Login(AuthUtils.LOGIN_CONTEXT_CLIENT, client_callback_handler);
                    login.startThreadIfNeeded();
                    loginCache.put(key, login);
                } catch (LoginException ex) {
                    LOG.error("Server failed to login in principal:" + ex, ex);
                    throw new RuntimeException(ex);
                }
            }
        }
    }

    final Subject subject = login.getSubject();
    if (subject.getPrivateCredentials(KerberosTicket.class).isEmpty()) { //error
        throw new RuntimeException("Fail to verify user principal with section \""
                + AuthUtils.LOGIN_CONTEXT_CLIENT + "\" in login configuration file " + login_conf);
    }

    final String principal = StringUtils.isBlank(asUser) ? getPrincipal(subject) : asUser;
    String serviceName = AuthUtils.get(login_conf, AuthUtils.LOGIN_CONTEXT_CLIENT, "serviceName");
    if (serviceName == null) {
        serviceName = AuthUtils.SERVICE;
    }
    Map<String, String> props = new TreeMap<String, String>();
    props.put(Sasl.QOP, "auth");
    props.put(Sasl.SERVER_AUTH, "false");

    LOG.debug("SASL GSSAPI client transport is being established");
    final TTransport sasalTransport = new TSaslClientTransport(KERBEROS, principal, serviceName, serverHost,
            props, null, transport);

    //open Sasl transport with the login credential
    try {
        Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {
            public Void run() {
                try {
                    LOG.debug("do as:" + principal);
                    sasalTransport.open();
                } catch (Exception e) {
                    LOG.error(
                            "Client failed to open SaslClientTransport to interact with a server during session initiation: "
                                    + e,
                            e);
                }
                return null;
            }
        });
    } catch (PrivilegedActionException e) {
        throw new RuntimeException(e);
    }

    return sasalTransport;
}

From source file:org.apache.ranger.services.kms.client.KMSClient.java

public List<String> getKeyList(final String keyNameMatching, final List<String> existingKeyList) {

    String providers[] = null;/*from www . jav  a 2 s  . co  m*/
    try {
        providers = createProvider(provider);
    } catch (IOException | URISyntaxException e) {
        return null;
    }
    final String errMsg = errMessage;
    List<String> lret = null;
    for (int i = 0; i < providers.length; i++) {
        lret = new ArrayList<String>();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Getting Kms Key list for keyNameMatching : " + keyNameMatching);
        }
        String uri = providers[i]
                + (providers[i].endsWith("/") ? KMS_LIST_API_ENDPOINT : ("/" + KMS_LIST_API_ENDPOINT));
        Client client = null;
        ClientResponse response = null;
        boolean isKerberos = false;
        try {
            ClientConfig cc = new DefaultClientConfig();
            cc.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
            client = Client.create(cc);

            if (authType != null && authType.equalsIgnoreCase(AUTH_TYPE_KERBEROS)) {
                isKerberos = true;
            }

            Subject sub = new Subject();
            if (!isKerberos) {
                uri = uri.concat("?user.name=" + username);
                WebResource webResource = client.resource(uri);
                response = webResource.accept(EXPECTED_MIME_TYPE).get(ClientResponse.class);
                LOG.info("Init Login: security not enabled, using username");
                sub = SecureClientLogin.login(username);
            } else {
                if (!StringUtils.isEmpty(rangerPrincipal) && !StringUtils.isEmpty(rangerKeytab)) {
                    LOG.info("Init Lookup Login: security enabled, using rangerPrincipal/rangerKeytab");
                    if (StringUtils.isEmpty(nameRules)) {
                        nameRules = "DEFAULT";
                    }
                    String shortName = new HadoopKerberosName(rangerPrincipal).getShortName();
                    uri = uri.concat("?doAs=" + shortName);
                    sub = SecureClientLogin.loginUserFromKeytab(rangerPrincipal, rangerKeytab, nameRules);
                } else {
                    LOG.info("Init Login: using username/password");
                    String shortName = new HadoopKerberosName(username).getShortName();
                    uri = uri.concat("?doAs=" + shortName);
                    String decryptedPwd = PasswordUtils.decryptPassword(password);
                    sub = SecureClientLogin.loginUserWithPassword(username, decryptedPwd);
                }
            }
            final WebResource webResource = client.resource(uri);
            response = Subject.doAs(sub, new PrivilegedAction<ClientResponse>() {
                @Override
                public ClientResponse run() {
                    return webResource.accept(EXPECTED_MIME_TYPE).get(ClientResponse.class);
                }
            });

            if (LOG.isDebugEnabled()) {
                LOG.debug("getKeyList():calling " + uri);
            }
            if (response != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("getKeyList():response.getStatus()= " + response.getStatus());
                }
                if (response.getStatus() == 200) {
                    String jsonString = response.getEntity(String.class);
                    Gson gson = new GsonBuilder().setPrettyPrinting().create();
                    @SuppressWarnings("unchecked")
                    List<String> keys = gson.fromJson(jsonString, List.class);
                    if (keys != null) {
                        for (String key : keys) {
                            if (existingKeyList != null && existingKeyList.contains(key)) {
                                continue;
                            }
                            if (keyNameMatching == null || keyNameMatching.isEmpty()
                                    || key.startsWith(keyNameMatching)) {
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("getKeyList():Adding kmsKey " + key);
                                }
                                lret.add(key);
                            }
                        }
                        return lret;
                    }
                } else if (response.getStatus() == 401) {
                    LOG.info("getKeyList():response.getStatus()= " + response.getStatus() + " for URL " + uri
                            + ", so returning null list");
                    String msgDesc = response.getEntity(String.class);
                    HadoopException hdpException = new HadoopException(msgDesc);
                    hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg, null, null);
                    lret = null;
                    throw hdpException;
                } else if (response.getStatus() == 403) {
                    LOG.info("getKeyList():response.getStatus()= " + response.getStatus() + " for URL " + uri
                            + ", so returning null list");
                    String msgDesc = response.getEntity(String.class);
                    HadoopException hdpException = new HadoopException(msgDesc);
                    hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg, null, null);
                    lret = null;
                    throw hdpException;
                } else {
                    LOG.info("getKeyList():response.getStatus()= " + response.getStatus() + " for URL " + uri
                            + ", so returning null list");
                    String jsonString = response.getEntity(String.class);
                    LOG.info(jsonString);
                    lret = null;
                }
            } else {
                String msgDesc = "Unable to get a valid response for " + "expected mime type : ["
                        + EXPECTED_MIME_TYPE + "] URL : " + uri + " - got null response.";
                LOG.error(msgDesc);
                HadoopException hdpException = new HadoopException(msgDesc);
                hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg, null, null);
                lret = null;
                throw hdpException;
            }
        } catch (HadoopException he) {
            lret = null;
            throw he;
        } catch (Throwable t) {
            String msgDesc = "Exception while getting Kms Key List. URL : " + uri;
            HadoopException hdpException = new HadoopException(msgDesc, t);
            LOG.error(msgDesc, t);
            hdpException.generateResponseDataMap(false, BaseClient.getMessage(t), msgDesc + errMsg, null, null);
            lret = null;
            throw hdpException;
        } finally {
            if (response != null) {
                response.close();
            }

            if (client != null) {
                client.destroy();
            }

            if (lret == null) {
                if (i != providers.length - 1)
                    continue;
            }
        }
    }
    return lret;
}