Example usage for java.security AccessController getContext

List of usage examples for java.security AccessController getContext

Introduction

In this page you can find the example usage for java.security AccessController getContext.

Prototype


public static AccessControlContext getContext() 

Source Link

Document

This method takes a "snapshot" of the current calling context, which includes the current Thread's inherited AccessControlContext and any limited privilege scope, and places it in an AccessControlContext object.

Usage

From source file:com.streamsets.pipeline.stage.destination.hdfs.HdfsTargetConfigBean.java

private boolean validateHadoopFS(Stage.Context context, List<Stage.ConfigIssue> issues) {
    hdfsConfiguration = getHadoopConfiguration(context, issues);

    boolean validHapoopFsUri = true;
    // if hdfsUri is empty, we'll use the default fs uri from hdfs config. no validation required.
    if (!hdfsUri.isEmpty()) {
        if (hdfsUri.contains("://")) {
            try {
                new URI(hdfsUri);
            } catch (Exception ex) {
                issues.add(context.createConfigIssue(Groups.HADOOP_FS.name(), null, Errors.HADOOPFS_22, hdfsUri,
                        ex.toString(), ex));
                validHapoopFsUri = false;
            }/*  w  w w  .  j  av  a  2s  . co m*/

            // Configured URI have precedence
            hdfsConfiguration.set(CommonConfigurationKeys.FS_DEFAULT_NAME_KEY, hdfsUri);
        } else {
            issues.add(context.createConfigIssue(Groups.HADOOP_FS.name(),
                    HDFS_TARGET_CONFIG_BEAN_PREFIX + "hdfsUri", Errors.HADOOPFS_18, hdfsUri));
            validHapoopFsUri = false;
        }
    } else {
        // HDFS URI is not set, we're expecting that it will be available in config files
        hdfsUri = hdfsConfiguration.get(CommonConfigurationKeys.FS_DEFAULT_NAME_KEY);
    }

    // We must have value of default.FS otherwise it's clear miss configuration
    if (hdfsUri == null || hdfsUri.isEmpty()) {
        issues.add(context.createConfigIssue(Groups.HADOOP_FS.name(), null, Errors.HADOOPFS_49));
        validHapoopFsUri = false;
    }

    StringBuilder logMessage = new StringBuilder();
    try {
        // forcing UGI to initialize with the security settings from the stage
        UserGroupInformation.setConfiguration(hdfsConfiguration);
        Subject subject = Subject.getSubject(AccessController.getContext());
        if (UserGroupInformation.isSecurityEnabled()) {
            loginUgi = UserGroupInformation.getUGIFromSubject(subject);
        } else {
            UserGroupInformation.loginUserFromSubject(subject);
            loginUgi = UserGroupInformation.getLoginUser();
        }
        LOG.info("Subject = {}, Principals = {}, Login UGI = {}", subject,
                subject == null ? "null" : subject.getPrincipals(), loginUgi);
        if (hdfsKerberos) {
            logMessage.append("Using Kerberos");
            if (loginUgi.getAuthenticationMethod() != UserGroupInformation.AuthenticationMethod.KERBEROS) {
                issues.add(context.createConfigIssue(Groups.HADOOP_FS.name(),
                        HDFS_TARGET_CONFIG_BEAN_PREFIX + "hdfsKerberos", Errors.HADOOPFS_00,
                        loginUgi.getAuthenticationMethod(),
                        UserGroupInformation.AuthenticationMethod.KERBEROS));
            }
        } else {
            logMessage.append("Using Simple");
            hdfsConfiguration.set(CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION,
                    UserGroupInformation.AuthenticationMethod.SIMPLE.name());
        }
        if (validHapoopFsUri) {
            getUGI().doAs(new PrivilegedExceptionAction<Void>() {
                @Override
                public Void run() throws Exception {
                    try (FileSystem fs = getFileSystemForInitDestroy()) { //to trigger the close
                    }
                    return null;
                }
            });
        }
    } catch (Exception ex) {
        LOG.info("Validation Error: " + Errors.HADOOPFS_01.getMessage(), hdfsUri, ex.toString(), ex);
        issues.add(context.createConfigIssue(Groups.HADOOP_FS.name(), null, Errors.HADOOPFS_01, hdfsUri,
                String.valueOf(ex), ex));

        // We weren't able connect to the cluster and hence setting the validity to false
        validHapoopFsUri = false;
    }
    LOG.info("Authentication Config: " + logMessage);
    return validHapoopFsUri;
}

From source file:org.apache.clerezza.platform.dashboard.UserLoginNode.java

@Override
public GraphNode addUserContext(GraphNode node) {

    final AccessControlContext context = AccessController.getContext();
    GraphNode agent = AccessController.doPrivileged(new PrivilegedAction<GraphNode>() {
        @Override/* ww  w.  j av  a  2s .co m*/
        public GraphNode run() {
            final String userName = UserUtil.getUserName(context);
            if (userName == null) {
                return null;
            }
            return userManager.getUserGraphNode(userName);
        }
    });
    if (agent != null) {
        if (agent.getNode() instanceof UriRef) {
            WebIdInfo webIdInfo = webIdGraphsService.getWebIdInfo((UriRef) agent.getNode());
            MGraph userGraph = webIdInfo.localPublicUserData();
            agent = new GraphNode(agent.getNode(), new UnionMGraph(agent.getGraph(), userGraph));
        }
        node.addProperty(PLATFORM.user, agent.getNode());
        MGraph userContext = new SimpleMGraph(agent.getNodeContext());
        removeTripleWithProperty(userContext, PERMISSION.password);
        removeTripleWithProperty(userContext, PERMISSION.passwordSha1);
        node.getGraph().addAll(userContext);
    }
    return node;
}

From source file:org.apache.geode.internal.security.IntegratedSecurityService.java

/**
 * It first looks the shiro subject in AccessControlContext since JMX will use multiple threads to
 * process operations from the same client, then it looks into Shiro's thead context.
 *
 * @return the shiro subject, null if security is not enabled
 *///from  w  w  w.j a v  a 2  s. com
public Subject getSubject() {
    if (!isIntegratedSecurity()) {
        return null;
    }

    Subject currentUser = null;

    // First try get the principal out of AccessControlContext instead of Shiro's Thread context
    // since threads can be shared between JMX clients.
    javax.security.auth.Subject jmxSubject = javax.security.auth.Subject
            .getSubject(AccessController.getContext());

    if (jmxSubject != null) {
        Set<ShiroPrincipal> principals = jmxSubject.getPrincipals(ShiroPrincipal.class);
        if (principals.size() > 0) {
            ShiroPrincipal principal = principals.iterator().next();
            currentUser = principal.getSubject();
            ThreadContext.bind(currentUser);
            return currentUser;
        }
    }

    // in other cases like rest call, client operations, we get it from the current thread
    currentUser = SecurityUtils.getSubject();

    if (currentUser == null || currentUser.getPrincipal() == null) {
        throw new GemFireSecurityException("Error: Anonymous User");
    }

    return currentUser;
}

From source file:org.apache.hadoop.gateway.identityasserter.common.filter.CommonIdentityAssertionFilter.java

/**
 * Obtain the standard javax.security.auth.Subject, retrieve the caller principal, map
 * to the identity to be asserted as appropriate and create the provider specific
 * assertion token. Add the assertion token to the request.
 *//*w  w  w .j  a  va  2s.  c o m*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    Subject subject = Subject.getSubject(AccessController.getContext());

    String principalName = getPrincipalName(subject);

    String mappedPrincipalName = mapUserPrincipalBase(principalName);
    mappedPrincipalName = mapUserPrincipal(mappedPrincipalName);
    String[] mappedGroups = mapGroupPrincipals(mappedPrincipalName, subject);
    String[] groups = mapGroupPrincipals(mappedPrincipalName, subject);
    groups = combineGroupMappings(mappedGroups, groups);

    HttpServletRequestWrapper wrapper = wrapHttpServletRequest(request, mappedPrincipalName);

    continueChainAsPrincipal(wrapper, response, chain, mappedPrincipalName, groups);
}

From source file:org.apache.hadoop.io.crypto.tool.kerberos.SpnegoRestCli.java

public StringBuffer getResult() throws Exception {
    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();//from   www.j a  v  a 2  s  . c o  m
    }
    Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            sb = new RestClient(url).getResult();
            return null;
        }
    });
    return sb;
}

From source file:org.apache.hadoop.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 2s.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, null, new KerberosConfiguration());
            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();
                    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.hadoop.security.SecurityUtil.java

/**
 * Find the original TGT within the current subject's credentials. Cross-realm
 * TGT's of the form "krbtgt/TWO.COM@ONE.COM" may be present.
 * //from   w  ww  . j av  a2 s .c o m
 * @return The TGT from the current subject
 * @throws IOException
 *           if TGT can't be found
 */
private static KerberosTicket getTgtFromSubject() throws IOException {
    Subject current = Subject.getSubject(AccessController.getContext());
    if (current == null) {
        throw new IOException("Can't get TGT from current Subject, because it is null");
    }
    Set<KerberosTicket> tickets = current.getPrivateCredentials(KerberosTicket.class);
    for (KerberosTicket t : tickets) {
        if (isOriginalTGT(t.getServer().getName()))
            return t;
    }
    throw new IOException("Failed to find TGT from current Subject:" + current);
}

From source file:org.apache.hadoop.security.SecurityUtil.java

/**
 * Explicitly pull the service ticket for the specified host.  This solves a
 * problem with Java's Kerberos SSL problem where the client cannot 
 * authenticate against a cross-realm service.  It is necessary for clients
 * making kerberized https requests to call this method on the target URL
 * to ensure that in a cross-realm environment the remote host will be 
 * successfully authenticated.  // w w  w. j a  v a 2s .co m
 * 
 * This method is internal to Hadoop and should not be used by other 
 * applications.  This method should not be considered stable or open: 
 * it will be removed when the Java behavior is changed.
 * 
 * @param remoteHost Target URL the krb-https client will access
 * @throws IOException if a service ticket is not available
 */
public static void fetchServiceTicket(URL remoteHost) throws IOException {
    if (!UserGroupInformation.isSecurityEnabled())
        return;

    String serviceName = "host/" + remoteHost.getHost();
    if (LOG.isDebugEnabled())
        LOG.debug("Fetching service ticket for host at: " + serviceName);
    Object serviceCred = null;
    Method credsToTicketMeth;
    Class<?> krb5utilClass;
    try {
        Class<?> principalClass;
        Class<?> credentialsClass;

        if (System.getProperty("java.vendor").contains("IBM")) {
            principalClass = Class.forName("com.ibm.security.krb5.PrincipalName");

            credentialsClass = Class.forName("com.ibm.security.krb5.Credentials");
            krb5utilClass = Class.forName("com.ibm.security.jgss.mech.krb5");
        } else {
            principalClass = Class.forName("sun.security.krb5.PrincipalName");
            credentialsClass = Class.forName("sun.security.krb5.Credentials");
            krb5utilClass = Class.forName("sun.security.jgss.krb5.Krb5Util");
        }
        @SuppressWarnings("rawtypes")
        Constructor principalConstructor = principalClass.getConstructor(String.class, int.class);
        Field KRB_NT_SRV_HST = principalClass.getDeclaredField("KRB_NT_SRV_HST");
        Method acquireServiceCredsMeth = credentialsClass.getDeclaredMethod("acquireServiceCreds", String.class,
                credentialsClass);
        Method ticketToCredsMeth = krb5utilClass.getDeclaredMethod("ticketToCreds", KerberosTicket.class);
        credsToTicketMeth = krb5utilClass.getDeclaredMethod("credsToTicket", credentialsClass);

        Object principal = principalConstructor.newInstance(serviceName, KRB_NT_SRV_HST.get(principalClass));

        serviceCred = acquireServiceCredsMeth.invoke(credentialsClass, principal.toString(),
                ticketToCredsMeth.invoke(krb5utilClass, getTgtFromSubject()));
    } catch (Exception e) {
        throw new IOException("Can't get service ticket for: " + serviceName, e);
    }
    if (serviceCred == null) {
        throw new IOException("Can't get service ticket for " + serviceName);
    }
    try {
        Subject.getSubject(AccessController.getContext()).getPrivateCredentials()
                .add(credsToTicketMeth.invoke(krb5utilClass, serviceCred));
    } catch (Exception e) {
        throw new IOException("Can't get service ticket for: " + serviceName, e);
    }
}

From source file:org.apache.hadoop.security.UserGroupInformation.java

/**
 * Return the current user, including any doAs in the current stack.
 * @return the current user/*from w ww.j  a  v  a 2s  .c o  m*/
 * @throws IOException if login fails
 */
public synchronized static UserGroupInformation getCurrentUser() throws IOException {
    AccessControlContext context = AccessController.getContext();
    Subject subject = Subject.getSubject(context);
    return subject == null ? getLoginUser() : new UserGroupInformation(subject);
}

From source file:org.apache.jackrabbit.core.RepositoryImpl.java

/**
 * {@inheritDoc}//w  w w . j  a v a  2  s  . c o m
 */
public Session login(Credentials credentials, String workspaceName)
        throws LoginException, NoSuchWorkspaceException, RepositoryException {
    try {
        shutdownLock.readLock().acquire();
    } catch (InterruptedException e) {
        throw new RepositoryException("Login lock could not be acquired", e);
    }

    try {
        // check sanity of this instance
        sanityCheck();

        if (workspaceName == null) {
            workspaceName = repConfig.getDefaultWorkspaceName();
        }

        // check if workspace exists (will throw NoSuchWorkspaceException if not)
        getWorkspaceInfo(workspaceName);

        if (credentials == null) {
            // null credentials, obtain the identity of the already-authenticated
            // subject from access control context
            AccessControlContext acc = AccessController.getContext();
            Subject subject = Subject.getSubject(acc);
            if (subject != null) {
                return createSession(subject, workspaceName);
            }
        }
        // login either using JAAS or our own LoginModule
        AuthContext authCtx;
        LoginModuleConfig lmc = repConfig.getLoginModuleConfig();
        if (lmc == null) {
            authCtx = new AuthContext.JAAS(repConfig.getAppName(), credentials);
        } else {
            authCtx = new AuthContext.Local(lmc.getLoginModule(), lmc.getParameters(), credentials);
        }
        authCtx.login();

        // create session
        return createSession(authCtx, workspaceName);
    } catch (SecurityException se) {
        throw new LoginException("Unable to access authentication information", se);
    } catch (javax.security.auth.login.LoginException le) {
        throw new LoginException(le.getMessage(), le);
    } catch (AccessDeniedException ade) {
        // authenticated subject is not authorized for the specified workspace
        throw new LoginException("Workspace access denied", ade);
    } finally {
        shutdownLock.readLock().release();
    }
}