Example usage for javax.security.auth Subject getSubject

List of usage examples for javax.security.auth Subject getSubject

Introduction

In this page you can find the example usage for javax.security.auth Subject getSubject.

Prototype

public static Subject getSubject(final AccessControlContext acc) 

Source Link

Document

Get the Subject associated with the provided AccessControlContext .

Usage

From source file:ca.nrc.cadc.uws.server.JobDAO.java

/**
 * Iterate over the jobs owned by the user in the subject contained in the
 * access control context./*from   ww w .ja va2 s  .  com*/
 *
 * @param phases Show only these phases
 * @param after Only show jobs after this time
 * @param last Show the last <i>last</i> jobs, ordererd by startTime ascending
 * @return job iterator
 * @throws JobPersistenceException
 * @throws TransientException
 */
public Iterator<JobRef> iterator(String appname, List<ExecutionPhase> phases, Date after, Integer last)
        throws TransientException, JobPersistenceException {
    AccessControlContext acContext = AccessController.getContext();
    Subject subject = Subject.getSubject(acContext);
    return iterator(subject, appname, phases, after, last);
}

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  ava  2 s .com

            // 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.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  v  a 2  s  .  co  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   ww w  .ja va2 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.
 *//* w ww.  j ava2s .co m*/
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 w  w .  jav  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.  //from w  w w  .  j  a v a  2 s  .  c o 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//www.  jav a 2s. co 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}//from   ww w. ja  v  a2 s  . c  om
 */
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();
    }
}

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

/**
 * Tries to add Principals to a given subject:
 * First Access the Subject from the current AccessControlContext,
 * If Subject is found the LoginContext is evoked for it, in order
 * to possibly allow for extension of preauthenticated Subject.<br>
 * In contrast to a login with Credentials, a Session is created, even if the
 * Authentication failed.<br>//from   ww  w . j a va  2 s  .c  om
 * If the {@link Subject} is marked to be unmodificable or if the
 * authentication of the the Subject failed Session is build for unchanged
 * Subject.
 *
 * @param workspaceName must not be null
 * @return if a Subject is exsting null else
 * @throws RepositoryException
 * @throws AccessDeniedException
 */
private Session extendAuthentication(String workspaceName) throws RepositoryException, AccessDeniedException {

    Subject subject = null;
    try {
        AccessControlContext acc = AccessController.getContext();
        subject = Subject.getSubject(acc);
    } catch (SecurityException e) {
        log.warn("Can't check for preauthentication. Reason:", e.getMessage());
    }
    if (subject == null) {
        log.debug("No preauthenticated subject found -> return null.");
        return null;
    }

    Session s;
    if (subject.isReadOnly()) {
        log.debug("Preauthenticated Subject is read-only -> create Session");
        s = createSession(subject, workspaceName);
    } else {
        log.debug("Found preauthenticated Subject, try to extend authentication");
        // login either using JAAS or custom LoginModule
        AuthContext authCtx = getSecurityManager().getAuthContext(null, subject);
        try {
            authCtx.login();
            s = createSession(authCtx, workspaceName);
        } catch (javax.security.auth.login.LoginException e) {
            // subject could not be extended
            log.debug("Preauthentication could not be extended");
            s = createSession(subject, workspaceName);
        }
    }
    return s;
}