Search in sources :

Example 36 with UsernameToken

use of org.apache.wss4j.dom.message.token.UsernameToken in project cxf by apache.

the class STSLoginModule method login.

@Override
public boolean login() throws LoginException {
    // Get username and password
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username: ");
    callbacks[1] = new PasswordCallback("Password: ", false);
    try {
        callbackHandler.handle(callbacks);
    } catch (IOException ioException) {
        throw new LoginException(ioException.getMessage());
    } catch (UnsupportedCallbackException unsupportedCallbackException) {
        throw new LoginException(unsupportedCallbackException.getMessage() + " not available to obtain information from user.");
    }
    String user = ((NameCallback) callbacks[0]).getName();
    char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
    if (tmpPassword == null) {
        tmpPassword = new char[0];
    }
    String password = new String(tmpPassword);
    roles = new HashSet<>();
    userPrincipal = null;
    STSTokenValidator validator = new STSTokenValidator(true);
    validator.setUseIssueBinding(requireRoles);
    validator.setUseOnBehalfOf(!disableOnBehalfOf);
    validator.setDisableCaching(!requireRoles || disableCaching);
    // Authenticate token
    try {
        UsernameToken token = convertToToken(user, password);
        Credential credential = new Credential();
        credential.setUsernametoken(token);
        RequestData data = new RequestData();
        Message message = PhaseInterceptorChain.getCurrentMessage();
        STSClient stsClient = configureSTSClient(message);
        if (message != null) {
            message.put(SecurityConstants.STS_CLIENT, stsClient);
            data.setMsgContext(message);
        } else {
            validator.setStsClient(stsClient);
        }
        credential = validator.validate(credential, data);
        // Add user principal
        userPrincipal = new SimplePrincipal(user);
        // Add roles if a SAML Assertion was returned from the STS
        roles.addAll(getRoles(message, credential));
    } catch (Exception e) {
        LOG.log(Level.INFO, "User " + user + " authentication failed", e);
        throw new LoginException("User " + user + " authentication failed: " + e.getMessage());
    }
    succeeded = true;
    return true;
}
Also used : Credential(org.apache.wss4j.dom.validate.Credential) Message(org.apache.cxf.message.Message) UsernameToken(org.apache.wss4j.dom.message.token.UsernameToken) IOException(java.io.IOException) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) BusException(org.apache.cxf.BusException) IOException(java.io.IOException) EndpointException(org.apache.cxf.endpoint.EndpointException) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) RequestData(org.apache.wss4j.dom.handler.RequestData) PasswordCallback(javax.security.auth.callback.PasswordCallback) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) SimplePrincipal(org.apache.cxf.common.security.SimplePrincipal)

Example 37 with UsernameToken

use of org.apache.wss4j.dom.message.token.UsernameToken in project cxf by apache.

the class WSS4JBasicAuthValidator method convertPolicyToToken.

protected UsernameToken convertPolicyToToken(AuthorizationPolicy policy) {
    Document doc = DOMUtils.getEmptyDocument();
    UsernameToken token = new UsernameToken(false, doc, WSS4JConstants.PASSWORD_TEXT);
    token.setName(policy.getUserName());
    token.setPassword(policy.getPassword());
    return token;
}
Also used : UsernameToken(org.apache.wss4j.dom.message.token.UsernameToken) Document(org.w3c.dom.Document)

Example 38 with UsernameToken

use of org.apache.wss4j.dom.message.token.UsernameToken in project cxf by apache.

the class WSS4JBasicAuthValidator method validate.

protected void validate(Message message) throws WSSecurityException {
    AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
    if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
        String name = null;
        if (policy != null) {
            name = policy.getUserName();
        }
        String errorMsg = "No user name and/or password is available, name: " + name;
        LOG.warning(errorMsg);
        throw new SecurityException(errorMsg);
    }
    UsernameToken token = convertPolicyToToken(policy);
    Credential credential = new Credential();
    credential.setUsernametoken(token);
    RequestData data = new RequestData();
    data.setMsgContext(message);
    data.setCallbackHandler(callbackHandler);
    credential = getValidator().validate(credential, data);
    // Create a Principal/SecurityContext
    final SecurityContext sc;
    if (credential != null && credential.getPrincipal() != null) {
        sc = createSecurityContext(message, credential);
    } else {
        Principal p = new WSUsernameTokenPrincipalImpl(policy.getUserName(), false);
        ((WSUsernameTokenPrincipalImpl) p).setPassword(policy.getPassword());
        sc = createSecurityContext(p);
    }
    message.put(SecurityContext.class, sc);
}
Also used : AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) Credential(org.apache.wss4j.dom.validate.Credential) RequestData(org.apache.wss4j.dom.handler.RequestData) UsernameToken(org.apache.wss4j.dom.message.token.UsernameToken) SAMLSecurityContext(org.apache.cxf.rt.security.saml.claims.SAMLSecurityContext) SecurityContext(org.apache.cxf.security.SecurityContext) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Principal(java.security.Principal) WSUsernameTokenPrincipalImpl(org.apache.wss4j.common.principal.WSUsernameTokenPrincipalImpl)

Example 39 with UsernameToken

use of org.apache.wss4j.dom.message.token.UsernameToken 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
    final Element usernameTokenElement;
    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 40 with UsernameToken

use of org.apache.wss4j.dom.message.token.UsernameToken in project cxf by apache.

the class UsernameTokenValidatorTest method testValidUsernameTokenDigest.

/**
 * Test a valid UsernameToken with password digest
 */
@org.junit.Test
public void testValidUsernameTokenDigest() throws Exception {
    TokenValidator usernameTokenValidator = new UsernameTokenValidator();
    TokenValidatorParameters validatorParameters = createValidatorParameters();
    TokenRequirements tokenRequirements = validatorParameters.getTokenRequirements();
    // Create a ValidateTarget consisting of a UsernameToken
    UsernameTokenType usernameToken = new UsernameTokenType();
    AttributedString username = new AttributedString();
    username.setValue("alice");
    usernameToken.setUsername(username);
    JAXBElement<UsernameTokenType> tokenType = new JAXBElement<UsernameTokenType>(QNameConstants.USERNAME_TOKEN, UsernameTokenType.class, usernameToken);
    // Create a WSS4J UsernameToken
    Document doc = DOMUtils.createDocument();
    UsernameToken ut = new UsernameToken(true, doc, WSS4JConstants.PASSWORD_DIGEST);
    ut.setName("alice");
    ut.setPassword("clarinet");
    ut.addNonce(doc);
    ut.addCreated(true, doc);
    // Add a password
    PasswordString password = new PasswordString();
    password.setValue(ut.getPassword());
    password.setType(WSS4JConstants.PASSWORD_DIGEST);
    JAXBElement<PasswordString> passwordType = new JAXBElement<PasswordString>(QNameConstants.PASSWORD, PasswordString.class, password);
    usernameToken.getAny().add(passwordType);
    // Add a nonce
    EncodedString nonce = new EncodedString();
    nonce.setValue(ut.getNonce());
    nonce.setEncodingType(WSS4JConstants.SOAPMESSAGE_NS + "#Base64Binary");
    JAXBElement<EncodedString> nonceType = new JAXBElement<EncodedString>(QNameConstants.NONCE, EncodedString.class, nonce);
    usernameToken.getAny().add(nonceType);
    // Add Created value
    String created = ut.getCreated();
    Element createdElement = doc.createElementNS(WSS4JConstants.WSU_NS, "Created");
    createdElement.setAttributeNS(WSS4JConstants.XMLNS_NS, "xmlns", WSS4JConstants.WSU_NS);
    createdElement.setTextContent(created);
    usernameToken.getAny().add(createdElement);
    ReceivedToken validateTarget = new ReceivedToken(tokenType);
    tokenRequirements.setValidateTarget(validateTarget);
    validatorParameters.setToken(validateTarget);
    assertTrue(usernameTokenValidator.canHandleToken(validateTarget));
    TokenValidatorResponse validatorResponse = usernameTokenValidator.validateToken(validatorParameters);
    assertNotNull(validatorResponse);
    assertNotNull(validatorResponse.getToken());
    assertTrue(validatorResponse.getToken().getState() == STATE.VALID);
    Principal principal = validatorResponse.getPrincipal();
    assertTrue(principal != null && principal.getName() != null);
    // Expected failure on a bad password
    password.setValue("badpassword");
    validatorResponse = usernameTokenValidator.validateToken(validatorParameters);
    assertNotNull(validatorResponse);
    assertNotNull(validatorResponse.getToken());
    assertTrue(validatorResponse.getToken().getState() == STATE.INVALID);
}
Also used : UsernameTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.UsernameTokenType) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) UsernameToken(org.apache.wss4j.dom.message.token.UsernameToken) JAXBElement(javax.xml.bind.JAXBElement) AttributedString(org.apache.cxf.ws.security.sts.provider.model.secext.AttributedString) PasswordString(org.apache.cxf.ws.security.sts.provider.model.secext.PasswordString) EncodedString(org.apache.cxf.ws.security.sts.provider.model.secext.EncodedString) Document(org.w3c.dom.Document) PasswordString(org.apache.cxf.ws.security.sts.provider.model.secext.PasswordString) AttributedString(org.apache.cxf.ws.security.sts.provider.model.secext.AttributedString) TokenRequirements(org.apache.cxf.sts.request.TokenRequirements) EncodedString(org.apache.cxf.ws.security.sts.provider.model.secext.EncodedString) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) Principal(java.security.Principal)

Aggregations

UsernameToken (org.apache.wss4j.dom.message.token.UsernameToken)46 Document (org.w3c.dom.Document)32 Credential (org.apache.wss4j.dom.validate.Credential)16 RequestData (org.apache.wss4j.dom.handler.RequestData)15 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)12 Element (org.w3c.dom.Element)10 Principal (java.security.Principal)9 WSUsernameTokenPrincipalImpl (org.apache.wss4j.common.principal.WSUsernameTokenPrincipalImpl)5 Test (org.junit.Test)5 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)4 JAXBElement (javax.xml.bind.JAXBElement)4 AuthorizationPolicy (org.apache.cxf.configuration.security.AuthorizationPolicy)4 Message (org.apache.cxf.message.Message)4 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)4 UsernameTokenType (org.apache.cxf.ws.security.sts.provider.model.secext.UsernameTokenType)4 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)4 CustomTokenPrincipal (org.apache.wss4j.common.principal.CustomTokenPrincipal)4 CallbackHandler (javax.security.auth.callback.CallbackHandler)3 Fault (org.apache.cxf.interceptor.Fault)3 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)3