Example usage for javax.security.auth Subject toString

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

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Return the String representation of this Subject .

Usage

From source file:com.qut.middleware.esoe.authn.plugins.spnego.authenticator.KerberosV5Authenticator.java

@SuppressWarnings("unchecked")
private String loginAndAction(String loginContextName, KerberosAuthenticationAction actionToPerform) {
    LoginContext context = null;//from  w  w w.  jav a  2s  . c om

    try {
        // Create a LoginContext 
        context = new LoginContext(loginContextName, null, null, this.config);

        this.logger.trace(Messages.getString("KerberosV5Authenticator.7") + loginContextName); //$NON-NLS-1$

        // Perform server authentication
        context.login();

        Subject subject = context.getSubject();
        this.logger.trace(subject.toString());
        this.logger.trace(Messages.getString("KerberosV5Authenticator.8") + subject.getPrincipals()); //$NON-NLS-1$

        // perform kerberos validation
        return (String) (Subject.doAs(subject, actionToPerform));

    } catch (LoginException e) {
        this.logger.warn(Messages.getString("KerberosV5Authenticator.9")); //$NON-NLS-1$
        this.logger.trace(e.getLocalizedMessage(), e);

        return null;
    } catch (PrivilegedActionException e) {
        this.logger.trace(e.getLocalizedMessage(), e);
        this.logger.trace(Messages.getString("KerberosV5Authenticator.10") + e.getCause().getMessage()); //$NON-NLS-1$

        return null;
    } catch (Exception e) {
        this.logger.debug(Messages.getString("KerberosV5Authenticator.11") + e.getCause().getMessage()); //$NON-NLS-1$
        this.logger.trace(e.getLocalizedMessage(), e);

        return null;
    }

}

From source file:org.atricore.idbus.capabilities.sso.main.sp.producers.AssertionConsumerProducer.java

protected void doProcessSamlResponseType(CamelMediationExchange exchange, ResponseType response)
        throws Exception {
    // Incomming message
    CamelMediationMessage in = (CamelMediationMessage) exchange.getIn();

    // Mediation state
    MediationState state = in.getMessage().getState();

    // May be used later by HTTP-Redirect binding!
    AbstractSSOMediator mediator = (AbstractSSOMediator) channel.getIdentityMediator();
    state.setAttribute("SAMLR2Signer", mediator.getSigner());

    // Originally received Authn request from binding channel
    // When using IdP initiated SSO, this will be null!
    SPInitiatedAuthnRequestType ssoRequest = (SPInitiatedAuthnRequestType) state
            .getLocalVariable("urn:org:atricore:idbus:sso:protocol:SPInitiatedAuthnRequest");
    state.removeLocalVariable("urn:org:atricore:idbus:sso:protocol:SPInitiatedAuthnRequest");

    // Destination, where to respond the above referred request
    String destinationLocation = ((SSOSPMediator) channel.getIdentityMediator()).getSpBindingACS();
    if (destinationLocation == null)
        throw new SSOException("SP Mediator does not have resource location!");

    EndpointDescriptor destination = new EndpointDescriptorImpl("EmbeddedSPAcs", "AssertionConsumerService",
            SSOBinding.SSO_ARTIFACT.getValue(), destinationLocation, null);

    // Stored by SP Initiated producer
    AuthnRequestType authnRequest = (AuthnRequestType) state
            .getLocalVariable(SAMLR2Constants.SAML_PROTOCOL_NS + ":AuthnRequest");
    state.removeLocalVariable(SAMLR2Constants.SAML_PROTOCOL_NS + ":AuthnRequest");

    if (logger.isDebugEnabled())
        logger.debug("Previous AuthnRequest " + (authnRequest != null ? authnRequest.getID() : "<NONE>"));

    if (ssoRequest != null && ssoRequest.getReplyTo() != null) {
        destination = new EndpointDescriptorImpl("EmbeddedSPAcs", "AssertionConsumerService",
                SSOBinding.SSO_ARTIFACT.getValue(), ssoRequest.getReplyTo(), null);
    }/*from  www.  j  a v a  2  s  .c o  m*/

    // ------------------------------------------------------
    // Handle Proxy Mode
    // ------------------------------------------------------

    validateResponse(authnRequest, response, in.getMessage().getRawContent(), state);
    //
    if (mediator.isVerifyUniqueIDs())
        mediator.getIdRegistry().register(response.getID());

    String issuerAlias = response.getIssuer().getValue();

    // Response is valid, check received status!
    StatusCode status = StatusCode.asEnum(response.getStatus().getStatusCode().getValue());
    StatusCode secStatus = response.getStatus().getStatusCode().getStatusCode() != null
            ? StatusCode.asEnum(response.getStatus().getStatusCode().getStatusCode().getValue())
            : null;

    if (logger.isDebugEnabled())
        logger.debug("Received status code " + status.getValue()
                + (secStatus != null ? "/" + secStatus.getValue() : ""));

    if (status.equals(StatusCode.TOP_RESPONDER) && secStatus != null
            && secStatus.equals(StatusCode.NO_PASSIVE)) {

        // Automatic Login failed
        if (logger.isDebugEnabled())
            logger.debug("IDP Reports Passive login failed");

        // This is SP initiated SSO or  we did not requested passive authentication
        if (authnRequest == null || authnRequest.getForceAuthn()) {
            throw new SSOException("IDP Sent " + StatusCode.NO_PASSIVE + " but passive was not requested.");
        }

        Properties auditProps = new Properties();
        auditProps.put("idpAlias", issuerAlias);
        auditProps.put("passive", "true");
        recordInfoAuditTrail("SP-SSOR", ActionOutcome.FAILURE, null, exchange, auditProps);

        // Send a 'no-passive' status response
        SPAuthnResponseType ssoResponse = buildSPAuthnResponseType(exchange, ssoRequest, null, destination);

        CamelMediationMessage out = (CamelMediationMessage) exchange.getOut();
        out.setMessage(new MediationMessageImpl(ssoResponse.getID(), ssoResponse, "SPAuthnResposne", null,
                destination, in.getMessage().getState()));

        exchange.setOut(out);
        return;

    } else if (!status.equals(StatusCode.TOP_SUCCESS)) {
        throw new SSOException("Unexpected IDP Status Code " + status.getValue()
                + (secStatus != null ? "/" + secStatus.getValue() : ""));

    }

    // check if there is an existing session for the user
    // if not, check if channel is federation-capable
    FederationChannel fChannel = (FederationChannel) channel;
    if (fChannel.getAccountLinkLifecycle() == null) {

        // cannot map subject to local account, terminate
        logger.error("No Account Lifecycle configured for Channel [" + fChannel.getName() + "] " + " Response ["
                + response.getID() + "]");
        throw new SSOException("No Account Lifecycle configured for Channel [" + fChannel.getName() + "] "
                + " Response [" + response.getID() + "]");
    }

    AccountLinkLifecycle accountLinkLifecycle = fChannel.getAccountLinkLifecycle();

    // ------------------------------------------------------------------
    // Build IDP Subject from response
    // ------------------------------------------------------------------
    Subject idpSubject = buildSubjectFromResponse(response);

    AccountLink acctLink = null;
    AccountLinkEmitter accountLinkEmitter = fChannel.getAccountLinkEmitter();

    if (logger.isTraceEnabled())
        logger.trace("Account Link Emitter Found for Channel [" + fChannel.getName() + "]");

    // Emit account link information
    acctLink = accountLinkEmitter.emit(idpSubject);

    if (logger.isDebugEnabled())
        logger.debug("Emitted Account Link ["
                + (acctLink != null ? "[" + acctLink.getId() + "]" + acctLink.getLocalAccountNameIdentifier()
                        : "null")
                + "] [" + fChannel.getName() + "] " + " for IDP Subject [" + idpSubject + "]");

    if (acctLink == null) {

        logger.error("No Account Link for Channel [" + fChannel.getName() + "] " + " Response ["
                + response.getID() + "]");

        throw new IdentityMediationFault(StatusCode.TOP_REQUESTER.getValue(), null,
                StatusDetails.NO_ACCOUNT_LINK.getValue(), idpSubject.toString(), null);
    }

    // ------------------------------------------------------------------
    // fetch local account for subject, if any
    // ------------------------------------------------------------------
    Subject localAccountSubject = accountLinkLifecycle.resolve(acctLink);
    if (logger.isTraceEnabled())
        logger.trace("Account Link [" + acctLink.getId() + "] resolved to " + "Local Subject ["
                + localAccountSubject + "] ");

    Subject federatedSubject = localAccountSubject; // if no identity mapping, the local account subject is used

    // having both remote and local accounts information, is now time to apply custom identity mapping rules
    if (fChannel.getIdentityMapper() != null) {
        IdentityMapper im = fChannel.getIdentityMapper();

        if (logger.isTraceEnabled())
            logger.trace("Using identity mapper : " + im.getClass().getName());

        federatedSubject = im.map(idpSubject, localAccountSubject);
    }

    // Add IDP Name to federated Subject
    if (logger.isDebugEnabled())
        logger.debug("IDP Subject [" + idpSubject + "] mapped to Subject [" + federatedSubject + "] "
                + "through Account Link [" + acctLink.getId() + "]");

    // ---------------------------------------------------
    // Create SP Security context and session!
    // ---------------------------------------------------

    CircleOfTrustMemberDescriptor idp = resolveIdp(exchange);

    // We must have an assertion!
    SPSecurityContext spSecurityCtx = createSPSecurityContext(exchange,
            (ssoRequest != null && ssoRequest.getReplyTo() != null ? ssoRequest.getReplyTo() : null), idp,
            acctLink, federatedSubject, idpSubject,
            (AssertionType) response.getAssertionOrEncryptedAssertion().get(0));

    Properties auditProps = new Properties();
    auditProps.put("idpAlias", spSecurityCtx.getIdpAlias());
    auditProps.put("idpSession", spSecurityCtx.getIdpSsoSession());

    Set<SubjectNameID> principals = federatedSubject.getPrincipals(SubjectNameID.class);
    SubjectNameID principal = null;
    if (principals.size() == 1) {
        principal = principals.iterator().next();
    }
    recordInfoAuditTrail("SP-SSOR", ActionOutcome.SUCCESS, principal != null ? principal.getName() : null,
            exchange, auditProps);

    Collection<CircleOfTrustMemberDescriptor> availableIdPs = getCotManager().lookupMembersForProvider(
            fChannel.getFederatedProvider(), SSOMetadataConstants.IDPSSODescriptor_QNAME.toString());

    SPAuthnResponseType ssoResponse = buildSPAuthnResponseType(exchange, ssoRequest, spSecurityCtx,
            destination);

    CamelMediationMessage out = (CamelMediationMessage) exchange.getOut();

    // ---------------------------------------------------
    // We must tell our Entity selector about the IdP we're using.  It's considered a selection.
    // ---------------------------------------------------
    if (availableIdPs.size() > 1) {

        EndpointDescriptor idpSelectorCallbackEndpoint = resolveIdPSelectorCallbackEndpoint(exchange, fChannel);

        if (idpSelectorCallbackEndpoint != null) {

            if (logger.isDebugEnabled())
                logger.debug("Sending Current Selected IdP request, callback location : "
                        + idpSelectorCallbackEndpoint);

            // Store destination and response
            CurrentEntityRequestType entityRequest = new CurrentEntityRequestType();

            entityRequest.setID(uuidGenerator.generateId());
            entityRequest.setIssuer(getCotMemberDescriptor().getAlias());
            entityRequest.setEntityId(idp.getAlias());

            entityRequest.setReplyTo(idpSelectorCallbackEndpoint.getResponseLocation() != null
                    ? idpSelectorCallbackEndpoint.getResponseLocation()
                    : idpSelectorCallbackEndpoint.getLocation());

            String idpSelectorLocation = ((SSOSPMediator) mediator).getIdpSelector();

            EndpointDescriptor entitySelectorEndpoint = new EndpointDescriptorImpl("IDPSelectorEndpoint",
                    "EntitySelector", SSOBinding.SSO_ARTIFACT.toString(), idpSelectorLocation, null);

            out.setMessage(new MediationMessageImpl(entityRequest.getID(), entityRequest,
                    "CurrentEntityRequest", null, entitySelectorEndpoint, in.getMessage().getState()));

            state.setLocalVariable(SSOConstants.SSO_RESPONSE_VAR_TMP, ssoResponse);
            state.setLocalVariable(SSOConstants.SSO_RESPONSE_ENDPOINT_VAR_TMP, destination);

            return;
        } else {
            if (logger.isDebugEnabled())
                logger.debug("Multipel IdPs found, but no callback idp selection service is avaiable");
        }
    }

    // ---------------------------------------------------
    // Send SPAuthnResponse
    // ---------------------------------------------------

    out.setMessage(new MediationMessageImpl(ssoResponse.getID(), ssoResponse, "SPAuthnResponse", null,
            destination, in.getMessage().getState()));

    exchange.setOut(out);

}

From source file:org.betaconceptframework.astroboa.client.AstroboaClient.java

/**
 * Allows client to login to an Astroboa repository without authenticating
 * user. This method runs only within Local context for security reasons.
 * // w  w w. j a va2s . co  m
 * @param repositoryId Repository identifier as provided
 * in repositories-conf.xml
 * 
 * @param subject Subject created during authentication by another system.
 * 
 * @param permanentKey  representing a trusted client whose token is never expired
 */
public void login(String repositoryId, Subject subject, String permanentKey) {

    if (getRepositoryService() != null) {
        authenticationToken = ((RepositoryServiceClientWrapper) getRepositoryService()).login(repositoryId,
                subject, permanentKey);
        cmsRepositoryEntityFactory = new CmsRepositoryEntityFactory() {

            @Override
            public String getAuthenticationToken() {
                return authenticationToken;
            }

        };

        //Login to Identity Store as well with the same credentials
        if (getIdentityStore() != null) {
            ((IdentityStoreClientWrapper) getIdentityStore()).login(subject, permanentKey);
        }

        if (subject == null) {
            //Normally this should never happen
            keepRepositoryAndUser(repositoryId, "unknown");
        } else if (subject.getPrincipals(IdentityPrincipal.class) != null
                && !subject.getPrincipals(IdentityPrincipal.class).isEmpty()) {
            keepRepositoryAndUser(repositoryId,
                    subject.getPrincipals(IdentityPrincipal.class).iterator().next().getName());
        } else {
            keepRepositoryAndUser(repositoryId, subject.toString());
        }
    }
}