Search in sources :

Example 1 with TokenProviderResponse

use of org.apache.cxf.sts.token.provider.TokenProviderResponse in project OpenAM by OpenRock.

the class SoapSamlTokenProvider method createToken.

/**
     * @see org.apache.cxf.sts.token.provider.TokenProvider
     */
@Override
public TokenProviderResponse createToken(TokenProviderParameters tokenProviderParameters) {
    try {
        final TokenProviderResponse tokenProviderResponse = new TokenProviderResponse();
        final SAML2SubjectConfirmation subjectConfirmation = determineSubjectConfirmation(tokenProviderParameters);
        final SoapTokenProviderBase.AuthenticationContextMapperState mapperState = getAuthenticationContextMapperState(tokenProviderParameters);
        String authNContextClassRef;
        if (mapperState.isDelegatedContext()) {
            authNContextClassRef = authnContextMapper.getAuthnContextForDelegatedToken(mapperState.getSecurityPolicyBindingTraversalYield(), mapperState.getDelegatedToken());
        } else {
            authNContextClassRef = authnContextMapper.getAuthnContext(mapperState.getSecurityPolicyBindingTraversalYield());
        }
        ProofTokenState proofTokenState = null;
        if (SAML2SubjectConfirmation.HOLDER_OF_KEY.equals(subjectConfirmation)) {
            proofTokenState = getProofTokenState(tokenProviderParameters);
        }
        String assertion;
        try {
            assertion = getAssertion(authNContextClassRef, subjectConfirmation, proofTokenState);
        } catch (TokenCreationException e) {
            throw new AMSTSRuntimeException(e.getCode(), e.getMessage(), e);
        }
        Document assertionDocument = xmlUtilities.stringToDocumentConversion(assertion);
        if (assertionDocument == null) {
            logger.error("Could not turn assertion string returned from TokenGenerationService into DOM Document. " + "The assertion string: " + assertion);
            throw new AMSTSRuntimeException(ResourceException.INTERNAL_ERROR, "Could not turn assertion string returned from TokenGenerationService into DOM Document.");
        }
        final Element assertionElement = assertionDocument.getDocumentElement();
        tokenProviderResponse.setToken(assertionElement);
        final String tokenId = assertionElement.getAttributeNS(null, "ID");
        /*
            The tokenId cannot be null or empty because a reference to the issued token is created using this id in the wss
            security header in the RequestSecurityTokenResponse. A null or empty id will generate a cryptic error in the cxf
            runtime. And if we are dealing with an encrypted assertion, there is no ID attribute, so in this case,
            a random uuid should be generated, as I believe the id serves only to refer to the token within the
            security header, and does not have to be connected to the token itself. An encrypted SAML2 assertion only
            contains some information on the encryption method, the symmetric key used for encryption, itself encrypted
            with the recipient's public key, and the encrypted assertion. So if no ID attribute is present, we are dealing
            with an encrypted assertion, and will generate a random UUID to serve as the key id.
            */
        if (StringUtils.isEmpty(tokenId)) {
            tokenProviderResponse.setTokenId(UUID.randomUUID().toString());
        } else {
            tokenProviderResponse.setTokenId(tokenId);
        }
        return tokenProviderResponse;
    } finally {
        try {
            amSessionInvalidator.invalidateAMSessions(threadLocalAMTokenCache.getToBeInvalidatedAMSessionIds());
        } catch (Exception e) {
            String message = "Exception caught invalidating interim AMSession in SoapSamlTokenProvider: " + e;
            logger.warn(message, e);
        /*
                The fact that the interim OpenAM session was not invalidated should not prevent a token from being issued, so
                I will not throw a AMSTSRuntimeException
                */
        }
    }
}
Also used : SAML2SubjectConfirmation(org.forgerock.openam.sts.token.SAML2SubjectConfirmation) Element(org.w3c.dom.Element) AMSTSRuntimeException(org.forgerock.openam.sts.AMSTSRuntimeException) TokenProviderResponse(org.apache.cxf.sts.token.provider.TokenProviderResponse) SoapTokenProviderBase(org.forgerock.openam.sts.soap.token.provider.SoapTokenProviderBase) ProofTokenState(org.forgerock.openam.sts.user.invocation.ProofTokenState) Document(org.w3c.dom.Document) TokenCreationException(org.forgerock.openam.sts.TokenCreationException) AMSTSRuntimeException(org.forgerock.openam.sts.AMSTSRuntimeException) TokenMarshalException(org.forgerock.openam.sts.TokenMarshalException) ResourceException(org.forgerock.json.resource.ResourceException) TokenCreationException(org.forgerock.openam.sts.TokenCreationException)

Example 2 with TokenProviderResponse

use of org.apache.cxf.sts.token.provider.TokenProviderResponse in project OpenAM by OpenRock.

the class SoapOpenIdConnectTokenProvider method createToken.

@Override
public TokenProviderResponse createToken(TokenProviderParameters tokenProviderParameters) {
    try {
        final TokenProviderResponse tokenProviderResponse = new TokenProviderResponse();
        final SoapTokenProviderBase.AuthenticationContextMapperState mapperState = getAuthenticationContextMapperState(tokenProviderParameters);
        String authNContextClassRef;
        Set<String> authNMethodsReferences;
        final List<WSHandlerResult> securityPolicyBindingTraversalYield = mapperState.getSecurityPolicyBindingTraversalYield();
        if (mapperState.isDelegatedContext()) {
            final ReceivedToken delegatedToken = mapperState.getDelegatedToken();
            authNContextClassRef = authnContextMapper.getAuthnContextForDelegatedToken(securityPolicyBindingTraversalYield, delegatedToken);
            authNMethodsReferences = methodsReferencesMapper.getAuthnMethodsReferencesForDelegatedToken(securityPolicyBindingTraversalYield, delegatedToken);
        } else {
            authNContextClassRef = authnContextMapper.getAuthnContext(securityPolicyBindingTraversalYield);
            authNMethodsReferences = methodsReferencesMapper.getAuthnMethodsReferences(securityPolicyBindingTraversalYield);
        }
        String token;
        try {
            token = getAssertion(getValidationInvocationContext(tokenProviderParameters), authNContextClassRef, authNMethodsReferences, System.currentTimeMillis() / 1000, NULL_NONCE);
            Element tokenElement = buildTokenElement(token);
            tokenProviderResponse.setToken(tokenElement);
            tokenProviderResponse.setTokenId(getTokenId(token));
            return tokenProviderResponse;
        } catch (TokenCreationException e) {
            throw new AMSTSRuntimeException(e.getCode(), e.getMessage(), e);
        }
    } finally {
        try {
            amSessionInvalidator.invalidateAMSessions(threadLocalAMTokenCache.getToBeInvalidatedAMSessionIds());
        } catch (Exception e) {
            String message = "Exception caught invalidating interim AMSession in SoapOpenIdConnectTokenProvider: " + e;
            logger.warn(message, e);
        /*
                The fact that the interim OpenAM session was not invalidated should not prevent a token from being issued, so
                I will not throw a AMSTSRuntimeException
                */
        }
    }
}
Also used : Element(org.w3c.dom.Element) AMSTSRuntimeException(org.forgerock.openam.sts.AMSTSRuntimeException) TokenProviderResponse(org.apache.cxf.sts.token.provider.TokenProviderResponse) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) SoapTokenProviderBase(org.forgerock.openam.sts.soap.token.provider.SoapTokenProviderBase) WSHandlerResult(org.apache.ws.security.handler.WSHandlerResult) TokenCreationException(org.forgerock.openam.sts.TokenCreationException) JwtReconstructionException(org.forgerock.json.jose.exceptions.JwtReconstructionException) TokenCreationException(org.forgerock.openam.sts.TokenCreationException) AMSTSRuntimeException(org.forgerock.openam.sts.AMSTSRuntimeException) JsonValueException(org.forgerock.json.JsonValueException) ResourceException(org.forgerock.json.resource.ResourceException)

Example 3 with TokenProviderResponse

use of org.apache.cxf.sts.token.provider.TokenProviderResponse in project cxf by apache.

the class TokenValidateOperation method validate.

public RequestSecurityTokenResponseType validate(RequestSecurityTokenType request, Principal principal, Map<String, Object> messageContext) {
    long start = System.currentTimeMillis();
    TokenValidatorParameters validatorParameters = new TokenValidatorParameters();
    try {
        RequestRequirements requestRequirements = parseRequest(request, messageContext);
        TokenRequirements tokenRequirements = requestRequirements.getTokenRequirements();
        validatorParameters.setStsProperties(stsProperties);
        validatorParameters.setPrincipal(principal);
        validatorParameters.setMessageContext(messageContext);
        validatorParameters.setTokenStore(getTokenStore());
        // validatorParameters.setKeyRequirements(keyRequirements);
        validatorParameters.setTokenRequirements(tokenRequirements);
        ReceivedToken validateTarget = tokenRequirements.getValidateTarget();
        if (validateTarget == null || validateTarget.getToken() == null) {
            throw new STSException("No element presented for validation", STSException.INVALID_REQUEST);
        }
        validatorParameters.setToken(validateTarget);
        if (tokenRequirements.getTokenType() == null) {
            tokenRequirements.setTokenType(STSConstants.STATUS);
            LOG.fine("Received TokenType is null, falling back to default token type: " + STSConstants.STATUS);
        }
        // Get the realm of the request
        String realm = null;
        if (stsProperties.getRealmParser() != null) {
            RealmParser realmParser = stsProperties.getRealmParser();
            realm = realmParser.parseRealm(messageContext);
        }
        validatorParameters.setRealm(realm);
        TokenValidatorResponse tokenResponse = validateReceivedToken(principal, messageContext, realm, tokenRequirements, validateTarget);
        if (tokenResponse == null) {
            LOG.fine("No Token Validator has been found that can handle this token");
            tokenResponse = new TokenValidatorResponse();
            validateTarget.setState(STATE.INVALID);
            tokenResponse.setToken(validateTarget);
        }
        // 
        // Create a new token (if requested)
        // 
        TokenProviderResponse tokenProviderResponse = null;
        String tokenType = tokenRequirements.getTokenType();
        if (tokenResponse.getToken().getState() == STATE.VALID && !STSConstants.STATUS.equals(tokenType)) {
            TokenProviderParameters providerParameters = createTokenProviderParameters(requestRequirements, principal, messageContext);
            processValidToken(providerParameters, validateTarget, tokenResponse);
            // Check if the requested claims can be handled by the configured claim handlers
            providerParameters.setClaimsManager(claimsManager);
            Map<String, Object> additionalProperties = tokenResponse.getAdditionalProperties();
            if (additionalProperties != null) {
                providerParameters.setAdditionalProperties(additionalProperties);
            }
            realm = providerParameters.getRealm();
            for (TokenProvider tokenProvider : tokenProviders) {
                boolean canHandle = false;
                if (realm == null) {
                    canHandle = tokenProvider.canHandleToken(tokenType);
                } else {
                    canHandle = tokenProvider.canHandleToken(tokenType, realm);
                }
                if (canHandle) {
                    try {
                        tokenProviderResponse = tokenProvider.createToken(providerParameters);
                    } catch (STSException ex) {
                        LOG.log(Level.WARNING, "", ex);
                        throw ex;
                    } catch (RuntimeException ex) {
                        LOG.log(Level.WARNING, "", ex);
                        throw new STSException("Error in providing a token", ex, STSException.REQUEST_FAILED);
                    }
                    break;
                }
            }
            if (tokenProviderResponse == null || tokenProviderResponse.getToken() == null) {
                LOG.fine("No Token Provider has been found that can handle this token");
                throw new STSException("No token provider found for requested token type: " + tokenType, STSException.REQUEST_FAILED);
            }
        }
        // prepare response
        try {
            RequestSecurityTokenResponseType response = createResponse(tokenResponse, tokenProviderResponse, tokenRequirements);
            STSValidateSuccessEvent event = new STSValidateSuccessEvent(validatorParameters, System.currentTimeMillis() - start);
            publishEvent(event);
            return response;
        } catch (Throwable ex) {
            LOG.log(Level.WARNING, "", ex);
            throw new STSException("Error in creating the response", ex, STSException.REQUEST_FAILED);
        }
    } catch (RuntimeException ex) {
        STSValidateFailureEvent event = new STSValidateFailureEvent(validatorParameters, System.currentTimeMillis() - start, ex);
        publishEvent(event);
        throw ex;
    }
}
Also used : RequestRequirements(org.apache.cxf.sts.request.RequestRequirements) STSException(org.apache.cxf.ws.security.sts.provider.STSException) RequestSecurityTokenResponseType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType) TokenProviderParameters(org.apache.cxf.sts.token.provider.TokenProviderParameters) TokenValidatorParameters(org.apache.cxf.sts.token.validator.TokenValidatorParameters) RealmParser(org.apache.cxf.sts.RealmParser) TokenProvider(org.apache.cxf.sts.token.provider.TokenProvider) TokenRequirements(org.apache.cxf.sts.request.TokenRequirements) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) TokenProviderResponse(org.apache.cxf.sts.token.provider.TokenProviderResponse) STSValidateSuccessEvent(org.apache.cxf.sts.event.STSValidateSuccessEvent) STSValidateFailureEvent(org.apache.cxf.sts.event.STSValidateFailureEvent)

Example 4 with TokenProviderResponse

use of org.apache.cxf.sts.token.provider.TokenProviderResponse in project cxf by apache.

the class JexlIssueSamlClaimsTest method createSAMLAssertion.

/*
     * Mock up an SAML assertion element
     */
private Element createSAMLAssertion(String tokenType, Crypto crypto, String signatureUsername, CallbackHandler callbackHandler, Map<String, RealmProperties> realms) throws WSSecurityException {
    SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider();
    samlTokenProvider.setRealmMap(realms);
    List<AttributeStatementProvider> customProviderList = new ArrayList<>();
    customProviderList.add(new ClaimsAttributeStatementProvider());
    samlTokenProvider.setAttributeStatementProviders(customProviderList);
    TokenProviderParameters providerParameters = createProviderParameters(tokenType, STSConstants.BEARER_KEY_KEYTYPE, crypto, signatureUsername, callbackHandler);
    if (realms != null) {
        providerParameters.setRealm("A");
    }
    // Set the ClaimsManager
    ClaimsManager claimsManager = new ClaimsManager();
    ClaimsHandler claimsHandler = new CustomClaimsHandler();
    claimsManager.setClaimHandlers(Collections.singletonList(claimsHandler));
    providerParameters.setClaimsManager(claimsManager);
    ClaimCollection requestedClaims = new ClaimCollection();
    Claim requestClaim = new Claim();
    requestClaim.setClaimType(ClaimTypes.LASTNAME);
    requestClaim.setOptional(true);
    requestedClaims.add(requestClaim);
    requestClaim = new Claim();
    requestClaim.setClaimType(ROLE_CLAIM);
    requestClaim.addValue("admin");
    requestClaim.addValue("manager");
    requestClaim.addValue("user");
    requestClaim.setOptional(false);
    requestedClaims.add(requestClaim);
    requestClaim = new Claim();
    requestClaim.setClaimType(ClaimTypes.EMAILADDRESS);
    requestClaim.setOptional(false);
    requestedClaims.add(requestClaim);
    providerParameters.setRequestedSecondaryClaims(requestedClaims);
    TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
    assertTrue(providerResponse != null);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);
    return (Element) providerResponse.getToken();
}
Also used : ClaimsAttributeStatementProvider(org.apache.cxf.sts.claims.ClaimsAttributeStatementProvider) ClaimsHandler(org.apache.cxf.sts.claims.ClaimsHandler) CustomClaimsHandler(org.apache.cxf.sts.common.CustomClaimsHandler) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) ClaimsAttributeStatementProvider(org.apache.cxf.sts.claims.ClaimsAttributeStatementProvider) AttributeStatementProvider(org.apache.cxf.sts.token.provider.AttributeStatementProvider) CustomClaimsHandler(org.apache.cxf.sts.common.CustomClaimsHandler) TokenProviderParameters(org.apache.cxf.sts.token.provider.TokenProviderParameters) SAMLTokenProvider(org.apache.cxf.sts.token.provider.SAMLTokenProvider) ClaimsManager(org.apache.cxf.sts.claims.ClaimsManager) TokenProviderResponse(org.apache.cxf.sts.token.provider.TokenProviderResponse) ClaimCollection(org.apache.cxf.rt.security.claims.ClaimCollection) Claim(org.apache.cxf.rt.security.claims.Claim)

Example 5 with TokenProviderResponse

use of org.apache.cxf.sts.token.provider.TokenProviderResponse in project cxf by apache.

the class CancelSCTUnitTest method testCancelSCT.

/**
 * Test to successfully cancel a SecurityContextToken
 */
@org.junit.Test
public void testCancelSCT() throws Exception {
    TokenCancelOperation cancelOperation = new TokenCancelOperation();
    cancelOperation.setTokenStore(tokenStore);
    // Add Token Canceller
    List<TokenCanceller> cancellerList = new ArrayList<>();
    TokenCanceller sctCanceller = new SCTCanceller();
    sctCanceller.setVerifyProofOfPossession(false);
    cancellerList.add(sctCanceller);
    cancelOperation.setTokenCancellers(cancellerList);
    // Add STSProperties object
    STSPropertiesMBean stsProperties = new StaticSTSProperties();
    Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
    stsProperties.setEncryptionCrypto(crypto);
    stsProperties.setSignatureCrypto(crypto);
    stsProperties.setEncryptionUsername("myservicekey");
    stsProperties.setSignatureUsername("mystskey");
    stsProperties.setCallbackHandler(new PasswordCallbackHandler());
    stsProperties.setIssuer("STS");
    cancelOperation.setStsProperties(stsProperties);
    // Get a SecurityContextToken via the SCTProvider
    TokenProviderResponse providerResponse = createSCT();
    Element sct = (Element) providerResponse.getToken();
    CancelTargetType cancelTarget = new CancelTargetType();
    cancelTarget.setAny(sct);
    // Mock up a request
    JAXBElement<CancelTargetType> cancelTargetType = new JAXBElement<CancelTargetType>(QNameConstants.CANCEL_TARGET, CancelTargetType.class, cancelTarget);
    RequestSecurityTokenType request = new RequestSecurityTokenType();
    request.getAny().add(cancelTargetType);
    // Mock up message context
    MessageImpl msg = new MessageImpl();
    WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
    Principal principal = new CustomTokenPrincipal("alice");
    msgCtx.put(SecurityContext.class.getName(), createSecurityContext(principal));
    // Cancel a token
    RequestSecurityTokenResponseType response = cancelOperation.cancel(request, principal, msgCtx);
    assertTrue(validateResponse(response));
    // Now try to cancel again
    try {
        cancelOperation.cancel(request, principal, msgCtx);
    } catch (STSException ex) {
    // expected
    }
}
Also used : JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) RequestSecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType) ArrayList(java.util.ArrayList) CancelTargetType(org.apache.cxf.ws.security.sts.provider.model.CancelTargetType) STSException(org.apache.cxf.ws.security.sts.provider.STSException) RequestSecurityTokenResponseType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType) StaticSTSProperties(org.apache.cxf.sts.StaticSTSProperties) JAXBElement(javax.xml.bind.JAXBElement) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) WrappedMessageContext(org.apache.cxf.jaxws.context.WrappedMessageContext) SecurityContext(org.apache.cxf.security.SecurityContext) PasswordCallbackHandler(org.apache.cxf.sts.common.PasswordCallbackHandler) TokenProviderResponse(org.apache.cxf.sts.token.provider.TokenProviderResponse) SCTCanceller(org.apache.cxf.sts.token.canceller.SCTCanceller) MessageImpl(org.apache.cxf.message.MessageImpl) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) Principal(java.security.Principal) TokenCanceller(org.apache.cxf.sts.token.canceller.TokenCanceller)

Aggregations

TokenProviderResponse (org.apache.cxf.sts.token.provider.TokenProviderResponse)51 TokenProviderParameters (org.apache.cxf.sts.token.provider.TokenProviderParameters)35 Element (org.w3c.dom.Element)31 SAMLTokenProvider (org.apache.cxf.sts.token.provider.SAMLTokenProvider)25 TokenProvider (org.apache.cxf.sts.token.provider.TokenProvider)22 JAXBElement (javax.xml.bind.JAXBElement)14 TokenRequirements (org.apache.cxf.sts.request.TokenRequirements)14 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)13 JWTTokenProvider (org.apache.cxf.sts.token.provider.jwt.JWTTokenProvider)12 JWTTokenValidator (org.apache.cxf.sts.token.validator.jwt.JWTTokenValidator)11 Principal (java.security.Principal)10 ArrayList (java.util.ArrayList)10 STSException (org.apache.cxf.ws.security.sts.provider.STSException)10 CustomTokenPrincipal (org.apache.wss4j.common.principal.CustomTokenPrincipal)9 Instant (java.time.Instant)7 PasswordCallbackHandler (org.apache.cxf.sts.common.PasswordCallbackHandler)7 RequestSecurityTokenResponseType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType)7 Document (org.w3c.dom.Document)7 Claim (org.apache.cxf.rt.security.claims.Claim)6 ClaimCollection (org.apache.cxf.rt.security.claims.ClaimCollection)6