Search in sources :

Example 81 with ReceivedToken

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

the class SCTValidator method validateToken.

/**
 * Validate a Token using the given TokenValidatorParameters.
 */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOG.fine("Validating SecurityContextToken");
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    if (tokenParameters.getTokenStore() == null) {
        LOG.log(Level.FINE, "A cache must be configured to use the SCTValidator");
        return response;
    }
    if (validateTarget.isDOMElement()) {
        try {
            Element validateTargetElement = (Element) validateTarget.getToken();
            SecurityContextToken sct = new SecurityContextToken(validateTargetElement);
            String identifier = sct.getIdentifier();
            SecurityToken token = tokenParameters.getTokenStore().getToken(identifier);
            if (token == null) {
                LOG.fine("Identifier: " + identifier + " is not found in the cache");
                return response;
            }
            if (token.isExpired()) {
                validateTarget.setState(STATE.EXPIRED);
                LOG.fine("Token: " + identifier + " is in the cache but expired");
                return response;
            }
            byte[] secret = token.getSecret();
            Map<String, Object> properties = new HashMap<>(1);
            properties.put(SCT_VALIDATOR_SECRET, secret);
            response.setAdditionalProperties(properties);
            response.setPrincipal(token.getPrincipal());
            Map<String, Object> props = token.getProperties();
            if (props != null) {
                String realm = (String) props.get(STSConstants.TOKEN_REALM);
                response.setTokenRealm(realm);
            }
            validateTarget.setState(STATE.VALID);
            LOG.fine("SecurityContextToken successfully validated");
        } catch (WSSecurityException ex) {
            LOG.log(Level.WARNING, "", ex);
        }
    }
    return response;
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) SecurityContextToken(org.apache.wss4j.dom.message.token.SecurityContextToken) HashMap(java.util.HashMap) Element(org.w3c.dom.Element) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken)

Example 82 with ReceivedToken

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

the class UsernameTokenValidator method validateToken.

/**
 * Validate a Token using the given TokenValidatorParameters.
 */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOG.fine("Validating UsernameToken");
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
    Crypto sigCrypto = stsProperties.getSignatureCrypto();
    CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    requestData.setWssConfig(wssConfig);
    requestData.setCallbackHandler(callbackHandler);
    requestData.setMsgContext(tokenParameters.getMessageContext());
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    if (!validateTarget.isUsernameToken()) {
        return response;
    }
    // 
    // Turn the JAXB UsernameTokenType into a DOM Element for validation
    // 
    UsernameTokenType usernameTokenType = (UsernameTokenType) validateTarget.getToken();
    // Marshall the received JAXB object into a DOM Element
    Element usernameTokenElement = null;
    try {
        Set<Class<?>> classes = new HashSet<>();
        classes.add(ObjectFactory.class);
        classes.add(org.apache.cxf.ws.security.sts.provider.model.wstrust14.ObjectFactory.class);
        CachedContextAndSchemas cache = JAXBContextCache.getCachedContextAndSchemas(classes, null, null, null, false);
        JAXBContext jaxbContext = cache.getContext();
        Marshaller marshaller = jaxbContext.createMarshaller();
        Document doc = DOMUtils.getEmptyDocument();
        Element rootElement = doc.createElement("root-element");
        JAXBElement<UsernameTokenType> tokenType = new JAXBElement<UsernameTokenType>(QNameConstants.USERNAME_TOKEN, UsernameTokenType.class, usernameTokenType);
        marshaller.marshal(tokenType, rootElement);
        usernameTokenElement = (Element) rootElement.getFirstChild();
    } catch (JAXBException ex) {
        LOG.log(Level.WARNING, "", ex);
        return response;
    }
    // 
    try {
        boolean allowNamespaceQualifiedPasswordTypes = requestData.isAllowNamespaceQualifiedPasswordTypes();
        UsernameToken ut = new UsernameToken(usernameTokenElement, allowNamespaceQualifiedPasswordTypes, new BSPEnforcer());
        // The parsed principal is set independent whether validation is successful or not
        response.setPrincipal(new CustomTokenPrincipal(ut.getName()));
        if (ut.getPassword() == null) {
            return response;
        }
        // See if the UsernameToken is stored in the cache
        int hash = ut.hashCode();
        SecurityToken secToken = null;
        if (tokenParameters.getTokenStore() != null) {
            secToken = tokenParameters.getTokenStore().getToken(Integer.toString(hash));
            if (secToken != null && (secToken.getTokenHash() != hash || secToken.isExpired())) {
                secToken = null;
            }
        }
        Principal principal = null;
        if (secToken == null) {
            Credential credential = new Credential();
            credential.setUsernametoken(ut);
            credential = validator.validate(credential, requestData);
            principal = credential.getPrincipal();
            if (credential.getSubject() != null && roleParser != null) {
                // Parse roles from the validated token
                Set<Principal> roles = roleParser.parseRolesFromSubject(principal, credential.getSubject());
                response.setRoles(roles);
            }
        }
        if (principal == null) {
            principal = createPrincipal(ut.getName(), ut.getPassword(), ut.getPasswordType(), ut.getNonce(), ut.getCreated());
        }
        // Get the realm of the UsernameToken
        String tokenRealm = null;
        if (usernameTokenRealmCodec != null) {
            tokenRealm = usernameTokenRealmCodec.getRealmFromToken(ut);
            // verify the realm against the cached token
            if (secToken != null) {
                Map<String, Object> props = secToken.getProperties();
                if (props != null) {
                    String cachedRealm = (String) props.get(STSConstants.TOKEN_REALM);
                    if (!tokenRealm.equals(cachedRealm)) {
                        return response;
                    }
                }
            }
        }
        // Store the successfully validated token in the cache
        if (tokenParameters.getTokenStore() != null && secToken == null) {
            secToken = new SecurityToken(ut.getID());
            secToken.setToken(ut.getElement());
            int hashCode = ut.hashCode();
            String identifier = Integer.toString(hashCode);
            secToken.setTokenHash(hashCode);
            tokenParameters.getTokenStore().add(identifier, secToken);
        }
        response.setPrincipal(principal);
        response.setTokenRealm(tokenRealm);
        validateTarget.setState(STATE.VALID);
        LOG.fine("Username Token successfully validated");
    } catch (WSSecurityException ex) {
        LOG.log(Level.WARNING, "", ex);
    }
    return response;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) UsernameToken(org.apache.wss4j.dom.message.token.UsernameToken) JAXBContext(javax.xml.bind.JAXBContext) Document(org.w3c.dom.Document) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) RequestData(org.apache.wss4j.dom.handler.RequestData) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) CachedContextAndSchemas(org.apache.cxf.common.jaxb.JAXBContextCache.CachedContextAndSchemas) HashSet(java.util.HashSet) Marshaller(javax.xml.bind.Marshaller) Credential(org.apache.wss4j.dom.validate.Credential) UsernameTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.UsernameTokenType) JAXBException(javax.xml.bind.JAXBException) BSPEnforcer(org.apache.wss4j.common.bsp.BSPEnforcer) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) JAXBElement(javax.xml.bind.JAXBElement) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) Principal(java.security.Principal)

Example 83 with ReceivedToken

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

the class DummyTokenValidator method validateToken.

public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    if (validateTarget != null && validateTarget.isBinarySecurityToken()) {
        BinarySecurityTokenType binarySecurity = (BinarySecurityTokenType) validateTarget.getToken();
        if ("12345678".equals(binarySecurity.getValue())) {
            validateTarget.setState(STATE.VALID);
        }
    }
    return response;
}
Also used : BinarySecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken)

Example 84 with ReceivedToken

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

the class SCTCancellerTest method testCancelToken.

/**
 * Get a (valid) SecurityContextToken and successfully cancel it.
 */
@org.junit.Test
public void testCancelToken() throws Exception {
    TokenCanceller sctCanceller = new SCTCanceller();
    sctCanceller.setVerifyProofOfPossession(false);
    TokenCancellerParameters cancellerParameters = createCancellerParameters();
    TokenRequirements tokenRequirements = cancellerParameters.getTokenRequirements();
    // Create a CancelTarget consisting of a SecurityContextToken
    TokenProviderResponse providerResponse = getSecurityContextToken();
    ReceivedToken cancelTarget = new ReceivedToken(providerResponse.getToken());
    tokenRequirements.setCancelTarget(cancelTarget);
    cancellerParameters.setToken(cancelTarget);
    assertTrue(sctCanceller.canHandleToken(cancelTarget));
    TokenCancellerResponse cancellerResponse = sctCanceller.cancelToken(cancellerParameters);
    assertTrue(cancellerResponse != null);
    assertTrue(cancellerResponse.getToken().getState() == STATE.CANCELLED);
    // Try to cancel the token again - this should fail
    cancellerResponse = sctCanceller.cancelToken(cancellerParameters);
    assertTrue(cancellerResponse != null);
    assertFalse(cancellerResponse.getToken().getState() == STATE.CANCELLED);
}
Also used : TokenRequirements(org.apache.cxf.sts.request.TokenRequirements) TokenProviderResponse(org.apache.cxf.sts.token.provider.TokenProviderResponse) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken)

Example 85 with ReceivedToken

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

the class SCTCancellerTest method testCancelInvalidToken.

/**
 * Try to cancel an invalid SecurityContextToken
 */
@org.junit.Test
public void testCancelInvalidToken() throws Exception {
    TokenCanceller sctCanceller = new SCTCanceller();
    sctCanceller.setVerifyProofOfPossession(false);
    TokenCancellerParameters cancellerParameters = createCancellerParameters();
    TokenRequirements tokenRequirements = cancellerParameters.getTokenRequirements();
    // Create a CancelTarget consisting of a SecurityContextToken
    Document doc = DOMUtils.getEmptyDocument();
    SecurityContextToken sct = new SecurityContextToken(doc);
    ReceivedToken cancelTarget = new ReceivedToken(sct.getElement());
    tokenRequirements.setCancelTarget(cancelTarget);
    cancellerParameters.setToken(cancelTarget);
    assertTrue(sctCanceller.canHandleToken(cancelTarget));
    TokenCancellerResponse cancellerResponse = sctCanceller.cancelToken(cancellerParameters);
    assertTrue(cancellerResponse != null);
    assertFalse(cancellerResponse.getToken().getState() == STATE.CANCELLED);
}
Also used : TokenRequirements(org.apache.cxf.sts.request.TokenRequirements) SecurityContextToken(org.apache.wss4j.dom.message.token.SecurityContextToken) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) Document(org.w3c.dom.Document)

Aggregations

ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)115 Crypto (org.apache.wss4j.common.crypto.Crypto)59 TokenRequirements (org.apache.cxf.sts.request.TokenRequirements)55 Element (org.w3c.dom.Element)44 CallbackHandler (javax.security.auth.callback.CallbackHandler)42 TokenValidatorResponse (org.apache.cxf.sts.token.validator.TokenValidatorResponse)42 PasswordCallbackHandler (org.apache.cxf.sts.common.PasswordCallbackHandler)38 Document (org.w3c.dom.Document)37 CustomTokenPrincipal (org.apache.wss4j.common.principal.CustomTokenPrincipal)35 TokenValidatorParameters (org.apache.cxf.sts.token.validator.TokenValidatorParameters)32 BinarySecurityTokenType (org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType)26 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)25 Test (org.junit.Test)25 Principal (java.security.Principal)24 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)22 STSException (org.apache.cxf.ws.security.sts.provider.STSException)19 TokenProviderParameters (org.apache.cxf.sts.token.provider.TokenProviderParameters)13 TokenProviderResponse (org.apache.cxf.sts.token.provider.TokenProviderResponse)13 TokenValidator (org.apache.cxf.sts.token.validator.TokenValidator)13 RequestData (org.apache.wss4j.dom.handler.RequestData)13