Example usage for javax.security.auth Subject getPrincipals

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

Introduction

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

Prototype

public <T extends Principal> Set<T> getPrincipals(Class<T> c) 

Source Link

Document

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

Usage

From source file:org.apache.hadoop.security.UserGroupInformation.java

/**
 * Create a UserGroupInformation for the given subject.
 * This does not change the subject or acquire new credentials.
 * @param subject the user's subject//  w  w  w . j a  v a 2s . c  o  m
 */
UserGroupInformation(Subject subject) {
    this.subject = subject;
    this.user = subject.getPrincipals(User.class).iterator().next();
    this.isKeytab = !subject.getPrivateCredentials(KerberosKey.class).isEmpty();
    this.isKrbTkt = !subject.getPrivateCredentials(KerberosTicket.class).isEmpty();
}

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.
 * /*from   www.  j a  v a 2s .  c o  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());
        }
    }
}

From source file:com.buaa.cfs.security.UserGroupInformation.java

/**
 * Create a UserGroupInformation for the given subject. This does not change the subject or acquire new
 * credentials./*ww  w .j a v a2s  .co  m*/
 *
 * @param subject the user's subject
 */
UserGroupInformation(Subject subject) {
    this.subject = subject;
    this.user = subject.getPrincipals(User.class).iterator().next();
    this.isKeytab = !subject.getPrivateCredentials(KeyTab.class).isEmpty();
    this.isKrbTkt = !subject.getPrivateCredentials(KerberosTicket.class).isEmpty();
}

From source file:com.ideabase.repository.webservice.controller.RESTfulControllerImpl.java

/**
 * Find {@see RepositoryUserPrincipal} from {@see Subject} object which must
 * be in {@see HttpSession} attribute list. if no such principal found an
 * unchecked exception will be raised./*  w ww  . ja va 2 s .  c  o m*/
 *
 * @param pRequest http servlet request.
 * @return the user id.
 */
private Integer findActiveUser(final HttpServletRequest pRequest) {
    final String authToken = pRequest.getParameter(PARAM_AUTH_TOKEN);
    final Subject subject;
    if (mStateManager != null && authToken != null) {
        final RequestState requestState = mStateManager.getRequestStateForToken(authToken);
        subject = requestState.getSubject();
    } else {
        subject = (Subject) pRequest.getSession().getAttribute(SESSION_ATTR_USER_SUBJECT);
    }
    final Set<RepositoryUserPrincipal> principals = subject.getPrincipals(RepositoryUserPrincipal.class);
    if (principals != null && !principals.isEmpty()) {
        final RepositoryUserPrincipal principal = principals.iterator().next();
        return principal.getId();
    } else {
        throw ServiceException.aNew(subject, "Subject doesn't contain the RepositoryUserPrincipal.");
    }
}

From source file:org.atricore.idbus.capabilities.sso.main.idp.producers.SingleSignOnProducer.java

/**
 * This will emit an assertion using the received claims.  If the process is successful, a SAML Response will
 * be issued to the original SP./*w w w  .  ja va 2s . c om*/
 * If an error occurs, the procedure will decide to retry collecting claims with the las
 * claims endpoint selected or collect claims using a new claims endpoint.
 * <p/>
 * If no more claim endpoints are available, this will send an status error response to the SP.
 *
 * @param exchange
 * @param claimsResponse
 * @throws Exception
 */
protected void doProcessClaimsResponse(CamelMediationExchange exchange,
        SSOCredentialClaimsResponse claimsResponse) throws Exception {

    //------------------------------------------------------------
    // Process a claims response
    //------------------------------------------------------------

    CamelMediationMessage in = (CamelMediationMessage) exchange.getIn();
    CamelMediationMessage out = (CamelMediationMessage) exchange.getOut();
    MediationState state = in.getMessage().getState();

    AuthenticationState authnState = getAuthnState(exchange);
    AuthnRequestType authnRequest = authnState.getAuthnRequest();
    IdentityMediationEndpoint prevClaimsEndpoint = authnState.getCurrentClaimsEndpoint();

    NameIDType issuer = authnRequest.getIssuer();
    CircleOfTrustMemberDescriptor sp = resolveProviderDescriptor(issuer);

    String responseMode = authnState.getResponseMode();
    String responseFormat = authnState.getResponseFormat();

    if (responseMode != null && responseMode.equalsIgnoreCase("unsolicited")) {
        logger.debug("Response Mode for Claim Response " + authnRequest.getID() + " is unsolicited");
        logger.debug("Response Format for Claim Response " + authnRequest.getID() + " is " + responseFormat);
    } else {
        logger.debug("Response Mode for Claim Response " + authnRequest.getID() + " is NOT unsolicited");
    }

    // ----------------------------------------------------
    // Emit new assertion
    // ----------------------------------------------------

    try {

        authnState.setSsoAttepmts(authnState.getSsoAttepmts() + 1);

        // Resolve SP endpoint
        EndpointDescriptor ed = this.resolveSpAcsEndpoint(exchange, authnRequest);

        // -------------------------------------------------------
        // Build STS Context
        // -------------------------------------------------------
        // The context will act as an alternative communication exchange between this producer (IDP) and the STS.
        // It will transport back the Subject which is not supported by the WST protocol
        SamlR2SecurityTokenEmissionContext securityTokenEmissionCtx = new SamlR2SecurityTokenEmissionContext();
        // Send extra information to STS, using the emission context

        securityTokenEmissionCtx.setIssuerMetadata(((SPChannel) channel).getMember().getMetadata());
        securityTokenEmissionCtx.setMember(sp);
        securityTokenEmissionCtx.setIdentityPlanName(getSTSPlanName());
        // TODO : Resolve SP SAMLR2 Role springmetadata

        securityTokenEmissionCtx.setRoleMetadata(null);
        securityTokenEmissionCtx.setAuthnState(authnState);
        securityTokenEmissionCtx.setSessionIndex(uuidGenerator.generateId());
        securityTokenEmissionCtx.setSpAcs(ed);

        // ----------------------------------------------------------------------------------------
        // Authenticate the user, send a RequestSecurityToken to the Security Token Service (STS)
        // and emit a SAML 2.0 Assertion
        // ----------------------------------------------------------------------------------------

        securityTokenEmissionCtx = emitAssertionFromClaims(exchange, securityTokenEmissionCtx,
                claimsResponse.getClaimSet(), sp);

        AssertionType assertion = securityTokenEmissionCtx.getAssertion();
        Subject authnSubject = securityTokenEmissionCtx.getSubject();

        SimplePrincipal principal = authnSubject.getPrincipals(SimplePrincipal.class).iterator().next();

        if (logger.isDebugEnabled())
            logger.debug("New Assertion " + assertion.getID() + " emitted form request "
                    + (authnRequest != null ? authnRequest.getID() : "<NULL>"));

        // Generate audit trail
        AbstractSSOMediator mediator = (AbstractSSOMediator) channel.getIdentityMediator();
        AuditingServer aServer = mediator.getAuditingServer();

        Properties auditProps = new Properties();
        auditProps.put("attempt", authnState.getSsoAttepmts() + "");
        if (authnState.getCurrentAuthnCtxClass() != null)
            auditProps.put("authnCtx", authnState.getCurrentAuthnCtxClass().getValue());
        recordInfoAuditTrail("SSO", ActionOutcome.SUCCESS, principal != null ? principal.getName() : null,
                exchange, auditProps);

        if (((IdentityProvider) getProvider()).isIdentityConfirmationEnabled()) {
            // --------------------------------------------------------------------
            // Confirm user's identity in case needed
            // --------------------------------------------------------------------
            logger.debug("Confirming user's identity with claims [" + claimsResponse.getClaimSet().getClaims()
                    + "] and " + "subject [" + securityTokenEmissionCtx.getSubject() + "]");

            UsernameTokenType usernameToken = new UsernameTokenType();
            AttributedString usernameString = new AttributedString();
            usernameString.setValue(principal.getName());
            usernameToken.setUsername(usernameString);
            Claim principalClaim = new CredentialClaimImpl("", usernameToken);
            claimsResponse.getClaimSet().addClaim(principalClaim);

            IdentityConfirmationChannel idConfChannel = selectNextIdentityConfirmationEndpoint(authnState,
                    exchange, claimsResponse.getClaimSet());
            IdentityMediationEndpoint idConfEndpoint = authnState.getCurrentIdConfirmationEndpoint();
            if (idConfEndpoint != null) {
                logger.debug("Selected identity confirmation endpoint : " + idConfEndpoint);

                // Create Claims Request
                IdentityConfirmationRequest idConfRequest = new IdentityConfirmationRequestImpl(
                        (SPChannel) channel, authnRequest.getIssuer().getValue());

                for (Claim claim : claimsResponse.getClaimSet().getClaims()) {
                    idConfRequest.getClaims().add(claim);
                }

                // generate our own claims
                idConfRequest.getClaims().add(
                        new UserClaimImpl("", "sourceIpAddress", state.getTransientVariable("RemoteAddress")));
                idConfRequest.getClaims().add(new UserClaimImpl("", "emailAddress", "gbrigand@gmail.com"));

                // --------------------------------------------------------------------
                // Submit identity confirmation request
                // --------------------------------------------------------------------

                EndpointDescriptor idConfEp = new EndpointDescriptorImpl(idConfEndpoint.getBinding(),
                        idConfEndpoint.getType(), idConfEndpoint.getBinding(),
                        idConfEndpoint.getLocation().startsWith("/")
                                ? idConfChannel.getLocation() + idConfEndpoint.getLocation()
                                : idConfEndpoint.getLocation(),
                        idConfEndpoint.getResponseLocation());

                logger.debug("Confirming user identity using endpoint " + idConfEp);

                clearAuthnState(exchange);

                out.setMessage(new MediationMessageImpl(idConfRequest.getId(), idConfRequest,
                        "IdentityConfirmationRequest", null, idConfEp, in.getMessage().getState()));

                exchange.setOut(out);
                return;
            } else {
                logger.debug("There is no endpoint available for identity confirmation. Skipping.");
            }
        }

        if (logger.isDebugEnabled())
            logger.debug("New Assertion " + assertion.getID() + " emitted form request "
                    + (authnRequest != null ? authnRequest.getID() : "<NULL>"));

        // Create a new SSO Session
        IdPSecurityContext secCtx = createSecurityContext(exchange, authnSubject, assertion,
                claimsResponse.getClaimSet());

        // Associate the SP with the new session, including relay state!
        // We already validated authn request issuer, so we can use it.
        secCtx.register(authnRequest.getIssuer(), authnState.getReceivedRelayState());

        // Build a response for the SP
        ResponseType saml2Response = buildSamlResponse(exchange, authnState, assertion, sp, ed);
        oasis.names.tc.saml._1_0.protocol.ResponseType saml11Response = null;

        // Set the SSO Session var
        in.getMessage().getState().setLocalVariable(getProvider().getName().toUpperCase() + "_SECURITY_CTX",
                secCtx);
        in.getMessage().getState().getLocalState()
                .addAlternativeId(IdentityProviderConstants.SEC_CTX_SSOSESSION_KEY, secCtx.getSessionIndex());

        // --------------------------------------------------------------------
        // Send Authn Response to SP
        // --------------------------------------------------------------------

        if (responseFormat != null && responseFormat.equals("urn:oasis:names:tc:SAML:1.1")) {
            saml11Response = transformSamlR2ResponseToSaml11(saml2Response);
            SamlR2Signer signer = ((SSOIDPMediator) channel.getIdentityMediator()).getSigner();
            saml11Response = signer.sign(saml11Response);
        }

        // Clear the current authentication state
        clearAuthnState(exchange);

        // If subject contains SSOPolicy enforcement principals, we need to show them to the user before moving on ...
        List<SSOPolicyEnforcementStatement> stmts = getPolicyEnforcementStatements(assertion);

        if (stmts != null && stmts.size() > 0) {

            if (logger.isDebugEnabled())
                logger.debug("Processing " + stmts.size() + " SSO Policy Enforcement Statements");

            // Store: Authn Response and Endpoint Descriptor
            in.getMessage().getState().setLocalVariable(
                    "urn:org:atricore:idbus:samlr2:idp:pendingAuthnResponse",
                    saml11Response != null ? saml11Response : saml2Response);

            in.getMessage().getState()
                    .setLocalVariable("urn:org:atricore:idbus:samlr2:idp:pendingAuthnResponseEndpoint", ed);

            in.getMessage().getState().setLocalVariable(
                    "urn:org:atricore:idbus:samlr2:idp:pendingAuthnResponseRelayState",
                    authnState.getReceivedRelayState());

            // 2. Send artifact to warning endpoint w/ policies
            EndpointDescriptor pweEd = new EndpointDescriptorImpl("PolicyEnforcementWarningService",
                    "PolicyEnforcementWarningService", SSOBinding.SSO_ARTIFACT.getValue(),
                    channel.getIdentityMediator().getWarningUrl(), null);

            EndpointDescriptor replyTo = resolveIdpSsoContinueEndpoint();
            PolicyEnforcementRequest per = new PolicyEnforcementRequestImpl(uuidGenerator.generateId(),
                    replyTo);

            per.getStatements().addAll(stmts);

            out.setMessage(new MediationMessageImpl(per.getId(), per, "PolicyEnforcementWarning", null, pweEd,
                    in.getMessage().getState()));
            return;
        }

        if (responseFormat != null && responseFormat.equals("urn:oasis:names:tc:SAML:1.1")) {

            if (logger.isDebugEnabled())
                logger.debug("Sending SAML 1.1 Response");

            out.setMessage(new MediationMessageImpl(saml11Response.getResponseID(), saml11Response, "Response",
                    authnState.getReceivedRelayState(), ed, in.getMessage().getState()));
        } else {

            if (logger.isDebugEnabled())
                logger.debug("Sending SAML 2.0 Response");

            // SAML R2 is used by default
            out.setMessage(new MediationMessageImpl(saml2Response.getID(), saml2Response, "Response",
                    authnState.getReceivedRelayState(), ed, in.getMessage().getState()));
        }

        exchange.setOut(out);

    } catch (SecurityTokenAuthenticationFailure e) {

        if (logger.isDebugEnabled())
            logger.debug("Security Token authentication failure : " + e.getMessage(), e);

        // Generate audit trail
        Properties auditProps = new Properties();
        auditProps.put("attempt", authnState.getSsoAttepmts() + "");
        if (authnState.getCurrentAuthnCtxClass() != null)
            auditProps.put("authnCtx", authnState.getCurrentAuthnCtxClass().getValue());

        recordInfoAuditTrail("SSO", ActionOutcome.FAILURE, e.getPrincipalName(), exchange, auditProps);

        // The authentication failed, let's see what needs to be done.

        // If the request was set to 'Passive', keep trying with passive claim endponits only!
        // If not, keep trying with other endpoints.

        // Set of policies enforced during authentication
        Set<SSOPolicyEnforcementStatement> ssoPolicyEnforcements = e.getSsoPolicyEnforcements();

        // Ask for more claims, using other auth schemes
        ClaimChannel claimChannel = selectNextClaimsEndpoint(authnState, exchange);
        IdentityMediationEndpoint claimEndpoint = authnState.getCurrentClaimsEndpoint();

        // No more claim endpoints available, the authentication process is over.
        if (claimEndpoint == null) {
            // Authentication failure, no more endpoints available, consider proxying to another IDP.
            if (logger.isDebugEnabled())
                logger.error("No claims endpoint found for authn request : " + authnRequest.getID());

            // Send failure response
            EndpointDescriptor ed = resolveSpAcsEndpoint(exchange, authnRequest);

            // This could be a response to a passive request ...
            ResponseType response = buildSamlResponse(exchange, authnState, null, sp, ed);

            out.setMessage(new MediationMessageImpl(response.getID(), response, "Response",
                    authnState.getReceivedRelayState(), ed, in.getMessage().getState()));

            exchange.setOut(out);
            return;
        }

        // We have another Claim endpoint to try, let's send the request.
        if (logger.isDebugEnabled())
            logger.debug("Selecting claims endpoint : " + endpoint.getName());

        SSOCredentialClaimsRequest claimsRequest = new SSOCredentialClaimsRequest(authnRequest.getID(), channel,
                endpoint, claimChannel, uuidGenerator.generateId());

        // We're retrying the same endpoint type, mark the authentication as failed
        if (prevClaimsEndpoint != null && prevClaimsEndpoint.getType().equals(claimEndpoint.getType()))
            claimsRequest.setLastErrorId("AUTHN_FAILED");

        claimsRequest.setLastErrorMsg(e.getMessage());
        claimsRequest.getSsoPolicyEnforcements().addAll(ssoPolicyEnforcements);

        // Update authentication state
        claimsRequest.setRequestedAuthnCtxClass(authnRequest.getRequestedAuthnContext());
        authnState.setAuthnRequest(authnRequest);

        // Set SP information
        if (authnRequest.getIssuer() != null)
            claimsRequest.setSpAlias(authnRequest.getIssuer().getValue());

        // --------------------------------------------------------------------
        // Send claims request
        // --------------------------------------------------------------------

        EndpointDescriptor ed = new EndpointDescriptorImpl(claimEndpoint.getBinding(), claimEndpoint.getType(),
                claimEndpoint.getBinding(), claimChannel.getLocation() + claimEndpoint.getLocation(),
                claimEndpoint.getResponseLocation());

        logger.debug(
                "Collecting claims using endpoint " + claimEndpoint.getName() + " [" + ed.getLocation() + "]");

        out.setMessage(new MediationMessageImpl(claimsRequest.getId(), claimsRequest, "ClaimsRequest", null, ed,
                in.getMessage().getState()));

        exchange.setOut(out);

    }

}

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

protected SPSecurityContext createSPSecurityContext(CamelMediationExchange exchange, String requester,
        CircleOfTrustMemberDescriptor idp, AccountLink acctLink, Subject federatedSubject, Subject idpSubject,
        AssertionType assertion) throws SSOException {

    if (logger.isDebugEnabled())
        logger.debug("Creating new SP Security Context for subject " + federatedSubject);

    IdPChannel idPChannel = (IdPChannel) channel;
    SSOSessionManager ssoSessionManager = idPChannel.getSessionManager();
    CamelMediationMessage in = (CamelMediationMessage) exchange.getIn();

    // Remove previous security context if any

    SPSecurityContext secCtx = (SPSecurityContext) in.getMessage().getState()
            .getLocalVariable(getProvider().getName().toUpperCase() + "_SECURITY_CTX");

    if (secCtx != null) {

        if (logger.isDebugEnabled())
            logger.debug("Invalidating old sso session " + secCtx.getSessionIndex());
        try {//from   ww w .  j a  v  a  2  s .c  om
            ssoSessionManager.invalidate(secCtx.getSessionIndex());
        } catch (NoSuchSessionException e) {
            // Ignore this ...
            if (logger.isDebugEnabled())
                logger.debug("Invalidating already expired sso session " + secCtx.getSessionIndex());

        } catch (SSOSessionException e) {
            throw new SSOException(e);
        }

    }

    // Get Subject ID (username ?)
    SubjectNameID nameId = null;
    Set<SubjectNameID> nameIds = federatedSubject.getPrincipals(SubjectNameID.class);

    if (nameIds != null && nameIds.size() > 0) {
        nameId = nameIds.iterator().next();
        if (logger.isTraceEnabled())
            logger.trace("Using Subject ID " + nameId.getName() + "[" + nameId.getFormat() + "] ");

        /* Old logic, serched for UNSPECIFIED Subject Name ID:
        for (SubjectNameID i : nameIds) {
                
        if (logger.isTraceEnabled())
            logger.trace("Checking Subject ID " + i.getName() + "["+i.getFormat()+"] ");
                
        // TODO : Support other name ID formats !!!
        if (i.getFormat() == null || i.getFormat().equals(NameIDFormat.UNSPECIFIED.getValue())) {
            nameId = i;
            break;
        }
        } */
    }

    if (nameId == null) {
        logger.error("No suitable Subject Name Identifier (SubjectNameID) found");
        throw new SSOException("No suitable Subject Name Identifier (SubjectNameID) found");
    }

    String idpSessionIndex = null;
    Collection<SubjectAuthenticationAttribute> authnAttrs = idpSubject
            .getPrincipals(SubjectAuthenticationAttribute.class);
    for (SubjectAuthenticationAttribute authnAttr : authnAttrs) {
        if (authnAttr.getName().equals(SubjectAuthenticationAttribute.Name.SESSION_INDEX.name())) {
            idpSessionIndex = authnAttr.getValue();
            break;
        }
    }

    AuthnCtxClass authnCtx = null;
    for (StatementAbstractType stmt : assertion.getStatementOrAuthnStatementOrAuthzDecisionStatement()) {
        if (stmt instanceof AuthnStatementType) {
            AuthnStatementType authnStmt = (AuthnStatementType) stmt;

            for (JAXBElement e : authnStmt.getAuthnContext().getContent()) {
                if (e.getName().getLocalPart().equals("AuthnContextClassRef")) {
                    authnCtx = AuthnCtxClass.asEnum((String) e.getValue());
                    break;
                }
            }
            break;
        }
    }

    // Create a new Security Context
    secCtx = new SPSecurityContext();

    secCtx.setIdpAlias(idp.getAlias());
    secCtx.setIdpSsoSession(idpSessionIndex);
    secCtx.setSubject(federatedSubject);
    secCtx.setAccountLink(acctLink);
    secCtx.setRequester(requester);
    secCtx.setAuthnCtxClass(authnCtx);

    SecurityToken<SPSecurityContext> token = new SecurityTokenImpl<SPSecurityContext>(
            uuidGenerator.generateId(), secCtx);

    try {
        // Create new SSO Session

        // Take session timeout from the assertion, if available.
        Calendar sessionExpiration = getSessionNotOnOrAfter(assertion);
        long sessionTimeout = 0;

        if (sessionExpiration != null) {
            sessionTimeout = (sessionExpiration.getTimeInMillis() - System.currentTimeMillis()) / 1000L;
        }

        String ssoSessionId = (sessionTimeout > 0
                ? ssoSessionManager.initiateSession(nameId.getName(), token, (int) sessionTimeout)
                : // Request session timeout
                ssoSessionManager.initiateSession(nameId.getName(), token)); // Use default session timeout

        if (logger.isTraceEnabled())
            logger.trace("Created SP SSO Session with id " + ssoSessionId);

        // Update security context with SSO Session ID
        secCtx.setSessionIndex(ssoSessionId);

        Set<SubjectAuthenticationAttribute> attrs = idpSubject
                .getPrincipals(SubjectAuthenticationAttribute.class);
        String idpSsoSessionId = null;
        for (SubjectAuthenticationAttribute attr : attrs) {
            // Session index
            if (attr.getName().equals(SubjectAuthenticationAttribute.Name.SESSION_INDEX.name())) {
                idpSsoSessionId = attr.getValue();
                break;
            }
        }

        // SubjectAuthenticationAttribute.Name.SESSION_NOT_ON_OR_AFTER

        if (logger.isDebugEnabled())
            logger.debug("Created SP security context " + secCtx);

        in.getMessage().getState().setLocalVariable(getProvider().getName().toUpperCase() + "_SECURITY_CTX",
                secCtx);
        in.getMessage().getState().getLocalState().addAlternativeId("ssoSessionId", secCtx.getSessionIndex());
        in.getMessage().getState().getLocalState().addAlternativeId("idpSsoSessionId", idpSsoSessionId);

        if (logger.isTraceEnabled())
            logger.trace(
                    "Stored SP Security Context in " + getProvider().getName().toUpperCase() + "_SECURITY_CTX");

        return secCtx;
    } catch (SSOSessionException e) {
        throw new SSOException(e);
    }

}

From source file:org.atricore.idbus.capabilities.sso.main.idp.producers.SingleSignOnProducer.java

/**
 * This will return an emission context with both, the required SAMLR2 Assertion and the associated Subject.
 *
 * @return SamlR2 Security emission context containing SAMLR2 Assertion and Subject.
 *///  w  w w. j  av a  2s.c  o  m
protected SamlR2SecurityTokenEmissionContext emitAssertionFromClaims(CamelMediationExchange exchange,
        SamlR2SecurityTokenEmissionContext securityTokenEmissionCtx, ClaimSet receivedClaims,
        CircleOfTrustMemberDescriptor sp) throws Exception {

    MessageQueueManager aqm = getArtifactQueueManager();

    // -------------------------------------------------------
    // Emit a new security token
    // -------------------------------------------------------

    // TODO : Improve communication mechanism between STS and IDP!
    // Queue this contenxt and send the artifact as RST context information
    Artifact emitterCtxArtifact = aqm.pushMessage(securityTokenEmissionCtx);

    SecurityTokenService sts = ((SPChannel) channel).getSecurityTokenService();
    // Send artifact id as RST context information, similar to relay state.
    RequestSecurityTokenType rst = buildRequestSecurityToken(receivedClaims, emitterCtxArtifact.getContent());

    if (logger.isDebugEnabled())
        logger.debug("Requesting Security Token (RST) w/context " + rst.getContext());

    // Send request to STS
    RequestSecurityTokenResponseType rstrt = sts.requestSecurityToken(rst);

    if (logger.isDebugEnabled())
        logger.debug("Received Request Security Token Response (RSTR) w/context " + rstrt.getContext());

    // Recover emission context, to get Subject information
    securityTokenEmissionCtx = (SamlR2SecurityTokenEmissionContext) aqm
            .pullMessage(ArtifactImpl.newInstance(rstrt.getContext()));

    /// Obtain assertion from STS Response
    JAXBElement<RequestedSecurityTokenType> token = (JAXBElement<RequestedSecurityTokenType>) rstrt.getAny()
            .get(1);
    Subject subject = (Subject) rstrt.getAny().get(2); // Hard-coded subject position in response
    AssertionType assertion = (AssertionType) token.getValue().getAny();
    if (logger.isDebugEnabled())
        logger.debug("Generated SamlR2 Assertion " + assertion.getID());

    securityTokenEmissionCtx.setAssertion(assertion);
    securityTokenEmissionCtx.setSubject(subject);

    SSOUser ssoUser = null;
    Set<SimplePrincipal> p = subject.getPrincipals(SimplePrincipal.class);
    if (p != null && p.size() > 0) {
        // We have a simple princiapl, Look for an SSOUser instance
        SimplePrincipal user = p.iterator().next();
        SSOIdentityManager identityMgr = ((SPChannel) channel).getIdentityManager();
        if (identityMgr != null)
            ssoUser = identityMgr.findUser(user.getName());

    } else {
        Set<SSOUser> ssoUsers = subject.getPrincipals(SSOUser.class);
        if (ssoUsers != null && ssoUsers.size() > 0) {
            // We already have an SSOUser instance
            ssoUser = ssoUsers.iterator().next();
        }
    }

    if (ssoUser != null) {
        // Make some validations on the SSO user
        for (SSONameValuePair nvp : ssoUser.getProperties()) {
            if (nvp.getName().equalsIgnoreCase("accountDisabled")) {
                boolean disabled = Boolean.parseBoolean(nvp.getValue());
                if (disabled) {
                    throw new SecurityTokenAuthenticationFailure("Account disabled");
                }
            }
        }
    }

    // Return context with Assertion and Subject
    return securityTokenEmissionCtx;

}

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  w ww  .j a  v a 2 s.  c  om

    // ------------------------------------------------------
    // 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.atricore.idbus.capabilities.sso.main.idp.producers.SingleSignOnProducer.java

protected IdPSecurityContext createSecurityContext(CamelMediationExchange exchange, Subject authnSubject,
        AssertionType assertion, ClaimSet claims) throws Exception {

    // -------------------------------------------------------
    // Create the SSO Session, using authnStatusment as security token
    // -------------------------------------------------------
    // The security token must store the AuthnStatmenet only, the rest of the assertion must be generated per request.
    AuthnStatementType authnStmt = null;
    for (StatementAbstractType stmt : assertion.getStatementOrAuthnStatementOrAuthzDecisionStatement()) {
        if (stmt instanceof AuthnStatementType) {
            authnStmt = (AuthnStatementType) stmt;
            break;
        }/*w w  w . jav  a 2s  .c om*/
    }

    if (authnStmt == null)
        throw new SSOException("Assertion MUST contain an AuthnStatement");

    // Create session security token, use the sesionIndex as token ID
    SecurityToken<AuthnStatementType> st = new SecurityTokenImpl<AuthnStatementType>(
            authnStmt.getSessionIndex(), authnStmt);

    // Get SSO User information (stored as simple principal!)
    Principal userId = authnSubject.getPrincipals(SimplePrincipal.class).iterator().next();

    if (logger.isDebugEnabled())
        logger.debug("Using username : " + userId.getName());

    // Initiate SSO Session
    String ssoSessionId = ((SPChannel) channel).getSessionManager().initiateSession(userId.getName(), st);
    assert ssoSessionId.equals(st.getId()) : "SSO Session Manager MUST use security token ID as session ID";

    boolean rememberMe = false;
    if (claims != null) {
        for (Claim c : claims.getClaims()) {
            if (c instanceof CredentialClaim) {
                CredentialClaim cc = (CredentialClaim) c;
                if (cc.getValue() instanceof UsernameTokenType) {
                    UsernameTokenType ut = (UsernameTokenType) cc.getValue();
                    String rememberMeStr = ut.getOtherAttributes().get(new QName(Constants.REMEMBERME_NS));
                    if (rememberMeStr != null)
                        rememberMe = Boolean.parseBoolean(rememberMeStr);
                }
            }
        }
    }

    if (rememberMe) {

        if (logger.isDebugEnabled())
            logger.debug("Creating remember-me security contenxt information");

        String preAuthnTokenId = null;

        for (StatementAbstractType stmt : assertion.getStatementOrAuthnStatementOrAuthzDecisionStatement()) {
            if (stmt instanceof AttributeStatementType) {
                AttributeStatementType attrStmt = (AttributeStatementType) stmt;
                for (Object o : attrStmt.getAttributeOrEncryptedAttribute()) {
                    // TODO : What if assertion is encrypted ?! (improve!)
                    if (o instanceof AttributeType) {
                        AttributeType attr = (AttributeType) o;
                        if (attr.getName().equals(WSTConstants.WST_OAUTH2_TOKEN_TYPE + "_ID")) {
                            preAuthnTokenId = (String) attr.getAttributeValue().get(0);
                        }
                    }
                }
            }
        }

        if (preAuthnTokenId != null) {
            String varName = getProvider().getStateManager().getNamespace().toUpperCase() + "_"
                    + getProvider().getName().toUpperCase() + "_RM";

            if (logger.isDebugEnabled())
                logger.debug("Creating remote variable (" + varName + ") with token id " + preAuthnTokenId);

            CamelMediationMessage in = (CamelMediationMessage) exchange.getIn();
            MediationState state = in.getMessage().getState();
            state.setRemoteVariable(varName, preAuthnTokenId,
                    System.currentTimeMillis() + (1000L * 60L * 60L * 24L * 30L)); // TODO : Configure!
        }
    }

    return new IdPSecurityContext(authnSubject, ssoSessionId, authnStmt);
}