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 Set<Object> getPrivateCredentials() 

Source Link

Document

Return the Set of private credentials held by this Subject .

Usage

From source file:org.apache.qpid.server.management.plugin.HttpManagementUtil.java

public static void checkRequestAuthenticatedAndAccessAuthorized(HttpServletRequest request, Broker broker,
        HttpManagementConfiguration managementConfig) {
    HttpSession session = request.getSession();
    Subject subject = getAuthorisedSubject(session);
    if (subject == null) {
        subject = tryToAuthenticate(request, managementConfig);
        if (subject == null) {
            throw new SecurityException("Only authenticated users can access the management interface");
        }/*from   w w w  .  j  a  v  a 2s  .  co m*/

        Subject original = subject;
        subject = new Subject(false, original.getPrincipals(), original.getPublicCredentials(),
                original.getPrivateCredentials());
        subject.getPrincipals().add(new ServletConnectionPrincipal(request));
        subject.setReadOnly();

        assertManagementAccess(broker.getSecurityManager(), subject);

        saveAuthorisedSubject(session, subject);

    }
}

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

private static Subject insertWorkerTokens(Subject subject, Map<String, String> credentials) {
    if (credentials == null) {
        return subject;
    }//from  w  ww  . j  a  va 2s. c  om
    for (WorkerTokenServiceType type : WorkerTokenServiceType.values()) {
        WorkerToken token = readWorkerToken(credentials, type);
        if (token != null) {
            Set<Object> creds = subject.getPrivateCredentials();
            synchronized (creds) {
                WorkerToken previous = findWorkerToken(subject, type);
                creds.add(token);
                if (previous != null) {
                    creds.remove(previous);
                }
            }
        }
    }
    return subject;
}

From source file:org.hippoecm.frontend.service.restproxy.RestProxyServicePlugin.java

protected Subject getSubject() {
    PluginUserSession session = (PluginUserSession) UserSession.get();

    Credentials credentials = session.getCredentials();
    Subject subject = new Subject();

    subject.getPrivateCredentials().add(credentials);
    subject.setReadOnly();/*from  w w  w  . ja  va2 s .  co  m*/
    return subject;
}

From source file:org.apache.directory.server.kerberos.kdc.AbstractKerberosITest.java

/**
 * Obtains a TGT and service tickets for the user.
 * Also makes some assertions on the received tickets.
 *
 * @param encryptionType the encryption type to use
 * @throws Exception/*from   w ww . jav  a 2  s  . com*/
 */
protected void testObtainTickets(ObtainTicketParameters parameters) throws Exception {
    setupEnv(parameters);
    Subject subject = new Subject();

    KerberosTestUtils.obtainTGT(subject, USER_UID, USER_PASSWORD);

    assertEquals(1, subject.getPrivateCredentials().size());
    assertEquals(0, subject.getPublicCredentials().size());

    KerberosTestUtils.obtainServiceTickets(subject, USER_UID, LDAP_SERVICE_NAME, HOSTNAME);

    assertEquals(2, subject.getPrivateCredentials().size());
    assertEquals(0, subject.getPublicCredentials().size());

    for (KerberosTicket kt : subject.getPrivateCredentials(KerberosTicket.class)) {
        // System.out.println( kt.getClient() );
        // System.out.println( kt.getServer() );
        // System.out.println( kt.getSessionKeyType() );
        assertEquals(parameters.encryptionType.getValue(), kt.getSessionKeyType());
    }
}

From source file:com.zimbra.cs.security.sasl.GssAuthenticator.java

private Subject getSubject(Krb5Keytab keytab, KerberosPrincipal kp) throws IOException {
    List<KerberosKey> keys = keytab.getKeys(kp);
    if (keys == null) {
        getLog().warn("Key not found in keystore for service principal '" + kp + "'");
        return null;
    }/* ww  w  . j  ava 2s.c o m*/
    Subject subject = new Subject();
    subject.getPrincipals().add(kp);
    subject.getPrivateCredentials().addAll(keys);
    return subject;
}

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

@SuppressWarnings("unchecked")
private void addCredentialToSubject(Subject subject, Map<String, String> credentials) {
    try {/* w  w w.  j  av  a  2 s .  c  om*/
        for (Pair<String, Credentials> cred : getCredentials(credentials)) {
            subject.getPrivateCredentials().add(cred.getSecond());
            LOG.info("Credentials added to the subject.");
        }
    } catch (Exception e) {
        LOG.error("Failed to initialize and get UserGroupInformation.", e);
    }
}

From source file:org.artificer.devsvr.ArtificerDevServer.java

/**
 * @return a security handler/*from   ww  w .  j  av a 2  s .  co m*/
 */
private SecurityHandler createSecurityHandler(boolean forUI) {
    Constraint constraint = new Constraint();
    constraint.setName(Constraint.__BASIC_AUTH);
    constraint.setRoles(new String[] { "user" });
    constraint.setAuthenticate(true);

    ConstraintMapping cm = new ConstraintMapping();
    cm.setConstraint(constraint);
    cm.setPathSpec("/*");

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setSessionRenewedOnAuthentication(false);
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName("artificer");
    if (forUI) {
        csh.addConstraintMapping(cm);
    }
    csh.setLoginService(new HashLoginService() {
        @Override
        public UserIdentity login(String username, Object credentials) {
            Credential credential = (credentials instanceof Credential) ? (Credential) credentials
                    : Credential.getCredential(credentials.toString());
            Principal userPrincipal = new KnownUser(username, credential);
            Subject subject = new Subject();
            subject.getPrincipals().add(userPrincipal);
            subject.getPrivateCredentials().add(credential);
            String[] roles = new String[] { "user", "readonly", "readwrite", "admin" };
            for (String role : roles) {
                subject.getPrincipals().add(new RolePrincipal(role));
            }
            subject.setReadOnly();
            return _identityService.newUserIdentity(subject, userPrincipal, roles);
        }
    });

    return csh;
}

From source file:org.kalypso.simulation.grid.SimpleGridProcess.java

private GSSCredential getCredential() throws IOException {
    // 1./*from  w ww . j a  v a 2  s  .  c  om*/
    // search for credential in current security context
    final Subject currentSubject = org.globus.gsi.jaas.JaasSubject.getCurrentSubject();
    if (currentSubject != null) {
        final Set<Object> creds = currentSubject.getPrivateCredentials();
        if (creds.size() >= 1) {
            return (GSSCredential) creds.iterator().next();
        } else {
            // if we are on server side, we cannot just create a credential, so throw an exception
            throw new IOException("Current subject does not have private credentials.");
        }
    }

    // 2.
    // Authenticate with user credential defined in <USER_HOME>/.globus/cog.properties
    // or (if undefined) use default proxy certificate <TEMP>/X509...
    final ExtendedGSSManager manager = (ExtendedGSSManager) ExtendedGSSManager.getInstance();
    try {
        return manager.createCredential(GSSCredential.INITIATE_AND_ACCEPT);
    } catch (final GSSException e) {
        // wrap as IOException because we cannot do I/O without security
        throw new IOException(e);
    }
}

From source file:it.cnr.icar.eric.client.xml.registry.ConnectionImpl.java

/**
 * Forces authentication to occur.//from  w  w w .ja v a2  s  .c  om
 ** Add to JAXR 2.0??
 *
 * @throws JAXRException DOCUMENT ME!
 */
public void authenticate() throws JAXRException {
    // Obtain a LoginContext, needed for authentication. Tell it 
    // to use the LoginModule implementation specified by the 
    // entry named "Sample" in the JAAS login configuration 
    // file and to also use the specified CallbackHandler.
    LoginContext lc = null;

    try {
        loginModuleMgr.createLoginConfigFile();

        String applicationName = loginModuleMgr.getApplicationName();
        handler = loginModuleMgr.getCallbackHandler();

        lc = new LoginContext(applicationName, handler);

        // attempt authentication
        lc.login();

        //Get the authenticated Subject.
        Subject subject = lc.getSubject();
        Set<Object> privateCredentials = subject.getPrivateCredentials();

        //Set credentials on JAXR Connections
        setCredentials(privateCredentials);

        log.info(JAXRResourceBundle.getInstance().getString("message.SetCredentialsOnConnection"));
    } catch (LoginException le) {
        String msg = le.getMessage();

        if ((msg != null) && (!(msg.equalsIgnoreCase("Login cancelled")))) {
            throw new JAXRException(le);
        }
    } catch (SecurityException se) {
        throw new JAXRException(se);
    }
}

From source file:org.helios.ember.auth.SSHLoginService.java

/**
 * // w w  w .  jav a  2s.  c  om
 * <p><b><code>username</code></b> can be:<ol>
 *    <li><code>username</code></li>
 *    <li><code>username@hostname</code></li>
 *    <li><code>username@hostname:port</code></li>
 * </ol></p>
 * <p>However, a <code>":&lt;port&gt;"</code> in the username will be parsed out (in the browser ?) and prepended to the credentials as <code>"&lt;port&gt;:"</code> 
 * so technically #3 will never been seen, so:<ul>
 *    <li>If we see #1, strip and ignore (or error out) on a leading <code>":&lt;port&gt;"</code> in the credentials</li>
 *  <li>If we see #2, check the credentials a leading <code>":&lt;port&gt;"</code> and strip it out.</li>
 * </ul></p>
 * {@inheritDoc}
 * @see org.eclipse.jetty.security.LoginService#login(java.lang.String, java.lang.Object)
 */
@SuppressWarnings("unchecked")
@Override
public UserIdentity login(String username, Object credentials) {
    SessionLogin sessionLogin = SessionLogin.newSessionLogin(pkRepo.getJSch(), username, credentials);
    if (sessionLogin == null)
        return null;
    if (!sessionLogin.login(5000)) { // should be a param
        return null;
    }
    // ===== user authenticated, set up subject and principal
    Subject subject = new Subject();
    subject.getPrincipals().add(new RolePrincipal("foo"));

    if (subject.getPrivateCredentials().isEmpty()) {
        subject.getPrivateCredentials().add(new HashMap<String, String>(
                Collections.singletonMap(sessionLogin.getSessionKey(), sessionLogin.getPassword())));
        subject.getPublicCredentials().add(new HashMap<String, SessionLogin>(
                Collections.singletonMap(sessionLogin.getSessionKey(), sessionLogin)));
    } else {
        ((HashMap<String, String>) subject.getPrivateCredentials().iterator().next())
                .put(sessionLogin.getSessionKey(), sessionLogin.getPassword());
        ((HashMap<String, SessionLogin>) subject.getPublicCredentials().iterator().next())
                .put(sessionLogin.getSessionKey(), sessionLogin);
    }
    subject.getPrivateCredentials().add(sessionLogin.getPassword());
    subject.getPublicCredentials().add(sessionLogin.getSession());
    return new DefaultUserIdentity(subject, sessionLogin, new String[] { "foo" });
}