Search in sources :

Example 81 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.

the class DefaultJWTClaimsProvider method handleConditions.

protected void handleConditions(JWTClaimsProviderParameters jwtClaimsProviderParameters, JwtClaims claims) {
    TokenProviderParameters providerParameters = jwtClaimsProviderParameters.getProviderParameters();
    Instant currentDate = Instant.now();
    long currentTime = currentDate.getEpochSecond();
    // Set the defaults first
    claims.setIssuedAt(currentTime);
    claims.setNotBefore(currentTime);
    claims.setExpiryTime(currentTime + lifetime);
    Lifetime tokenLifetime = providerParameters.getTokenRequirements().getLifetime();
    if (lifetime > 0 && acceptClientLifetime && tokenLifetime != null && tokenLifetime.getCreated() != null && tokenLifetime.getExpires() != null) {
        final Instant creationTime;
        Instant expirationTime;
        try {
            creationTime = ZonedDateTime.parse(tokenLifetime.getCreated()).toInstant();
            expirationTime = ZonedDateTime.parse(tokenLifetime.getExpires()).toInstant();
        } catch (DateTimeParseException ex) {
            LOG.fine("Error in parsing Timestamp Created or Expiration Strings");
            throw new STSException("Error in parsing Timestamp Created or Expiration Strings", STSException.INVALID_TIME);
        }
        // Check to see if the created time is in the future
        Instant validCreation = Instant.now();
        if (futureTimeToLive > 0) {
            validCreation = validCreation.plusSeconds(futureTimeToLive);
        }
        if (creationTime.isAfter(validCreation)) {
            LOG.fine("The Created Time is too far in the future");
            throw new STSException("The Created Time is too far in the future", STSException.INVALID_TIME);
        }
        long requestedLifetime = Duration.between(creationTime, expirationTime).getSeconds();
        if (requestedLifetime > getMaxLifetime()) {
            StringBuilder sb = new StringBuilder();
            sb.append("Requested lifetime [").append(requestedLifetime);
            sb.append(" sec] exceed configured maximum lifetime [").append(getMaxLifetime());
            sb.append(" sec]");
            LOG.warning(sb.toString());
            if (isFailLifetimeExceedance()) {
                throw new STSException("Requested lifetime exceeds maximum lifetime", STSException.INVALID_TIME);
            }
            expirationTime = creationTime.plusSeconds(getMaxLifetime());
        }
        long creationTimeInSeconds = creationTime.getEpochSecond();
        claims.setIssuedAt(creationTimeInSeconds);
        claims.setNotBefore(creationTimeInSeconds);
        claims.setExpiryTime(expirationTime.getEpochSecond());
    }
}
Also used : DateTimeParseException(java.time.format.DateTimeParseException) Lifetime(org.apache.cxf.sts.request.Lifetime) Instant(java.time.Instant) STSException(org.apache.cxf.ws.security.sts.provider.STSException) TokenProviderParameters(org.apache.cxf.sts.token.provider.TokenProviderParameters)

Example 82 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.

the class DefaultSubjectProvider method getSubject.

/**
 * Get a SubjectBean object.
 */
public SubjectBean getSubject(SubjectProviderParameters subjectProviderParameters) {
    // 1. Get the principal
    Principal principal = getPrincipal(subjectProviderParameters);
    if (principal == null) {
        LOG.fine("Error in getting principal");
        throw new STSException("Error in getting principal", STSException.REQUEST_FAILED);
    }
    // 2. Create the SubjectBean using the principal
    SubjectBean subjectBean = createSubjectBean(principal, subjectProviderParameters);
    // 3. Create the KeyInfoBean and set it on the SubjectBean
    KeyInfoBean keyInfo = createKeyInfo(subjectProviderParameters);
    subjectBean.setKeyInfo(keyInfo);
    return subjectBean;
}
Also used : SubjectBean(org.apache.wss4j.common.saml.bean.SubjectBean) KeyInfoBean(org.apache.wss4j.common.saml.bean.KeyInfoBean) STSException(org.apache.cxf.ws.security.sts.provider.STSException) X500Principal(javax.security.auth.x500.X500Principal) KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) Principal(java.security.Principal) UsernameTokenPrincipal(org.apache.wss4j.common.principal.UsernameTokenPrincipal)

Example 83 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.

the class SCTProvider method createToken.

/**
 * Create a token given a TokenProviderParameters
 */
public TokenProviderResponse createToken(TokenProviderParameters tokenParameters) {
    TokenRequirements tokenRequirements = tokenParameters.getTokenRequirements();
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Handling token of type: " + tokenRequirements.getTokenType());
    }
    if (tokenParameters.getTokenStore() == null) {
        LOG.log(Level.FINE, "A cache must be configured to use the SCTProvider");
        throw new STSException("Can't serialize SCT", STSException.REQUEST_FAILED);
    }
    SymmetricKeyHandler keyHandler = new SymmetricKeyHandler(tokenParameters);
    keyHandler.createSymmetricKey();
    try {
        Document doc = DOMUtils.getEmptyDocument();
        SecurityContextToken sct = new SecurityContextToken(getWSCVersion(tokenRequirements.getTokenType()), doc);
        WSSConfig wssConfig = WSSConfig.getNewInstance();
        sct.setID(wssConfig.getIdAllocator().createId("sctId-", sct));
        TokenProviderResponse response = new TokenProviderResponse();
        response.setTokenId(sct.getIdentifier());
        if (returnEntropy) {
            response.setEntropy(keyHandler.getEntropyBytes());
        }
        long keySize = keyHandler.getKeySize();
        response.setKeySize(keySize);
        response.setComputedKey(keyHandler.isComputedKey());
        // putting the secret key into the cache
        Instant created = Instant.now();
        response.setCreated(created);
        Instant expires = null;
        if (lifetime > 0) {
            expires = created.plusSeconds(lifetime);
            response.setExpires(expires);
        }
        SecurityToken token = new SecurityToken(sct.getIdentifier(), created, expires);
        token.setSecret(keyHandler.getSecret());
        token.setPrincipal(tokenParameters.getPrincipal());
        Map<String, Object> props = token.getProperties();
        if (props == null) {
            props = new HashMap<>();
        }
        token.setProperties(props);
        if (tokenParameters.getRealm() != null) {
            props.put(STSConstants.TOKEN_REALM, tokenParameters.getRealm());
        }
        // Handle Renewing logic
        Renewing renewing = tokenParameters.getTokenRequirements().getRenewing();
        if (renewing != null) {
            props.put(STSConstants.TOKEN_RENEWING_ALLOW, String.valueOf(renewing.isAllowRenewing()));
            props.put(STSConstants.TOKEN_RENEWING_ALLOW_AFTER_EXPIRY, String.valueOf(renewing.isAllowRenewingAfterExpiry()));
        } else {
            props.put(STSConstants.TOKEN_RENEWING_ALLOW, "true");
            props.put(STSConstants.TOKEN_RENEWING_ALLOW_AFTER_EXPIRY, "false");
        }
        tokenParameters.getTokenStore().add(token);
        if (tokenParameters.isEncryptToken()) {
            Element el = TokenProviderUtils.encryptToken(sct.getElement(), response.getTokenId(), tokenParameters.getStsProperties(), tokenParameters.getEncryptionProperties(), tokenParameters.getKeyRequirements(), tokenParameters.getMessageContext());
            response.setToken(el);
        } else {
            response.setToken(sct.getElement());
        }
        // Create the references
        TokenReference attachedReference = new TokenReference();
        attachedReference.setIdentifier(sct.getID());
        attachedReference.setUseDirectReference(true);
        attachedReference.setWsseValueType(tokenRequirements.getTokenType());
        response.setAttachedReference(attachedReference);
        TokenReference unAttachedReference = new TokenReference();
        unAttachedReference.setIdentifier(sct.getIdentifier());
        unAttachedReference.setUseDirectReference(true);
        unAttachedReference.setWsseValueType(tokenRequirements.getTokenType());
        response.setUnattachedReference(unAttachedReference);
        LOG.fine("SecurityContextToken successfully created");
        return response;
    } catch (Exception e) {
        LOG.log(Level.WARNING, "", e);
        throw new STSException("Can't serialize SCT", e, STSException.REQUEST_FAILED);
    }
}
Also used : Renewing(org.apache.cxf.sts.request.Renewing) Instant(java.time.Instant) Element(org.w3c.dom.Element) STSException(org.apache.cxf.ws.security.sts.provider.STSException) Document(org.w3c.dom.Document) STSException(org.apache.cxf.ws.security.sts.provider.STSException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) TokenRequirements(org.apache.cxf.sts.request.TokenRequirements) SecurityContextToken(org.apache.wss4j.dom.message.token.SecurityContextToken) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig)

Example 84 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.

the class JWTTokenProvider method signToken.

private String signToken(JwtClaims claims, RealmProperties jwtRealm, STSPropertiesMBean stsProperties) throws Exception {
    if (signToken) {
        // Initialise signature objects with defaults of STSPropertiesMBean
        Crypto signatureCrypto = stsProperties.getSignatureCrypto();
        CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
        SignatureProperties signatureProperties = stsProperties.getSignatureProperties();
        String alias = stsProperties.getSignatureUsername();
        if (jwtRealm != null) {
            // callbackhandler and alias of STSPropertiesMBean is ignored
            if (jwtRealm.getSignatureCrypto() != null) {
                LOG.fine("SAMLRealm signature keystore used");
                signatureCrypto = jwtRealm.getSignatureCrypto();
                callbackHandler = jwtRealm.getCallbackHandler();
                alias = jwtRealm.getSignatureAlias();
            }
            // SignatureProperties can be defined independently of SignatureCrypto
            if (jwtRealm.getSignatureProperties() != null) {
                signatureProperties = jwtRealm.getSignatureProperties();
            }
        }
        // Get the signature algorithm to use - for now we don't allow the client to ask
        // for a particular signature algorithm, as with SAML
        String signatureAlgorithm = signatureProperties.getSignatureAlgorithm();
        try {
            SignatureAlgorithm.getAlgorithm(signatureAlgorithm);
        } catch (IllegalArgumentException ex) {
            signatureAlgorithm = SignatureAlgorithm.RS256.name();
        }
        // If alias not defined, get the default of the SignatureCrypto
        if ((alias == null || "".equals(alias)) && (signatureCrypto != null)) {
            alias = signatureCrypto.getDefaultX509Identifier();
            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("Signature alias is null so using default alias: " + alias);
            }
        }
        // Get the password
        String password = null;
        if (callbackHandler != null) {
            WSPasswordCallback[] cb = { new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE) };
            callbackHandler.handle(cb);
            password = cb[0].getPassword();
        }
        Properties signingProperties = new Properties();
        signingProperties.put(JoseConstants.RSSEC_SIGNATURE_ALGORITHM, signatureAlgorithm);
        if (alias != null) {
            signingProperties.put(JoseConstants.RSSEC_KEY_STORE_ALIAS, alias);
        }
        if (password != null) {
            signingProperties.put(JoseConstants.RSSEC_KEY_PSWD, password);
        } else {
            throw new STSException("Can't get the password", STSException.REQUEST_FAILED);
        }
        if (!(signatureCrypto instanceof Merlin)) {
            throw new STSException("Can't get the keystore", STSException.REQUEST_FAILED);
        }
        KeyStore keystore = ((Merlin) signatureCrypto).getKeyStore();
        signingProperties.put(JoseConstants.RSSEC_KEY_STORE, keystore);
        JwsHeaders jwsHeaders = new JwsHeaders(signingProperties);
        JwsJwtCompactProducer jws = new JwsJwtCompactProducer(jwsHeaders, claims);
        JwsSignatureProvider sigProvider = JwsUtils.loadSignatureProvider(signingProperties, jwsHeaders);
        return jws.signWith(sigProvider);
    }
    JwsHeaders jwsHeaders = new JwsHeaders(SignatureAlgorithm.NONE);
    JwsJwtCompactProducer jws = new JwsJwtCompactProducer(jwsHeaders, claims);
    return jws.getSignedEncodedJws();
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) STSException(org.apache.cxf.ws.security.sts.provider.STSException) EncryptionProperties(org.apache.cxf.sts.service.EncryptionProperties) SignatureProperties(org.apache.cxf.sts.SignatureProperties) Properties(java.util.Properties) RealmProperties(org.apache.cxf.sts.token.realm.RealmProperties) KeyStore(java.security.KeyStore) JwsHeaders(org.apache.cxf.rs.security.jose.jws.JwsHeaders) JwsJwtCompactProducer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactProducer) Crypto(org.apache.wss4j.common.crypto.Crypto) SignatureProperties(org.apache.cxf.sts.SignatureProperties) WSPasswordCallback(org.apache.wss4j.common.ext.WSPasswordCallback) Merlin(org.apache.wss4j.common.crypto.Merlin) JwsSignatureProvider(org.apache.cxf.rs.security.jose.jws.JwsSignatureProvider)

Example 85 with STSException

use of org.apache.cxf.ws.security.sts.provider.STSException in project cxf by apache.

the class JWTTokenProvider method createToken.

/**
 * Create a token given a TokenProviderParameters
 */
public TokenProviderResponse createToken(TokenProviderParameters tokenParameters) {
    // KeyRequirements keyRequirements = tokenParameters.getKeyRequirements();
    TokenRequirements tokenRequirements = tokenParameters.getTokenRequirements();
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Handling token of type: " + tokenRequirements.getTokenType());
    }
    String realm = tokenParameters.getRealm();
    RealmProperties jwtRealm = null;
    if (realm != null) {
        jwtRealm = realmMap.get(realm);
    }
    // Get the claims
    JWTClaimsProviderParameters jwtClaimsProviderParameters = new JWTClaimsProviderParameters();
    jwtClaimsProviderParameters.setProviderParameters(tokenParameters);
    if (jwtRealm != null) {
        jwtClaimsProviderParameters.setIssuer(jwtRealm.getIssuer());
    }
    JwtClaims claims = jwtClaimsProvider.getJwtClaims(jwtClaimsProviderParameters);
    try {
        String tokenData = signToken(claims, jwtRealm, tokenParameters.getStsProperties());
        if (tokenParameters.isEncryptToken()) {
            tokenData = encryptToken(tokenData, new JweHeaders(), tokenParameters.getStsProperties(), tokenParameters.getEncryptionProperties(), tokenParameters.getKeyRequirements());
        }
        TokenProviderResponse response = new TokenProviderResponse();
        response.setToken(tokenData);
        response.setTokenId(claims.getTokenId());
        if (claims.getIssuedAt() > 0) {
            response.setCreated(Instant.ofEpochMilli(claims.getIssuedAt() * 1000L));
        }
        if (claims.getExpiryTime() > 0) {
            Instant expires = Instant.ofEpochMilli(claims.getExpiryTime() * 1000L);
            response.setExpires(expires);
        }
        LOG.fine("JWT Token successfully created");
        return response;
    } catch (Exception e) {
        LOG.log(Level.WARNING, "", e);
        throw new STSException("Can't serialize JWT token", e, STSException.REQUEST_FAILED);
    }
}
Also used : TokenRequirements(org.apache.cxf.sts.request.TokenRequirements) JwtClaims(org.apache.cxf.rs.security.jose.jwt.JwtClaims) Instant(java.time.Instant) STSException(org.apache.cxf.ws.security.sts.provider.STSException) TokenProviderResponse(org.apache.cxf.sts.token.provider.TokenProviderResponse) RealmProperties(org.apache.cxf.sts.token.realm.RealmProperties) STSException(org.apache.cxf.ws.security.sts.provider.STSException) JweHeaders(org.apache.cxf.rs.security.jose.jwe.JweHeaders)

Aggregations

STSException (org.apache.cxf.ws.security.sts.provider.STSException)87 Element (org.w3c.dom.Element)33 Crypto (org.apache.wss4j.common.crypto.Crypto)31 JAXBElement (javax.xml.bind.JAXBElement)30 StaticSTSProperties (org.apache.cxf.sts.StaticSTSProperties)26 RequestSecurityTokenResponseType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType)26 RequestSecurityTokenType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType)26 WrappedMessageContext (org.apache.cxf.jaxws.context.WrappedMessageContext)25 MessageImpl (org.apache.cxf.message.MessageImpl)25 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)24 PasswordCallbackHandler (org.apache.cxf.sts.common.PasswordCallbackHandler)24 ServiceMBean (org.apache.cxf.sts.service.ServiceMBean)21 StaticService (org.apache.cxf.sts.service.StaticService)20 RequestSecurityTokenResponseCollectionType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseCollectionType)18 Document (org.w3c.dom.Document)18 Principal (java.security.Principal)14 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)14 EncryptionProperties (org.apache.cxf.sts.service.EncryptionProperties)14 TokenRequirements (org.apache.cxf.sts.request.TokenRequirements)13 SAMLTokenProvider (org.apache.cxf.sts.token.provider.SAMLTokenProvider)13