Search in sources :

Example 21 with TokenProviderResponse

use of org.apache.cxf.sts.token.provider.TokenProviderResponse in project tesb-rt-se by Talend.

the class UsernameTokenProvider method createToken.

public TokenProviderResponse createToken(TokenProviderParameters tokenParameters) {
    try {
        Document doc = DOMUtils.createDocument();
        Principal principal = tokenParameters.getPrincipal();
        String user = principal.getName();
        // Get the password
        WSPasswordCallback[] cb = { new WSPasswordCallback(user, WSPasswordCallback.USERNAME_TOKEN) };
        STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
        stsProperties.getCallbackHandler().handle(cb);
        String password = cb[0].getPassword();
        if (password == null || "".equals(password)) {
            throw new STSException("No password available", STSException.REQUEST_FAILED);
        }
        UsernameToken ut = new UsernameToken(true, doc, WSConstants.PASSWORD_TEXT);
        ut.setName(user);
        ut.setPassword(password);
        WSSConfig config = WSSConfig.getNewInstance();
        ut.setID(config.getIdAllocator().createId("UsernameToken-", ut));
        TokenProviderResponse response = new TokenProviderResponse();
        response.setToken(ut.getElement());
        response.setTokenId(ut.getID());
        return response;
    } catch (Exception e) {
        e.printStackTrace();
        throw new STSException("Error creating UsernameToken", e, STSException.REQUEST_FAILED);
    }
}
Also used : STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) UsernameToken(org.apache.wss4j.dom.message.token.UsernameToken) STSException(org.apache.cxf.ws.security.sts.provider.STSException) TokenProviderResponse(org.apache.cxf.sts.token.provider.TokenProviderResponse) Document(org.w3c.dom.Document) WSPasswordCallback(org.apache.wss4j.common.ext.WSPasswordCallback) Principal(java.security.Principal) STSException(org.apache.cxf.ws.security.sts.provider.STSException)

Example 22 with TokenProviderResponse

use of org.apache.cxf.sts.token.provider.TokenProviderResponse 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 23 with TokenProviderResponse

use of org.apache.cxf.sts.token.provider.TokenProviderResponse 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 && realmMap.containsKey(realm)) {
        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));
        }
        Instant expires = null;
        if (claims.getExpiryTime() > 0) {
            expires = Instant.ofEpochMilli(claims.getExpiryTime() * 1000L);
            response.setExpires(expires);
        }
        // set the token in cache (only if the token is signed)
        if (signToken && tokenParameters.getTokenStore() != null) {
            SecurityToken securityToken = CacheUtils.createSecurityTokenForStorage(null, claims.getTokenId(), expires, tokenParameters.getPrincipal(), tokenParameters.getRealm(), tokenParameters.getTokenRequirements().getRenewing());
            securityToken.setData(tokenData.getBytes());
            String signature = tokenData.substring(tokenData.lastIndexOf(".") + 1);
            CacheUtils.storeTokenInCache(securityToken, tokenParameters.getTokenStore(), signature.getBytes());
        }
        LOG.fine("JWT Token successfully created");
        return response;
    } catch (Exception e) {
        e.printStackTrace();
        LOG.log(Level.WARNING, "", e);
        throw new STSException("Can't serialize JWT token", e, STSException.REQUEST_FAILED);
    }
}
Also used : SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) 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)

Example 24 with TokenProviderResponse

use of org.apache.cxf.sts.token.provider.TokenProviderResponse in project cxf by apache.

the class DummyTokenProvider method createToken.

public TokenProviderResponse createToken(TokenProviderParameters tokenParameters) {
    try {
        Document doc = DOMUtils.getEmptyDocument();
        // Mock up a dummy BinarySecurityToken
        String id = "BST-1234";
        BinarySecurity bst = new BinarySecurity(doc);
        bst.addWSSENamespace();
        bst.addWSUNamespace();
        bst.setID(id);
        bst.setValueType(TOKEN_TYPE);
        bst.setEncodingType(BASE64_NS);
        bst.setToken("12345678".getBytes());
        TokenProviderResponse response = new TokenProviderResponse();
        response.setToken(bst.getElement());
        response.setTokenId(id);
        if (tokenParameters.isEncryptToken()) {
            Element el = TokenProviderUtils.encryptToken(bst.getElement(), response.getTokenId(), tokenParameters.getStsProperties(), tokenParameters.getEncryptionProperties(), tokenParameters.getKeyRequirements(), tokenParameters.getMessageContext());
            response.setToken(el);
        } else {
            response.setToken(bst.getElement());
        }
        return response;
    } catch (Exception e) {
        throw new STSException("Can't serialize SAML assertion", e, STSException.REQUEST_FAILED);
    }
}
Also used : BinarySecurity(org.apache.wss4j.common.token.BinarySecurity) Element(org.w3c.dom.Element) STSException(org.apache.cxf.ws.security.sts.provider.STSException) TokenProviderResponse(org.apache.cxf.sts.token.provider.TokenProviderResponse) Document(org.w3c.dom.Document) STSException(org.apache.cxf.ws.security.sts.provider.STSException)

Example 25 with TokenProviderResponse

use of org.apache.cxf.sts.token.provider.TokenProviderResponse in project cxf by apache.

the class IssueJWTClaimsUnitTest method createSAMLAssertion.

/*
     * Mock up an SAML assertion element
     */
private Element createSAMLAssertion(String tokenType, Crypto crypto, String signatureUsername, CallbackHandler callbackHandler, Map<String, RealmProperties> realms) throws WSSecurityException {
    SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider();
    samlTokenProvider.setRealmMap(realms);
    List<AttributeStatementProvider> customProviderList = new ArrayList<>();
    customProviderList.add(new ClaimsAttributeStatementProvider());
    samlTokenProvider.setAttributeStatementProviders(customProviderList);
    TokenProviderParameters providerParameters = createProviderParameters(tokenType, STSConstants.BEARER_KEY_KEYTYPE, crypto, signatureUsername, callbackHandler);
    if (realms != null) {
        providerParameters.setRealm("A");
    }
    // Set the ClaimsManager
    ClaimsManager claimsManager = new ClaimsManager();
    ClaimsHandler claimsHandler = new CustomClaimsHandler();
    claimsManager.setClaimHandlers(Collections.singletonList(claimsHandler));
    providerParameters.setClaimsManager(claimsManager);
    ClaimCollection requestedClaims = new ClaimCollection();
    Claim requestClaim = new Claim();
    requestClaim.setClaimType(ClaimTypes.LASTNAME);
    requestClaim.setOptional(false);
    requestedClaims.add(requestClaim);
    providerParameters.setRequestedSecondaryClaims(requestedClaims);
    TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
    assertTrue(providerResponse != null);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);
    return (Element) providerResponse.getToken();
}
Also used : ClaimsAttributeStatementProvider(org.apache.cxf.sts.claims.ClaimsAttributeStatementProvider) ClaimsHandler(org.apache.cxf.sts.claims.ClaimsHandler) CustomClaimsHandler(org.apache.cxf.sts.common.CustomClaimsHandler) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) ClaimsAttributeStatementProvider(org.apache.cxf.sts.claims.ClaimsAttributeStatementProvider) AttributeStatementProvider(org.apache.cxf.sts.token.provider.AttributeStatementProvider) CustomClaimsHandler(org.apache.cxf.sts.common.CustomClaimsHandler) TokenProviderParameters(org.apache.cxf.sts.token.provider.TokenProviderParameters) SAMLTokenProvider(org.apache.cxf.sts.token.provider.SAMLTokenProvider) ClaimsManager(org.apache.cxf.sts.claims.ClaimsManager) TokenProviderResponse(org.apache.cxf.sts.token.provider.TokenProviderResponse) ClaimCollection(org.apache.cxf.rt.security.claims.ClaimCollection) Claim(org.apache.cxf.rt.security.claims.Claim)

Aggregations

TokenProviderResponse (org.apache.cxf.sts.token.provider.TokenProviderResponse)51 TokenProviderParameters (org.apache.cxf.sts.token.provider.TokenProviderParameters)35 Element (org.w3c.dom.Element)31 SAMLTokenProvider (org.apache.cxf.sts.token.provider.SAMLTokenProvider)25 TokenProvider (org.apache.cxf.sts.token.provider.TokenProvider)22 JAXBElement (javax.xml.bind.JAXBElement)14 TokenRequirements (org.apache.cxf.sts.request.TokenRequirements)14 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)13 JWTTokenProvider (org.apache.cxf.sts.token.provider.jwt.JWTTokenProvider)12 JWTTokenValidator (org.apache.cxf.sts.token.validator.jwt.JWTTokenValidator)11 Principal (java.security.Principal)10 ArrayList (java.util.ArrayList)10 STSException (org.apache.cxf.ws.security.sts.provider.STSException)10 CustomTokenPrincipal (org.apache.wss4j.common.principal.CustomTokenPrincipal)9 Instant (java.time.Instant)7 PasswordCallbackHandler (org.apache.cxf.sts.common.PasswordCallbackHandler)7 RequestSecurityTokenResponseType (org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType)7 Document (org.w3c.dom.Document)7 Claim (org.apache.cxf.rt.security.claims.Claim)6 ClaimCollection (org.apache.cxf.rt.security.claims.ClaimCollection)6