Example usage for javax.security.auth Subject getPublicCredentials

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

Introduction

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

Prototype

public Set<Object> getPublicCredentials() 

Source Link

Document

Return the Set of public credentials held by this Subject .

Usage

From source file:org.picketlink.test.trust.servlet.GatewayServlet.java

private SamlCredential getSamlToken() {
    Subject subject = SecurityAssociation.getSubject();
    for (Object c : subject.getPublicCredentials()) {
        if (c instanceof SamlCredential)
            return (SamlCredential) c;
    }/*from  www  .ja  va2s .  c o  m*/
    return null;
}

From source file:org.keysupport.shibboleth.idp.x509.X509AuthServlet.java

/** {@inheritDoc} */
@Override//from   w  w w.ja v a2 s . co m
protected void service(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse)
        throws ServletException, IOException {

    try {
        final String key = ExternalAuthentication.startExternalAuthentication(httpRequest);

        final X509Certificate[] certs = (X509Certificate[]) httpRequest
                .getAttribute("javax.servlet.request.X509Certificate");
        log.debug("{} X.509 Certificate(s) found in request", certs != null ? certs.length : 0);

        if (certs == null || certs.length < 1) {
            log.error("No X.509 Certificates found in request");
            httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                    AuthnEventIds.NO_CREDENTIALS);
            ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
            return;
        }

        final X509Certificate cert = certs[0];
        log.debug("End-entity X.509 certificate found with subject '{}', issued by '{}'",
                cert.getSubjectDN().getName(), cert.getIssuerDN().getName());

        if (trustEngine != null) {
            try {
                final BasicX509Credential cred = new BasicX509Credential(cert);
                cred.setEntityCertificateChain(Arrays.asList(certs));
                if (trustEngine.validate(cred, new CriteriaSet())) {
                    log.debug("Trust engine validated X.509 certificate");
                } else {
                    log.warn("Trust engine failed to validate X.509 certificate");
                    httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                            AuthnEventIds.INVALID_CREDENTIALS);
                    ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
                    return;
                }
            } catch (final SecurityException e) {
                log.error("Exception raised by trust engine", e);
                httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_EXCEPTION_KEY, e);
                ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
                return;
            }
        }

        final String passthrough = httpRequest.getParameter(PASSTHROUGH_PARAM);
        if (passthrough != null && Boolean.parseBoolean(passthrough)) {
            log.debug("Setting UI passthrough cookie");
            final Cookie cookie = new Cookie(PASSTHROUGH_PARAM, "1");
            cookie.setPath(httpRequest.getContextPath());
            cookie.setMaxAge(60 * 60 * 24 * 365);
            cookie.setSecure(true);
            httpResponse.addCookie(cookie);
        }

        final Subject subject = new Subject();
        subject.getPublicCredentials().add(cert);
        subject.getPrincipals().add(cert.getSubjectX500Principal());

        httpRequest.setAttribute(ExternalAuthentication.SUBJECT_KEY, subject);

        //         final String revokeConsent = httpRequest
        //               .getParameter(ProfileInterceptorFlowDescriptor.REVOKE_CONSENT_PARAM);
        //         if (revokeConsent != null
        //               && ("1".equals(revokeConsent) || "true"
        //                     .equals(revokeConsent))) {
        //            httpRequest.setAttribute(
        //                  ExternalAuthentication.REVOKECONSENT_KEY, Boolean.TRUE);
        //         }

        ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);

    } catch (final ExternalAuthenticationException e) {
        throw new ServletException("Error processing external authentication request", e);
    }
}

From source file:org.picketlink.test.trust.servlet.GatewayServlet.java

private void authInfoAction(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    PrintWriter out = resp.getWriter();
    out.println("GatewayAuthentication=Success");
    out.println("ClassName=" + this.getClass().getName());
    out.println("--------------------------------------");

    out.println("UserPrincipal=" + req.getUserPrincipal().getName());
    out.println("--------------------------------------");

    Subject subject = SecurityAssociation.getSubject();
    if (subject != null) {
        out.println("Subject=" + subject);
        out.println("--------------------------------------");
        out.println("PublicCredentialsSize=" + subject.getPublicCredentials().size());
        out.println("--------------------------------------");
        int i = 0;
        for (Object c : subject.getPublicCredentials()) {
            out.println("Credential[" + i + "]=" + c.toString());
            i++;/*from  w  w  w  . jav  a2s. c o m*/
        }
    }
}

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

/**
 * //from  w  ww  .j ava 2s.co  m
 * <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" });
}

From source file:nl.nn.adapterframework.util.SsoUtil.java

public static String getSsoToken()
        throws WSSecurityException, CredentialDestroyedException, CredentialExpiredException {
    String result = null;/*from   w  w w .  jav a  2s . c  o  m*/

    Subject subj = WSSubject.getCallerSubject();

    if (subj == null) {
        throw new WSSecurityException("could not find Subject");
    }
    Set pubs = subj.getPublicCredentials();
    if (pubs == null) {
        throw new WSSecurityException("could not find PublicCredentials");
    }
    for (Iterator it = pubs.iterator(); result == null && it.hasNext();) {
        Object pc = it.next();
        if (pc instanceof WSCredentialImpl) {
            WSCredentialImpl wsci = (WSCredentialImpl) pc;
            byte token[] = wsci.getCredentialToken();
            if (token != null && token.length > 0) {
                result = Base64.encodeBase64String(token);
            }
        }
    }
    return result;
}

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/*w w w.j av  a 2s .  co m*/
 */
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:org.apache.hadoop.hive.shims.Hadoop23Shims.java

@Override
public UserGroupInformation cloneUgi(UserGroupInformation baseUgi) throws IOException {
    // Based on UserGroupInformation::createProxyUser.
    // TODO: use a proper method after we can depend on HADOOP-13081.
    if (getSubjectMethod == null) {
        throw new IOException("The UGI method was not found: " + ugiCloneError);
    }/*  w w  w  .  j  ava2 s . c o  m*/
    try {
        Subject origSubject = (Subject) getSubjectMethod.invoke(baseUgi);

        Subject subject = new Subject(false, origSubject.getPrincipals(),
                cloneCredentials(origSubject.getPublicCredentials()),
                cloneCredentials(origSubject.getPrivateCredentials()));
        return ugiCtor.newInstance(subject);
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
        throw new IOException(e);
    }
}

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");
        }// www .ja  v a2s  . 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.globus.workspace.client_common.TempBaseClient.java

public void setOptions(Stub stub) throws Exception {

    if (this.descriptorFile != null) {
        stub._setProperty(Constants.CLIENT_DESCRIPTOR_FILE, this.descriptorFile);
        return;//from   ww  w .ja va 2s  .  c om
    }

    if (this.protection != null) {
        // this means if both transport security and message security
        // are enabled both will get the same protection
        if (this.endpoint.getAddress().getScheme().equals("https")) {
            stub._setProperty(GSIConstants.GSI_TRANSPORT, this.protection);
        }
        if (this.mechanism != null) {
            stub._setProperty(this.mechanism, this.protection);
        }
    }

    if (this.convActor != null) {
        stub._setProperty("gssActor", this.convActor);
    }

    if (this.delegation != null) {
        stub._setProperty(GSIConstants.GSI_MODE, this.delegation);
    }

    if (this.authorization != null) {
        stub._setProperty(Constants.AUTHORIZATION, this.authorization);
    }

    if (this.anonymous != null) {
        stub._setProperty(Constants.GSI_ANONYMOUS, this.anonymous);
    }

    if (this.msgActor != null) {
        stub._setProperty("x509Actor", this.msgActor);
    }

    if ((Constants.GSI_SEC_MSG.equals(this.mechanism)) && (Constants.ENCRYPTION.equals(this.protection))) {
        Subject subject = new Subject();
        X509Certificate serverCert = CertUtil.loadCertificate(publicKeyFilename);
        EncryptionCredentials encryptionCreds = new EncryptionCredentials(new X509Certificate[] { serverCert });
        subject.getPublicCredentials().add(encryptionCreds);
        stub._setProperty(Constants.PEER_SUBJECT, subject);
    }

    if (this.contextLifetime != null) {
        stub._setProperty(Constants.CONTEXT_LIFETIME, this.contextLifetime);
    }

    final GSSCredential usercred = NimbusCredential.getGSSCredential();
    if (usercred != null) {
        stub._setProperty(GSIConstants.GSI_CREDENTIALS, usercred);
    }
}