Search in sources :

Example 56 with TokenRequirements

use of org.apache.cxf.sts.request.TokenRequirements in project cxf by apache.

the class TokenCancelOperation method cancel.

public RequestSecurityTokenResponseType cancel(RequestSecurityTokenType request, Principal principal, Map<String, Object> messageContext) {
    long start = System.currentTimeMillis();
    TokenCancellerParameters cancellerParameters = new TokenCancellerParameters();
    try {
        RequestRequirements requestRequirements = parseRequest(request, messageContext);
        KeyRequirements keyRequirements = requestRequirements.getKeyRequirements();
        TokenRequirements tokenRequirements = requestRequirements.getTokenRequirements();
        cancellerParameters.setStsProperties(stsProperties);
        cancellerParameters.setPrincipal(principal);
        cancellerParameters.setMessageContext(messageContext);
        cancellerParameters.setTokenStore(getTokenStore());
        cancellerParameters.setKeyRequirements(keyRequirements);
        cancellerParameters.setTokenRequirements(tokenRequirements);
        ReceivedToken cancelTarget = tokenRequirements.getCancelTarget();
        if (cancelTarget == null || cancelTarget.getToken() == null) {
            throw new STSException("No element presented for cancellation", STSException.INVALID_REQUEST);
        }
        cancellerParameters.setToken(cancelTarget);
        if (tokenRequirements.getTokenType() == null) {
            tokenRequirements.setTokenType(STSConstants.STATUS);
            LOG.fine("Received TokenType is null, falling back to default token type: " + STSConstants.STATUS);
        }
        // 
        // Cancel token
        // 
        TokenCancellerResponse tokenResponse = null;
        for (TokenCanceller tokenCanceller : tokencancellers) {
            if (tokenCanceller.canHandleToken(cancelTarget)) {
                try {
                    tokenResponse = tokenCanceller.cancelToken(cancellerParameters);
                } catch (RuntimeException ex) {
                    LOG.log(Level.WARNING, "", ex);
                    throw new STSException("Error while cancelling a token", ex, STSException.REQUEST_FAILED);
                }
                break;
            }
        }
        if (tokenResponse == null || tokenResponse.getToken() == null) {
            LOG.fine("No Token Canceller has been found that can handle this token");
            throw new STSException("No token canceller found for requested token type: " + tokenRequirements.getTokenType(), STSException.REQUEST_FAILED);
        }
        if (tokenResponse.getToken().getState() != STATE.CANCELLED) {
            LOG.log(Level.WARNING, "Token cancellation failed.");
            throw new STSException("Token cancellation failed.");
        }
        // prepare response
        try {
            RequestSecurityTokenResponseType response = createResponse(tokenRequirements);
            STSCancelSuccessEvent event = new STSCancelSuccessEvent(cancellerParameters, 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) {
        STSCancelFailureEvent event = new STSCancelFailureEvent(cancellerParameters, System.currentTimeMillis() - start, ex);
        publishEvent(event);
        throw ex;
    }
}
Also used : TokenCancellerParameters(org.apache.cxf.sts.token.canceller.TokenCancellerParameters) 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) STSCancelSuccessEvent(org.apache.cxf.sts.event.STSCancelSuccessEvent) TokenCancellerResponse(org.apache.cxf.sts.token.canceller.TokenCancellerResponse) STSCancelFailureEvent(org.apache.cxf.sts.event.STSCancelFailureEvent) TokenRequirements(org.apache.cxf.sts.request.TokenRequirements) KeyRequirements(org.apache.cxf.sts.request.KeyRequirements) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) TokenCanceller(org.apache.cxf.sts.token.canceller.TokenCanceller)

Example 57 with TokenRequirements

use of org.apache.cxf.sts.request.TokenRequirements in project cxf by apache.

the class TokenIssueOperation method issueSingle.

public RequestSecurityTokenResponseType issueSingle(RequestSecurityTokenType request, Principal principal, Map<String, Object> messageContext) {
    long start = System.currentTimeMillis();
    TokenProviderParameters providerParameters = new TokenProviderParameters();
    try {
        RequestRequirements requestRequirements = parseRequest(request, messageContext);
        providerParameters = createTokenProviderParameters(requestRequirements, principal, messageContext);
        providerParameters.setClaimsManager(claimsManager);
        String realm = providerParameters.getRealm();
        TokenRequirements tokenRequirements = requestRequirements.getTokenRequirements();
        String tokenType = tokenRequirements.getTokenType();
        if (stsProperties.getSamlRealmCodec() != null) {
            SamlAssertionWrapper assertion = fetchSAMLAssertionFromWSSecuritySAMLToken(messageContext);
            if (assertion != null) {
                String wssecRealm = stsProperties.getSamlRealmCodec().getRealmFromToken(assertion);
                SAMLTokenPrincipal samlPrincipal = new SAMLTokenPrincipalImpl(assertion);
                if (LOG.isLoggable(Level.FINE)) {
                    LOG.fine("SAML token realm of user '" + samlPrincipal.getName() + "' is " + wssecRealm);
                }
                ReceivedToken wssecToken = new ReceivedToken(assertion.getElement());
                wssecToken.setState(STATE.VALID);
                TokenValidatorResponse tokenResponse = new TokenValidatorResponse();
                tokenResponse.setPrincipal(samlPrincipal);
                tokenResponse.setToken(wssecToken);
                tokenResponse.setTokenRealm(wssecRealm);
                tokenResponse.setAdditionalProperties(new HashMap<String, Object>());
                processValidToken(providerParameters, wssecToken, tokenResponse);
                providerParameters.setPrincipal(wssecToken.getPrincipal());
            }
        }
        // Validate OnBehalfOf token if present
        if (providerParameters.getTokenRequirements().getOnBehalfOf() != null) {
            ReceivedToken validateTarget = providerParameters.getTokenRequirements().getOnBehalfOf();
            handleDelegationToken(validateTarget, providerParameters, principal, messageContext, realm, requestRequirements);
        }
        // See whether ActAs is allowed or not
        if (providerParameters.getTokenRequirements().getActAs() != null) {
            ReceivedToken validateTarget = providerParameters.getTokenRequirements().getActAs();
            handleDelegationToken(validateTarget, providerParameters, principal, messageContext, realm, requestRequirements);
        }
        // create token
        TokenProviderResponse tokenResponse = null;
        for (TokenProvider tokenProvider : tokenProviders) {
            boolean canHandle = false;
            if (realm == null) {
                canHandle = tokenProvider.canHandleToken(tokenType);
            } else {
                canHandle = tokenProvider.canHandleToken(tokenType, realm);
            }
            if (canHandle) {
                try {
                    tokenResponse = 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 (tokenResponse == null || tokenResponse.getToken() == null) {
            LOG.log(Level.WARNING, "No token provider found for requested token type: " + tokenType);
            throw new STSException("No token provider found for requested token type: " + tokenType, STSException.REQUEST_FAILED);
        }
        // prepare response
        try {
            KeyRequirements keyRequirements = requestRequirements.getKeyRequirements();
            EncryptionProperties encryptionProperties = providerParameters.getEncryptionProperties();
            RequestSecurityTokenResponseType response = createResponse(encryptionProperties, tokenResponse, tokenRequirements, keyRequirements);
            STSIssueSuccessEvent event = new STSIssueSuccessEvent(providerParameters, 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) {
        LOG.log(Level.SEVERE, "Cannot issue token: " + ex.getMessage(), ex);
        STSIssueFailureEvent event = new STSIssueFailureEvent(providerParameters, System.currentTimeMillis() - start, ex);
        publishEvent(event);
        throw ex;
    }
}
Also used : SAMLTokenPrincipal(org.apache.wss4j.common.principal.SAMLTokenPrincipal) RequestRequirements(org.apache.cxf.sts.request.RequestRequirements) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) STSException(org.apache.cxf.ws.security.sts.provider.STSException) EncryptionProperties(org.apache.cxf.sts.service.EncryptionProperties) RequestSecurityTokenResponseType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType) TokenProviderParameters(org.apache.cxf.sts.token.provider.TokenProviderParameters) 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) KeyRequirements(org.apache.cxf.sts.request.KeyRequirements) SAMLTokenPrincipalImpl(org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl) STSIssueSuccessEvent(org.apache.cxf.sts.event.STSIssueSuccessEvent) STSIssueFailureEvent(org.apache.cxf.sts.event.STSIssueFailureEvent)

Example 58 with TokenRequirements

use of org.apache.cxf.sts.request.TokenRequirements in project cxf by apache.

the class ActAsAttributeStatementProvider method getStatement.

/**
 * Get an AttributeStatementBean using the given parameters.
 */
public AttributeStatementBean getStatement(TokenProviderParameters providerParameters) {
    AttributeStatementBean attrBean = new AttributeStatementBean();
    TokenRequirements tokenRequirements = providerParameters.getTokenRequirements();
    ReceivedToken actAs = tokenRequirements.getActAs();
    try {
        if (actAs != null) {
            List<AttributeBean> attributeList = new ArrayList<>();
            String tokenType = tokenRequirements.getTokenType();
            AttributeBean parameterBean = handleAdditionalParameters(actAs.getToken(), tokenType);
            if (!parameterBean.getAttributeValues().isEmpty()) {
                attributeList.add(parameterBean);
            }
            attrBean.setSamlAttributes(attributeList);
        }
    } catch (WSSecurityException ex) {
        throw new STSException(ex.getMessage(), ex);
    }
    return attrBean;
}
Also used : AttributeStatementBean(org.apache.wss4j.common.saml.bean.AttributeStatementBean) TokenRequirements(org.apache.cxf.sts.request.TokenRequirements) ArrayList(java.util.ArrayList) STSException(org.apache.cxf.ws.security.sts.provider.STSException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) AttributeBean(org.apache.wss4j.common.saml.bean.AttributeBean)

Example 59 with TokenRequirements

use of org.apache.cxf.sts.request.TokenRequirements in project cxf by apache.

the class DefaultSubjectProvider method createSubjectBean.

/**
 * Create the SubjectBean using the specified principal.
 */
protected SubjectBean createSubjectBean(Principal principal, SubjectProviderParameters subjectProviderParameters) {
    TokenProviderParameters providerParameters = subjectProviderParameters.getProviderParameters();
    TokenRequirements tokenRequirements = providerParameters.getTokenRequirements();
    KeyRequirements keyRequirements = providerParameters.getKeyRequirements();
    String tokenType = tokenRequirements.getTokenType();
    String keyType = keyRequirements.getKeyType();
    String confirmationMethod = getSubjectConfirmationMethod(tokenType, keyType);
    String subjectName = principal.getName();
    String localSubjectNameIDFormat = subjectNameIDFormat;
    if (SAML2Constants.NAMEID_FORMAT_UNSPECIFIED.equals(localSubjectNameIDFormat) && principal instanceof X500Principal) {
        // Just use the "cn" instead of the entire DN
        try {
            LdapName ln = new LdapName(principal.getName());
            for (Rdn rdn : ln.getRdns()) {
                if ("CN".equalsIgnoreCase(rdn.getType()) && (rdn.getValue() instanceof String)) {
                    subjectName = (String) rdn.getValue();
                    break;
                }
            }
        } catch (Throwable ex) {
            subjectName = principal.getName();
        // Ignore, not X500 compliant thus use the whole string as the value
        }
    } else if (!SAML2Constants.NAMEID_FORMAT_UNSPECIFIED.equals(localSubjectNameIDFormat)) {
        /* Set subjectNameIDFormat correctly based on type of principal
                unless already set to some value other than unspecified */
        if (principal instanceof UsernameTokenPrincipal) {
            localSubjectNameIDFormat = SAML2Constants.NAMEID_FORMAT_PERSISTENT;
        } else if (principal instanceof X500Principal) {
            localSubjectNameIDFormat = SAML2Constants.NAMEID_FORMAT_X509_SUBJECT_NAME;
        } else if (principal instanceof KerberosPrincipal) {
            localSubjectNameIDFormat = SAML2Constants.NAMEID_FORMAT_KERBEROS;
        } else if (localSubjectNameIDFormat == null) {
            localSubjectNameIDFormat = SAML2Constants.NAMEID_FORMAT_UNSPECIFIED;
        }
    }
    SubjectBean subjectBean = new SubjectBean(subjectName, subjectNameQualifier, confirmationMethod);
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Creating new subject with principal name: " + principal.getName());
    }
    subjectBean.setSubjectNameIDFormat(localSubjectNameIDFormat);
    return subjectBean;
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) SubjectBean(org.apache.wss4j.common.saml.bean.SubjectBean) TokenRequirements(org.apache.cxf.sts.request.TokenRequirements) UsernameTokenPrincipal(org.apache.wss4j.common.principal.UsernameTokenPrincipal) X500Principal(javax.security.auth.x500.X500Principal) KeyRequirements(org.apache.cxf.sts.request.KeyRequirements) Rdn(javax.naming.ldap.Rdn) LdapName(javax.naming.ldap.LdapName)

Example 60 with TokenRequirements

use of org.apache.cxf.sts.request.TokenRequirements 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)

Aggregations

TokenRequirements (org.apache.cxf.sts.request.TokenRequirements)116 CustomTokenPrincipal (org.apache.wss4j.common.principal.CustomTokenPrincipal)79 Crypto (org.apache.wss4j.common.crypto.Crypto)67 PasswordCallbackHandler (org.apache.cxf.sts.common.PasswordCallbackHandler)65 KeyRequirements (org.apache.cxf.sts.request.KeyRequirements)63 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)55 WrappedMessageContext (org.apache.cxf.jaxws.context.WrappedMessageContext)54 MessageImpl (org.apache.cxf.message.MessageImpl)54 StaticSTSProperties (org.apache.cxf.sts.StaticSTSProperties)54 EncryptionProperties (org.apache.cxf.sts.service.EncryptionProperties)45 TokenProviderParameters (org.apache.cxf.sts.token.provider.TokenProviderParameters)39 Document (org.w3c.dom.Document)33 Element (org.w3c.dom.Element)31 CallbackHandler (javax.security.auth.callback.CallbackHandler)29 STSException (org.apache.cxf.ws.security.sts.provider.STSException)18 Principal (java.security.Principal)16 TokenValidatorParameters (org.apache.cxf.sts.token.validator.TokenValidatorParameters)16 TokenValidatorResponse (org.apache.cxf.sts.token.validator.TokenValidatorResponse)15 TokenProviderResponse (org.apache.cxf.sts.token.provider.TokenProviderResponse)14 TokenValidator (org.apache.cxf.sts.token.validator.TokenValidator)12