Example usage for javax.security.auth Subject getPrivateCredentials

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

Introduction

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

Prototype

public <T> Set<T> getPrivateCredentials(Class<T> c) 

Source Link

Document

Return a Set of private credentials associated with this Subject that are instances or subclasses of the specified Class .

Usage

From source file:uk.ac.ox.webauth.WebauthGetTokensRequest.java

/**
 * Simple test method that tries to post the request to the WebKDC and parse
 * the response message./*w w w .  j a  v a  2s  .c om*/
 * @param   args    First principal and then the keytab to load a key from,
 *          then the service to generate the KRB_AP_REQ message for,
 *          then the url to post the request to.
 * @throws  Exception   when something goes wrong.
 */
public static void main(String[] args) throws Exception {
    // get some keys to decrypt with
    long start = System.currentTimeMillis();
    KeytabKeyLoader kkl = new KeytabKeyLoader(args[0], args[1], false);
    Subject sub = kkl.acquire();
    long stop = System.currentTimeMillis();
    System.out.println("Grabbing private key took " + (stop - start) + " milliseconds.");

    // grab the service ticket
    start = System.currentTimeMillis();
    try {
        Subject.doAs(sub, new ServiceTicketGrabberHack(args[0], args[2]));
    } catch (Exception e) {
        e.printStackTrace();
    }
    KerberosTicket ticket = null;
    for (KerberosTicket t : sub.getPrivateCredentials(KerberosTicket.class)) {
        if (t.getServer().getName().startsWith(args[2])) {
            ticket = t;
        }
    }
    stop = System.currentTimeMillis();
    System.out.println("Getting the service ticket took " + (stop - start) + " milliseconds.");

    // request a webkdc token
    start = System.currentTimeMillis();
    byte[] krb_ap_req = new KrbApReq(ticket).toASN1Object().getEncoded();
    WebauthGetTokensRequest wgtr = new WebauthGetTokensRequest(args[3], krb_ap_req);
    wgtr.tokenRequest();
    stop = System.currentTimeMillis();
    System.out.println("Getting the WebKDC token took " + (stop - start) + " milliseconds.");
    System.out.println("Token data: " + wgtr.tokenData());
    System.out.println("Session key: " + wgtr.sessionKey());
    System.out.println("Expires: " + wgtr.expires());
    System.out.println("Success.");
}

From source file:org.apache.storm.security.auth.ClientAuthUtils.java

/**
 * Find a worker token in a given subject with a given token type.
 *
 * @param subject what to look in.//from   w  ww  .  j a  va2  s.  c  o  m
 * @param type    the type of token to look for.
 * @return the token or null.
 */
public static WorkerToken findWorkerToken(Subject subject, final WorkerTokenServiceType type) {
    Set<WorkerToken> creds = subject.getPrivateCredentials(WorkerToken.class);
    synchronized (creds) {
        return creds.stream().filter((wt) -> wt.get_serviceType() == type).findAny().orElse(null);
    }
}

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 . j  a  va2 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.kudu.mapreduce.KuduTableMapReduceUtil.java

/**
 * Import credentials from the current thread's JAAS {@link Subject} into the provided
 * {@link KuduClient}./*from  w  w w . j  a v a2  s .c  o  m*/
 *
 * This must be called for any clients created within a MapReduce job in order to
 * adopt the credentials added by {@link #addCredentialsToJob(KuduClient, Job)}.
 * When using {@link KuduTableInputFormat} or {@link KuduTableOutputFormat}, the
 * implementation automatically handles creating the client and importing necessary
 * credentials. As such, this is only necessary in jobs that explicitly create a
 * {@link KuduClient}.
 *
 * If no appropriate credentials are found, does nothing.
 */
public static void importCredentialsFromCurrentSubject(KuduClient client) {
    Subject subj = Subject.getSubject(AccessController.getContext());
    if (subj == null) {
        return;
    }
    Text service = new Text(client.getMasterAddressesAsString());
    // Find the Hadoop credentials stored within the JAAS subject.
    Set<Credentials> credSet = subj.getPrivateCredentials(Credentials.class);
    if (credSet == null) {
        return;
    }
    for (Credentials creds : credSet) {
        for (Token<?> tok : creds.getAllTokens()) {
            if (!tok.getKind().equals(KUDU_TOKEN_KIND)) {
                continue;
            }
            // Only import credentials relevant to the service corresponding to
            // 'client'. This is necessary if we want to support a job which
            // reads from one cluster and writes to another.
            if (!tok.getService().equals(service)) {
                LOG.debug("Not importing credentials for service " + service + "(expecting service " + service
                        + ")");
                continue;
            }
            LOG.debug("Importing credentials for service " + service);
            client.importAuthenticationCredentials(tok.getPassword());
            return;
        }
    }
}

From source file:org.apache.storm.common.AbstractHadoopAutoCreds.java

private void addTokensToUGI(Subject subject) {
    if (subject != null) {
        Set<Credentials> privateCredentials = subject.getPrivateCredentials(Credentials.class);
        if (privateCredentials != null) {
            for (Credentials cred : privateCredentials) {
                Collection<Token<? extends TokenIdentifier>> allTokens = cred.getAllTokens();
                if (allTokens != null) {
                    for (Token<? extends TokenIdentifier> token : allTokens) {
                        try {
                            LOG.debug("Current user: {}", UserGroupInformation.getCurrentUser());
                            LOG.debug("Token from credential: {} / {}", token.toString(),
                                    token.decodeIdentifier().getUser());

                            UserGroupInformation.getCurrentUser().addToken(token);
                            LOG.info("Added delegation tokens to UGI.");
                        } catch (IOException e) {
                            LOG.error("Exception while trying to add tokens to ugi", e);
                        }//from   www  .  ja v  a2s  .  com
                    }
                }
            }
        }
    }
}

From source file:backtype.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
    Login login = null;//from   ww  w. ja  v a 2  s.c o m
    try {
        // specify a configuration object to be used
        Configuration.setConfiguration(login_conf);
        // now login
        login = new Login(AuthUtils.LOGIN_CONTEXT_CLIENT, client_callback_handler);
    } 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.ws.security.message.token.KerberosSecurity.java

/**
 * Get a KerberosTicket from the clientSubject parameter, that is not equal to the supplied KerberosTicket
 * parameter (can be null)/*from www  . j a  v a  2 s .  c o  m*/
 */
private KerberosTicket getKerberosTicket(Subject clientSubject, KerberosTicket previousTicket) {
    Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class);
    if (privateCredentials == null || privateCredentials.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("Kerberos client subject private credentials are null");
        }
        return null;
    }

    for (KerberosTicket privateCredential : privateCredentials) {
        if (!privateCredential.equals(previousTicket)) {
            return privateCredential;
        }
    }
    return null;
}

From source file:org.apache.storm.common.AbstractAutoCreds.java

private void addTokensToUGI(Subject subject) {
    if (subject != null) {
        Set<Credentials> privateCredentials = subject.getPrivateCredentials(Credentials.class);
        if (privateCredentials != null) {
            for (Credentials cred : privateCredentials) {
                Collection<Token<? extends TokenIdentifier>> allTokens = cred.getAllTokens();
                if (allTokens != null) {
                    for (Token<? extends TokenIdentifier> token : allTokens) {
                        try {
                            UserGroupInformation.getCurrentUser().addToken(token);
                            LOG.info("Added delegation tokens to UGI.");
                        } catch (IOException e) {
                            LOG.error("Exception while trying to add tokens to ugi", e);
                        }/*from   w  w w.  j a  v  a2  s  .c  o m*/
                    }
                }
            }
        }
    }
}

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 . j  a  va 2 s . co 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.globus.gsi.gssapi.GlobusGSSManagerImpl.java

/** Acquires GSI GSS credentials. First, it tries to find the credentials
 * in the private credential set of the current JAAS Subject. If the
 * Subject is not set or credentials are not found in the Subject, it
 * tries to get a default user credential (usually an user proxy file)
 *
 * @param lifetime Only lifetime set to//from ww w.j a  v  a 2 s .  c o m
 *        {@link GSSCredential#DEFAULT_LIFETIME
 *        GSSCredential.DEFAULT_LIFETIME} is allowed.
 * @see org.globus.gsi.X509Credential#getDefaultCredential()
 */
public GSSCredential createCredential(GSSName name, int lifetime, Oid mech, int usage) throws GSSException {
    checkMechanism(mech);

    if (name != null) {
        if (name.isAnonymous()) {
            return new GlobusGSSCredentialImpl();
        } else {
            throw new GSSException(GSSException.UNAVAILABLE);
        }
    }

    X509Credential cred = null;

    Subject subject = JaasSubject.getCurrentSubject();
    if (subject != null) {
        logger.debug("Getting credential from context");
        Set gssCreds = subject.getPrivateCredentials(GlobusGSSCredentialImpl.class);
        if (gssCreds != null) {
            Iterator iter = gssCreds.iterator();
            if (iter.hasNext()) {
                GlobusGSSCredentialImpl credImpl = (GlobusGSSCredentialImpl) iter.next();
                cred = credImpl.getX509Credential();
            }
        }
    }

    if (lifetime == GSSCredential.INDEFINITE_LIFETIME || lifetime > 0) {
        // lifetime not supported
        throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "badLifetime01");
    }

    if (cred == null) {
        logger.debug("Getting default credential");
        try {
            cred = X509Credential.getDefaultCredential();
        } catch (CredentialException e) {
            throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, e);
        } catch (Exception e) {
            throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, e);
        }

        return getDefaultCredential(cred, usage);
    } else {
        return new GlobusGSSCredentialImpl(cred, usage);
    }
}