Search in sources :

Example 1 with TokenCreationException

use of org.forgerock.openam.sts.TokenCreationException in project OpenAM by OpenRock.

the class STSCryptoProviderBase method loadKeystore.

private KeyStore loadKeystore() throws TokenCreationException {
    InputStream inputStream;
    try {
        inputStream = getKeystoreInputStream();
    } catch (FileNotFoundException e) {
        throw new TokenCreationException(ResourceException.BAD_REQUEST, "Could not find keystore file at location " + keystoreLocation + " neither on the filesystem, nor on the classpath.");
    }
    KeyStore keyStore;
    try {
        keyStore = KeyStore.getInstance(keystoreType);
    } catch (KeyStoreException e) {
        throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "Could not get JKS keystore: " + e.getMessage(), e);
    }
    try {
        keyStore.load(inputStream, new String(keystorePassword, AMSTSConstants.UTF_8_CHARSET_ID).toCharArray());
        return keyStore;
    } catch (IOException | NoSuchAlgorithmException | CertificateException e) {
        throw new TokenCreationException(ResourceException.CONFLICT, "Could not load keystore at location " + keystoreLocation + ": " + e.getMessage(), e);
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) TokenCreationException(org.forgerock.openam.sts.TokenCreationException) KeyStore(java.security.KeyStore)

Example 2 with TokenCreationException

use of org.forgerock.openam.sts.TokenCreationException in project OpenAM by OpenRock.

the class DefaultOpenIdConnectTokenClaimMapper method getCustomClaims.

@Override
public Map<String, String> getCustomClaims(SSOToken token, Map<String, String> claimMap) throws TokenCreationException {
    try {
        final AMIdentity amIdentity = IdUtils.getIdentity(token);
        final HashSet<String> attributeNames = new HashSet<>(claimMap.size());
        attributeNames.addAll(claimMap.values());
        Map<String, String> joinedMappings = joinMultiValues(amIdentity.getAttributes(attributeNames));
        /*
             At this point, the key entries joinedMappings will be the attribute name, and the value will be the
             corresponding value pulled from the user data store. Because I need to return a Map where the keys are the
             claim names, as in the claimMap parameter, I need to create a new map, whose keys correspond to the
             keys in the claimMap parameter, and whose value correspond to the joinedMappings value.
             */
        Map<String, String> adjustedMap = new HashMap<>(joinedMappings.size());
        for (Map.Entry<String, String> claimMapEntry : claimMap.entrySet()) {
            if (!StringUtils.isEmpty(joinedMappings.get(claimMapEntry.getValue()))) {
                adjustedMap.put(claimMapEntry.getKey(), joinedMappings.get(claimMapEntry.getValue()));
            }
        }
        return adjustedMap;
    } catch (IdRepoException | SSOException e) {
        throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "Exception encountered in claim attribute lookup: " + e, e);
    }
}
Also used : HashMap(java.util.HashMap) AMIdentity(com.sun.identity.idm.AMIdentity) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException) HashMap(java.util.HashMap) Map(java.util.Map) TokenCreationException(org.forgerock.openam.sts.TokenCreationException) HashSet(java.util.HashSet)

Example 3 with TokenCreationException

use of org.forgerock.openam.sts.TokenCreationException in project OpenAM by OpenRock.

the class OpenIdConnectTokenGenerationImpl method generate.

@Override
public String generate(SSOToken subjectToken, STSInstanceState stsInstanceState, TokenGenerationServiceInvocationState invocationState) throws TokenCreationException {
    final OpenIdConnectTokenConfig tokenConfig = stsInstanceState.getConfig().getOpenIdConnectTokenConfig();
    final long issueInstant = System.currentTimeMillis();
    final String subject = ssoTokenIdentity.validateAndGetTokenPrincipal(subjectToken);
    STSOpenIdConnectToken openIdConnectToken = buildToken(subjectToken, tokenConfig, invocationState.getOpenIdConnectTokenGenerationState(), issueInstant / 1000, subject);
    final JwsAlgorithm jwsAlgorithm = tokenConfig.getSignatureAlgorithm();
    final JwsAlgorithmType jwsAlgorithmType = jwsAlgorithm.getAlgorithmType();
    String tokenString;
    if (JwsAlgorithmType.HMAC.equals(jwsAlgorithmType)) {
        final SignedJwt signedJwt = symmetricSign(openIdConnectToken, jwsAlgorithm, tokenConfig.getClientSecret());
        tokenString = signedJwt.build();
    } else if (JwsAlgorithmType.RSA.equals(jwsAlgorithmType)) {
        final SignedJwt signedJwt = asymmetricSign(openIdConnectToken, jwsAlgorithm, getKeyPair(stsInstanceState.getOpenIdConnectTokenPKIProvider(), tokenConfig.getSignatureKeyAlias(), tokenConfig.getSignatureKeyPassword()), determinePublicKeyReferenceType(tokenConfig));
        tokenString = signedJwt.build();
    } else {
        throw new TokenCreationException(ResourceException.BAD_REQUEST, "Unknown JwsAlgorithmType: " + jwsAlgorithmType);
    }
    if (stsInstanceState.getConfig().persistIssuedTokensInCTS()) {
        try {
            ctsTokenPersistence.persistToken(invocationState.getStsInstanceId(), TokenType.OPENIDCONNECT, tokenString, subject, issueInstant, tokenConfig.getTokenLifetimeInSeconds());
        } catch (CTSTokenPersistenceException e) {
            throw new TokenCreationException(e.getCode(), e.getMessage(), e);
        }
    }
    return tokenString;
}
Also used : JwsAlgorithm(org.forgerock.json.jose.jws.JwsAlgorithm) JwsAlgorithmType(org.forgerock.json.jose.jws.JwsAlgorithmType) SignedJwt(org.forgerock.json.jose.jws.SignedJwt) TokenCreationException(org.forgerock.openam.sts.TokenCreationException) CTSTokenPersistenceException(org.forgerock.openam.sts.CTSTokenPersistenceException) OpenIdConnectTokenConfig(org.forgerock.openam.sts.config.user.OpenIdConnectTokenConfig)

Example 4 with TokenCreationException

use of org.forgerock.openam.sts.TokenCreationException 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 5 with TokenCreationException

use of org.forgerock.openam.sts.TokenCreationException in project OpenAM by OpenRock.

the class TokenGenerationService method createInstance.

@Override
public Promise<ResourceResponse, ResourceException> createInstance(Context context, CreateRequest request) {
    TokenGenerationServiceInvocationState invocationState;
    try {
        invocationState = TokenGenerationServiceInvocationState.fromJson(request.getContent());
    } catch (Exception e) {
        logger.error("Exception caught marshalling json into TokenGenerationServiceInvocationState instance: " + e);
        return new BadRequestException(e.getMessage(), e).asPromise();
    }
    SSOToken subjectToken;
    try {
        subjectToken = validateAssertionSubjectSession(invocationState);
    } catch (ForbiddenException e) {
        return e.asPromise();
    }
    STSInstanceState stsInstanceState;
    try {
        stsInstanceState = getSTSInstanceState(invocationState);
    } catch (ResourceException e) {
        return e.asPromise();
    }
    if (TokenType.SAML2.equals(invocationState.getTokenType())) {
        try {
            final String assertion = saml2TokenGeneration.generate(subjectToken, stsInstanceState, invocationState);
            return newResultPromise(issuedTokenResource(assertion));
        } catch (TokenCreationException e) {
            logger.error("Exception caught generating saml2 token: " + e, e);
            return e.asPromise();
        } catch (Exception e) {
            logger.error("Exception caught generating saml2 token: " + e, e);
            return new InternalServerErrorException(e.toString(), e).asPromise();
        }
    } else if (TokenType.OPENIDCONNECT.equals(invocationState.getTokenType())) {
        try {
            final String assertion = openIdConnectTokenGeneration.generate(subjectToken, stsInstanceState, invocationState);
            return newResultPromise(issuedTokenResource(assertion));
        } catch (TokenCreationException e) {
            logger.error("Exception caught generating OpenIdConnect token: " + e, e);
            return e.asPromise();
        } catch (Exception e) {
            logger.error("Exception caught generating OpenIdConnect token: " + e, e);
            return new InternalServerErrorException(e.toString(), e).asPromise();
        }
    } else {
        String message = "Bad request: unexpected token type:" + invocationState.getTokenType();
        logger.error(message);
        return new BadRequestException(message).asPromise();
    }
}
Also used : TokenGenerationServiceInvocationState(org.forgerock.openam.sts.service.invocation.TokenGenerationServiceInvocationState) ForbiddenException(org.forgerock.json.resource.ForbiddenException) SSOToken(com.iplanet.sso.SSOToken) BadRequestException(org.forgerock.json.resource.BadRequestException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ResourceException(org.forgerock.json.resource.ResourceException) RestSTSInstanceState(org.forgerock.openam.sts.tokengeneration.state.RestSTSInstanceState) SoapSTSInstanceState(org.forgerock.openam.sts.tokengeneration.state.SoapSTSInstanceState) STSInstanceState(org.forgerock.openam.sts.tokengeneration.state.STSInstanceState) TokenCreationException(org.forgerock.openam.sts.TokenCreationException) CTSTokenPersistenceException(org.forgerock.openam.sts.CTSTokenPersistenceException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ForbiddenException(org.forgerock.json.resource.ForbiddenException) SSOException(com.iplanet.sso.SSOException) NotFoundException(org.forgerock.json.resource.NotFoundException) BadRequestException(org.forgerock.json.resource.BadRequestException) IdRepoException(com.sun.identity.idm.IdRepoException) TokenCreationException(org.forgerock.openam.sts.TokenCreationException) ResourceException(org.forgerock.json.resource.ResourceException) STSPublishException(org.forgerock.openam.sts.STSPublishException)

Aggregations

TokenCreationException (org.forgerock.openam.sts.TokenCreationException)23 SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)12 ArrayList (java.util.ArrayList)6 Date (java.util.Date)4 IOException (java.io.IOException)3 ResourceException (org.forgerock.json.resource.ResourceException)3 CTSTokenPersistenceException (org.forgerock.openam.sts.CTSTokenPersistenceException)3 Element (org.w3c.dom.Element)3 SSOException (com.iplanet.sso.SSOException)2 IdRepoException (com.sun.identity.idm.IdRepoException)2 Attribute (com.sun.identity.saml2.assertion.Attribute)2 AttributeStatement (com.sun.identity.saml2.assertion.AttributeStatement)2 NameID (com.sun.identity.saml2.assertion.NameID)2 Subject (com.sun.identity.saml2.assertion.Subject)2 SubjectConfirmationData (com.sun.identity.saml2.assertion.SubjectConfirmationData)2 HashMap (java.util.HashMap)2 TokenProviderResponse (org.apache.cxf.sts.token.provider.TokenProviderResponse)2 JwsHeaderBuilder (org.forgerock.json.jose.builders.JwsHeaderBuilder)2 SigningManager (org.forgerock.json.jose.jws.SigningManager)2 SigningHandler (org.forgerock.json.jose.jws.handlers.SigningHandler)2