Package com.sun.xml.ws.security.trust.elements

Examples of com.sun.xml.ws.security.trust.elements.RequestSecurityToken


        this.wstVer = (WSTrustVersion)stsConfig.getOtherOptions().get(WSTrustConstants.WST_VERSION);
        this.eleFac = WSTrustElementFactory.newInstance(wstVer);
    }

    public BaseSTSResponse issue(BaseSTSRequest request, IssuedTokenContext context) throws WSTrustException {
        RequestSecurityToken rst = (RequestSecurityToken)request;
        SecondaryParameters secParas = null;
        context.getOtherProperties().put(IssuedTokenContext.WS_TRUST_VERSION, wstVer);
        if (wstVer.getNamespaceURI().equals(WSTrustVersion.WS_TRUST_13_NS_URI)){
            secParas = rst.getSecondaryParameters();
        }
       
       // Get token scope
        final AppliesTo applies = rst.getAppliesTo();
        String appliesTo = null;
        X509Certificate serCert = null;
        List<Object> at = null;
        if(applies != null){
            at = WSTrustUtil.parseAppliesTo(applies);
            for (int i = 0; i < at.size(); i++){
                Object obj = at.get(i);
                if (obj instanceof String){
                    appliesTo = (String)obj;
                }else if (obj instanceof X509Certificate){
                    serCert = (X509Certificate)obj;
                }
            }
        }
        context.setAppliesTo(appliesTo);
       
        // Get token issuer
        String issuer = stsConfig.getIssuer();
        context.setTokenIssuer(issuer);
       
        // Get the metadata for the SP as identified by the AppliesTo
        TrustSPMetadata spMd = stsConfig.getTrustSPMetadata(appliesTo);
        if (spMd == null){
            // Only used for testing purpose; default should not documented
            spMd = stsConfig.getTrustSPMetadata("default");
        }
        if (spMd == null){
            log.log(Level.SEVERE,
                    LogStringsMessages.WST_0004_UNKNOWN_SERVICEPROVIDER(appliesTo));
            throw new WSTrustException(LogStringsMessages.WST_0004_UNKNOWN_SERVICEPROVIDER(appliesTo));
        }
       
        // Get service certificate
        if (serCert == null){
            serCert = this.getServiceCertificate(spMd, appliesTo);
        }
        if (serCert != null){
            context.getOtherProperties().put(IssuedTokenContext.TARGET_SERVICE_CERTIFICATE, serCert);
        }
       
        // Get STS certificate and private key
        Object[] certAndKey = this.getSTSCertAndPrivateKey();
        context.getOtherProperties().put(IssuedTokenContext.STS_CERTIFICATE, (X509Certificate)certAndKey[0]);
        context.getOtherProperties().put(IssuedTokenContext.STS_PRIVATE_KEY, (PrivateKey)certAndKey[1]);
       
        // Get TokenType
        String tokenType = null;
        URI tokenTypeURI = rst.getTokenType();
        if (tokenTypeURI == null && secParas != null){
            tokenTypeURI = secParas.getTokenType();
        }
        if (tokenTypeURI != null){
            tokenType = tokenTypeURI.toString();
        }else{
            tokenType = spMd.getTokenType();
        }
        if (tokenType == null){
            tokenType = WSTrustConstants.SAML11_ASSERTION_TOKEN_TYPE;
        }
        context.setTokenType(tokenType);
       
        // Get KeyType
        String keyType = null;
        URI keyTypeURI = rst.getKeyType();
        if (keyTypeURI == null && secParas != null){
            keyTypeURI = secParas.getKeyType();
        }
        if (keyTypeURI != null){
            keyType = keyTypeURI.toString();
        }else{
            keyType = spMd.getKeyType();
        }
        if (keyType == null){
            keyType = wstVer.getSymmetricKeyTypeURI();
        }
        context.setKeyType(keyType);

        // Get crypto algorithms
        String encryptionAlgorithm = null;
        URI encryptionAlgorithmURI = rst.getEncryptionAlgorithm();
        if(encryptionAlgorithmURI == null && secParas != null){
            encryptionAlgorithmURI = secParas.getEncryptionAlgorithm();
        }
        if(encryptionAlgorithmURI != null){
            encryptionAlgorithm = encryptionAlgorithmURI.toString();
        }
        context.setEncryptionAlgorithm(encryptionAlgorithm);
       
        String signatureAlgorithm = null;
        URI signatureAlgorithmURI = rst.getSignatureAlgorithm();
        if(signatureAlgorithmURI == null && secParas != null){
            signatureAlgorithmURI = secParas.getSignatureAlgorithm();
        }
        if(signatureAlgorithmURI != null){
            signatureAlgorithm = signatureAlgorithmURI.toString();
        }
        context.setSignatureAlgorithm(signatureAlgorithm);
       
        String canonicalizationAlgorithm = null;
        URI canonicalizationAlgorithmURI = rst.getCanonicalizationAlgorithm();
        if(canonicalizationAlgorithmURI == null && secParas != null){
            canonicalizationAlgorithmURI = secParas.getCanonicalizationAlgorithm();
        }
        if(canonicalizationAlgorithmURI != null){
            canonicalizationAlgorithm = canonicalizationAlgorithmURI.toString();
        }
        context.setCanonicalizationAlgorithm(canonicalizationAlgorithm);
       
        // Get KeyWrap Algorithm, which is the part of WS-Trust wssx versaion
        URI keyWrapAlgorithmURI = null;       
        if(secParas != null){
            keyWrapAlgorithmURI = secParas.getKeyWrapAlgorithm();           
        }       
        if(keyWrapAlgorithmURI != null){
            context.getOtherProperties().put(IssuedTokenContext.KEY_WRAP_ALGORITHM, keyWrapAlgorithmURI.toString());
        }               
       
        // Get authenticaed client Subject
        Subject subject = context.getRequestorSubject();
        if (subject == null){
            AccessControlContext acc = AccessController.getContext();
            subject = Subject.getSubject(acc);
            context.setRequestorSubject(subject);
        }
        if(subject == null){
            log.log(Level.SEVERE,
                    LogStringsMessages.WST_0030_REQUESTOR_NULL());
            throw new WSTrustException(LogStringsMessages.WST_0030_REQUESTOR_NULL());
        }
       
        // Get client authentication context
        String authnCtx = (String)stsConfig.getOtherOptions().get(WSTrustConstants.AUTHN_CONTEXT_CLASS);
        if (authnCtx != null){
             context.getOtherProperties().put(IssuedTokenContext.AUTHN_CONTEXT, authnCtx);
        }

        // Get Claims from the RST
        Claims claims = rst.getClaims();
        if (claims == null && secParas != null){
            claims = secParas.getClaims();
        }
        if (claims != null){
            // Add supporting information
            List<Object> si = rst.getExtensionElements();
            claims.getSupportingProperties().addAll(si);
            if (at != null){
                claims.getSupportingProperties().addAll(at);
            }
        }else{
            claims = eleFac.createClaims();
        }

        String confirMethod = null;

        Element assertionInRST = (Element)stsConfig.getOtherOptions().get(WSTrustConstants.SAML_ASSERTION_ELEMENT_IN_RST);
        // Handle OnBehalfOf token
        OnBehalfOf obo = rst.getOnBehalfOf();
        if (obo != null){
            Object oboToken = obo.getAny();
            if (assertionInRST != null){
                oboToken = assertionInRST;
            }
            if (oboToken != null){
                subject.getPublicCredentials().add(eleFac.toElement(oboToken));

                 // set OnBehalfOf attribute
                claims.getOtherAttributes().put(new QName("OnBehalfOf"), "true");
                context.getOtherProperties().put("OnBehalfOf", "true");

                // Create a Subject with ActAs credential and put it in claims
                Subject oboSubj = new Subject();
                oboSubj.getPublicCredentials().add(eleFac.toElement(oboToken));
                claims.getSupportingProperties().add(oboSubj);
            }
        }
       
        // Handle ActAs token
        ActAs actAs = rst.getActAs();
        if (actAs != null){
            Object actAsToken = actAs.getAny();
            if (assertionInRST != null){
                actAsToken = assertionInRST;
            }
            if (actAsToken != null){
                // set ActAs attribute
                claims.getOtherAttributes().put(new QName("ActAs"), "true");
                context.getOtherProperties().put("ActAs", "true");

                // Create a Subject with ActAs credential and put it in claims
                Subject actAsSubj = new Subject();
                actAsSubj.getPublicCredentials().add(eleFac.toElement(actAsToken));
                claims.getSupportingProperties().add(actAsSubj);
            }
        }

        if (confirMethod != null){
            context.getOtherProperties().put(IssuedTokenContext.CONFIRMATION_METHOD, confirMethod);
        }

        // Check if the client is authorized to be issued the token from the STSAuthorizationProvider
        //ToDo: handling ActAs case
        final STSAuthorizationProvider authzProvider = WSTrustFactory.getSTSAuthorizationProvider();
        if (!authzProvider.isAuthorized(subject, appliesTo, tokenType, keyType)){
            String user = subject.getPrincipals().iterator().next().getName();
            log.log(Level.SEVERE,
                    LogStringsMessages.WST_0015_CLIENT_NOT_AUTHORIZED(
                    user, tokenType, appliesTo));
            throw new WSTrustException(LogStringsMessages.WST_0015_CLIENT_NOT_AUTHORIZED(
                    user, tokenType, appliesTo));
        }
       
        // Get claimed attributes from the STSAttributeProvider
        final STSAttributeProvider attrProvider = WSTrustFactory.getSTSAttributeProvider();
        final Map<QName, List<String>> claimedAttrs = attrProvider.getClaimedAttributes(subject, appliesTo, tokenType, claims);
        context.getOtherProperties().put(IssuedTokenContext.CLAIMED_ATTRUBUTES, claimedAttrs);
       
        //==========================================
        // Create proof key and RequestedProofToken
        //==========================================
          
        RequestedProofToken proofToken = null;
        Entropy serverEntropy = null;
        int keySize = 0;
        if (wstVer.getSymmetricKeyTypeURI().equals(keyType)){
            proofToken = eleFac.createRequestedProofToken();
             // Get client entropy
            byte[] clientEntr = null;
            final Entropy clientEntropy = rst.getEntropy();
            if (clientEntropy != null){
                final BinarySecret clientBS = clientEntropy.getBinarySecret();
                if (clientBS == null){
                    if(log.isLoggable(Level.FINE)) {
                        log.log(Level.FINE,
                                LogStringsMessages.WST_1009_NULL_BINARY_SECRET());
                    }
                }else {
                    clientEntr = clientBS.getRawValue();
                }
            }
           
            // Get KeySize
            keySize = (int)rst.getKeySize();
            if (keySize < 1 && secParas != null){
                keySize = (int) secParas.getKeySize();
            }
            if (keySize < 1){
                keySize = DEFAULT_KEY_SIZE;
            }
            if(log.isLoggable(Level.FINE)) {
                log.log(Level.FINE,
                        LogStringsMessages.WST_1010_KEY_SIZE(keySize, DEFAULT_KEY_SIZE));
            }
           
            byte[] key = WSTrustUtil.generateRandomSecret(keySize/8);
            final BinarySecret serverBS = eleFac.createBinarySecret(key, wstVer.getNonceBinarySecretTypeURI());
            serverEntropy = eleFac.createEntropy(serverBS);
           
            // compute the secret key
            try {
                if (clientEntr != null && clientEntr.length > 0){
                    proofToken.setComputedKey(URI.create(wstVer.getCKPSHA1algorithmURI()));
                    proofToken.setProofTokenType(RequestedProofToken.COMPUTED_KEY_TYPE);
                    key = SecurityUtil.P_SHA1(clientEntr, key, keySize/8);
                }else{
                    proofToken.setProofTokenType(RequestedProofToken.BINARY_SECRET_TYPE);
                    proofToken.setBinarySecret(serverBS);
                }
            } catch (Exception ex){
                log.log(Level.SEVERE,
                        LogStringsMessages.WST_0013_ERROR_SECRET_KEY(wstVer.getCKPSHA1algorithmURI(), keySize, appliesTo), ex);
                throw new WSTrustException(LogStringsMessages.WST_0013_ERROR_SECRET_KEY(wstVer.getCKPSHA1algorithmURI(), keySize, appliesTo), ex);
            }
           
            // put the generated secret key into the IssuedTokenContext
            context.setProofKey(key);
        }else if(wstVer.getPublicKeyTypeURI().equals(keyType)){
            // Get UseKey from the RST
            UseKey useKey = rst.getUseKey();
            if (useKey != null){
                Element uk = (Element)eleFac.toElement(useKey.getToken().getTokenValue());
                context.getOtherProperties().put("ConfirmationKeyInfo", uk);
            }
            final Set certs = subject.getPublicCredentials();
            boolean addedClientCert = false;
            for(Object o : certs){
                if(o instanceof X509Certificate){
                    final X509Certificate clientCert = (X509Certificate)o;
                    context.setRequestorCertificate(clientCert);
                    addedClientCert = true;
                }
            }
            if(!addedClientCert && useKey == null){
                log.log(Level.SEVERE,
                        LogStringsMessages.WST_0034_UNABLE_GET_CLIENT_CERT());
                throw new WSTrustException(LogStringsMessages.WST_0034_UNABLE_GET_CLIENT_CERT());
            }
        }else if(wstVer.getBearerKeyTypeURI().equals(keyType)){
            //No proof key required
        }else{
            log.log(Level.SEVERE,
                    LogStringsMessages.WST_0025_INVALID_KEY_TYPE(keyType, appliesTo));
            throw new WSTrustException(LogStringsMessages.WST_0025_INVALID_KEY_TYPE(keyType, appliesTo));
        }
       
        // Create Lifetime
        Lifetime lifetime = rst.getLifetime();
        long currentTime = WSTrustUtil.getCurrentTimeWithOffset();
        long lifespan = -1;
        if (lifetime == null){
            lifespan = stsConfig.getIssuedTokenTimeout();
            lifetime = WSTrustUtil.createLifetime(currentTime, lifespan, wstVer);
          
        }else{
            lifespan = WSTrustUtil.getLifeSpan(lifetime);
        }
        context.setCreationTime(new Date(currentTime));
        context.setExpirationTime(new Date(currentTime + lifespan));
       
        //==============================================
        // Create RequestedSecurityToken and references
        //==============================================
       
        // Get STSTokenProvider
        STSTokenProvider tokenProvider = WSTrustFactory.getSTSTokenProvider();
        tokenProvider.generateToken(context);
       
        // Create RequestedSecurityToken
        final RequestedSecurityToken reqSecTok = eleFac.createRequestedSecurityToken();
        Token issuedToken = context.getSecurityToken();
       
        // Encrypt the token if required and the service certificate is available
        if (stsConfig.getEncryptIssuedToken()&& serCert != null){
            String keyWrapAlgo = (String) context.getOtherProperties().get(IssuedTokenContext.KEY_WRAP_ALGORITHM);
            Element encTokenEle = this.encryptToken((Element)issuedToken.getTokenValue(), serCert, appliesTo, encryptionAlgorithm, keyWrapAlgo);
            issuedToken = new GenericToken(encTokenEle);
        }
        reqSecTok.setToken(issuedToken);
       
        // Create RequestedAttachedReference and RequestedUnattachedReference
        final SecurityTokenReference raSTR = (SecurityTokenReference)context.getAttachedSecurityTokenReference();
        final SecurityTokenReference ruSTR = (SecurityTokenReference)context.getUnAttachedSecurityTokenReference();
        RequestedAttachedReference raRef =  null;
        if (raSTR != null){
            raRef = eleFac.createRequestedAttachedReference(raSTR);
        }
        RequestedUnattachedReference ruRef = null;
        if (ruSTR != null){
            ruRef = eleFac.createRequestedUnattachedReference(ruSTR);
        }
       
        //======================================
        // Create RequestSecurityTokenResponse
        //======================================
       
        // get Context
        URI ctx = null;
        final String rstCtx = rst.getContext();
        if (rstCtx != null){
            ctx = URI.create(rstCtx);
        }
     
        // Create RequestSecurityTokenResponse
View Full Code Here


    public BaseSTSResponse cancel(BaseSTSRequest rst, IssuedTokenContext context, Map map) throws WSTrustException {
        throw new UnsupportedOperationException("Unsupported operation: cancel");
    }

    public BaseSTSResponse validate(BaseSTSRequest request, IssuedTokenContext context) throws WSTrustException {
        RequestSecurityToken rst = (RequestSecurityToken)request;
       
        // Get STS certificate and private key
        Object[] certAndKey = this.getSTSCertAndPrivateKey();
        context.getOtherProperties().put(IssuedTokenContext.STS_CERTIFICATE, (X509Certificate)certAndKey[0]);
        context.getOtherProperties().put(IssuedTokenContext.STS_PRIVATE_KEY, (PrivateKey)certAndKey[1]);
        context.getOtherProperties().put(IssuedTokenContext.WS_TRUST_VERSION, wstVer);
        
        // get TokenType
        URI tokenType = rst.getTokenType();
        context.setTokenType(tokenType.toString());
       
        //Get ValidateTarget
        Element token = null;
        Element assertionInRST = (Element)stsConfig.getOtherOptions().get(WSTrustConstants.SAML_ASSERTION_ELEMENT_IN_RST);
        if (assertionInRST != null){
            token = assertionInRST;
        }else if (wstVer.getNamespaceURI().equals(WSTrustVersion.WS_TRUST_10_NS_URI)){
            // It is not well defined how to carry the security token
            // to be validated. ValidateTarget is only introduced in the
            // ws-trust 1.3. Here we assume the token is directly child element
            // of RST
            List<Object> exts = rst.getExtensionElements();
            if (exts.size() > 0){
                token = (Element)exts.get(0);
           
        }else{
            ValidateTarget vt = rst.getValidateTarget();
            token = (Element)vt.getAny();
        }
        context.setTarget(new GenericToken(token));
       
        // Get STSTokenProvider and validate the token
View Full Code Here

        this.wstVer = (WSTrustVersion)stsConfig.getOtherOptions().get(WSTrustConstants.WST_VERSION);
        this.eleFac = WSTrustElementFactory.newInstance(wstVer);
    }

    public BaseSTSResponse issue(BaseSTSRequest request, IssuedTokenContext context) throws WSTrustException {
        RequestSecurityToken rst = (RequestSecurityToken)request;
        SecondaryParameters secParas = null;
        context.getOtherProperties().put(IssuedTokenContext.WS_TRUST_VERSION, wstVer);
        if (wstVer.getNamespaceURI().equals(WSTrustVersion.WS_TRUST_13_NS_URI)){
            secParas = rst.getSecondaryParameters();
        }
       
       // Get token scope
        final AppliesTo applies = rst.getAppliesTo();
        String appliesTo = null;
        X509Certificate serCert = null;
        List<Object> at = null;
        if(applies != null){
            at = WSTrustUtil.parseAppliesTo(applies);
            for (int i = 0; i < at.size(); i++){
                Object obj = at.get(i);
                if (obj instanceof String){
                    appliesTo = (String)obj;
                }else if (obj instanceof X509Certificate){
                    serCert = (X509Certificate)obj;
                }
            }
        }
        context.setAppliesTo(appliesTo);
       
        // Get token issuer
        String issuer = stsConfig.getIssuer();
        context.setTokenIssuer(issuer);
       
        // Get the metadata for the SP as identified by the AppliesTo
        TrustSPMetadata spMd = stsConfig.getTrustSPMetadata(appliesTo);
        if (spMd == null){
            // Only used for testing purpose; default should not documented
            spMd = stsConfig.getTrustSPMetadata("default");
        }
        if (spMd == null){
            log.log(Level.SEVERE,
                    LogStringsMessages.WST_0004_UNKNOWN_SERVICEPROVIDER(appliesTo));
            throw new WSTrustException(LogStringsMessages.WST_0004_UNKNOWN_SERVICEPROVIDER(appliesTo));
        }
       
        // Get service certificate
        if (serCert == null){
            serCert = this.getServiceCertificate(spMd, appliesTo);
        }
        if (serCert != null){
            context.getOtherProperties().put(IssuedTokenContext.TARGET_SERVICE_CERTIFICATE, serCert);
        }
       
        // Get STS certificate and private key
        Object[] certAndKey = this.getSTSCertAndPrivateKey();
        context.getOtherProperties().put(IssuedTokenContext.STS_CERTIFICATE, (X509Certificate)certAndKey[0]);
        context.getOtherProperties().put(IssuedTokenContext.STS_PRIVATE_KEY, (PrivateKey)certAndKey[1]);
       
        // Get TokenType
        String tokenType = null;
        URI tokenTypeURI = rst.getTokenType();
        if (tokenTypeURI == null && secParas != null){
            tokenTypeURI = secParas.getTokenType();
        }
        if (tokenTypeURI != null){
            tokenType = tokenTypeURI.toString();
        }else{
            tokenType = spMd.getTokenType();
        }
        if (tokenType == null){
            tokenType = WSTrustConstants.SAML11_ASSERTION_TOKEN_TYPE;
        }
        context.setTokenType(tokenType);
       
        // Get KeyType
        String keyType = null;
        URI keyTypeURI = rst.getKeyType();
        if (keyTypeURI == null && secParas != null){
            keyTypeURI = secParas.getKeyType();
        }
        if (keyTypeURI != null){
            keyType = keyTypeURI.toString();
        }else{
            keyType = spMd.getKeyType();
        }
        if (keyType == null){
            keyType = wstVer.getSymmetricKeyTypeURI();
        }
        context.setKeyType(keyType);

        // Get crypto algorithms
        String encryptionAlgorithm = null;
        URI encryptionAlgorithmURI = rst.getEncryptionAlgorithm();
        if(encryptionAlgorithmURI == null && secParas != null){
            encryptionAlgorithmURI = secParas.getEncryptionAlgorithm();
        }
        if(encryptionAlgorithmURI != null){
            encryptionAlgorithm = encryptionAlgorithmURI.toString();
        }
        context.setEncryptionAlgorithm(encryptionAlgorithm);
       
        String signatureAlgorithm = null;
        URI signatureAlgorithmURI = rst.getSignatureAlgorithm();
        if(signatureAlgorithmURI == null && secParas != null){
            signatureAlgorithmURI = secParas.getSignatureAlgorithm();
        }
        if(signatureAlgorithmURI != null){
            signatureAlgorithm = signatureAlgorithmURI.toString();
        }
        context.setSignatureAlgorithm(signatureAlgorithm);
       
        String canonicalizationAlgorithm = null;
        URI canonicalizationAlgorithmURI = rst.getCanonicalizationAlgorithm();
        if(canonicalizationAlgorithmURI == null && secParas != null){
            canonicalizationAlgorithmURI = secParas.getCanonicalizationAlgorithm();
        }
        if(canonicalizationAlgorithmURI != null){
            canonicalizationAlgorithm = canonicalizationAlgorithmURI.toString();
        }
        context.setCanonicalizationAlgorithm(canonicalizationAlgorithm);
       
        // Get KeyWrap Algorithm, which is the part of WS-Trust wssx versaion
        URI keyWrapAlgorithmURI = null;       
        if(secParas != null){
            keyWrapAlgorithmURI = secParas.getKeyWrapAlgorithm();           
        }       
        if(keyWrapAlgorithmURI != null){
            context.getOtherProperties().put(IssuedTokenContext.KEY_WRAP_ALGORITHM, keyWrapAlgorithmURI.toString());
        }               
       
        // Get authenticaed client Subject
        Subject subject = context.getRequestorSubject();
        if (subject == null){
            AccessControlContext acc = AccessController.getContext();
            subject = Subject.getSubject(acc);
            context.setRequestorSubject(subject);
        }
        if(subject == null){
            log.log(Level.SEVERE,
                    LogStringsMessages.WST_0030_REQUESTOR_NULL());
            throw new WSTrustException(LogStringsMessages.WST_0030_REQUESTOR_NULL());
        }
       
        // Get client authentication context
        String authnCtx = (String)stsConfig.getOtherOptions().get(WSTrustConstants.AUTHN_CONTEXT_CLASS);
        if (authnCtx != null){
             context.getOtherProperties().put(IssuedTokenContext.AUTHN_CONTEXT, authnCtx);
        }

        // Get Claims from the RST
        Claims claims = rst.getClaims();
        if (claims == null && secParas != null){
            claims = secParas.getClaims();
        }
        if (claims != null){
            // Add supporting information
            List<Object> si = rst.getExtensionElements();
            claims.getSupportingProperties().addAll(si);
            if (at != null){
                claims.getSupportingProperties().addAll(at);
            }
        }else{
            claims = eleFac.createClaims();
        }

        String confirMethod = null;

        Element assertionInRST = (Element)stsConfig.getOtherOptions().get(WSTrustConstants.SAML_ASSERTION_ELEMENT_IN_RST);
        // Handle OnBehalfOf token
        OnBehalfOf obo = rst.getOnBehalfOf();
        if (obo != null){
            Object oboToken = obo.getAny();
            if (assertionInRST != null){
                oboToken = assertionInRST;
            }
            if (oboToken != null){
                subject.getPublicCredentials().add(eleFac.toElement(oboToken));

                 // set OnBehalfOf attribute
                claims.getOtherAttributes().put(new QName("OnBehalfOf"), "true");
                context.getOtherProperties().put("OnBehalfOf", "true");

                // Create a Subject with ActAs credential and put it in claims
                Subject oboSubj = new Subject();
                oboSubj.getPublicCredentials().add(eleFac.toElement(oboToken));
                claims.getSupportingProperties().add(oboSubj);
            }
        }
       
        // Handle ActAs token
        ActAs actAs = rst.getActAs();
        if (actAs != null){
            Object actAsToken = actAs.getAny();
            if (assertionInRST != null){
                actAsToken = assertionInRST;
            }
            if (actAsToken != null){
                // set ActAs attribute
                claims.getOtherAttributes().put(new QName("ActAs"), "true");
                context.getOtherProperties().put("ActAs", "true");

                // Create a Subject with ActAs credential and put it in claims
                Subject actAsSubj = new Subject();
                actAsSubj.getPublicCredentials().add(eleFac.toElement(actAsToken));
                claims.getSupportingProperties().add(actAsSubj);
            }
        }

        if (confirMethod != null){
            context.getOtherProperties().put(IssuedTokenContext.CONFIRMATION_METHOD, confirMethod);
        }

        // Check if the client is authorized to be issued the token from the STSAuthorizationProvider
        //ToDo: handling ActAs case
        final STSAuthorizationProvider authzProvider = WSTrustFactory.getSTSAuthorizationProvider();
        if (!authzProvider.isAuthorized(subject, appliesTo, tokenType, keyType)){
            String user = subject.getPrincipals().iterator().next().getName();
            log.log(Level.SEVERE,
                    LogStringsMessages.WST_0015_CLIENT_NOT_AUTHORIZED(
                    user, tokenType, appliesTo));
            throw new WSTrustException(LogStringsMessages.WST_0015_CLIENT_NOT_AUTHORIZED(
                    user, tokenType, appliesTo));
        }
       
        // Get claimed attributes from the STSAttributeProvider
        final STSAttributeProvider attrProvider = WSTrustFactory.getSTSAttributeProvider();
        final Map<QName, List<String>> claimedAttrs = attrProvider.getClaimedAttributes(subject, appliesTo, tokenType, claims);
        context.getOtherProperties().put(IssuedTokenContext.CLAIMED_ATTRUBUTES, claimedAttrs);
       
        //==========================================
        // Create proof key and RequestedProofToken
        //==========================================
          
        RequestedProofToken proofToken = null;
        Entropy serverEntropy = null;
        int keySize = 0;
        if (wstVer.getSymmetricKeyTypeURI().equals(keyType)){
            proofToken = eleFac.createRequestedProofToken();
             // Get client entropy
            byte[] clientEntr = null;
            final Entropy clientEntropy = rst.getEntropy();
            if (clientEntropy != null){
                final BinarySecret clientBS = clientEntropy.getBinarySecret();
                if (clientBS == null){
                    if(log.isLoggable(Level.FINE)) {
                        log.log(Level.FINE,
                                LogStringsMessages.WST_1009_NULL_BINARY_SECRET());
                    }
                }else {
                    clientEntr = clientBS.getRawValue();
                }
            }
           
            // Get KeySize
            keySize = (int)rst.getKeySize();
            if (keySize < 1 && secParas != null){
                keySize = (int) secParas.getKeySize();
            }
            if (keySize < 1){
                keySize = DEFAULT_KEY_SIZE;
            }
            if(log.isLoggable(Level.FINE)) {
                log.log(Level.FINE,
                        LogStringsMessages.WST_1010_KEY_SIZE(keySize, DEFAULT_KEY_SIZE));
            }
           
            byte[] key = WSTrustUtil.generateRandomSecret(keySize/8);
            final BinarySecret serverBS = eleFac.createBinarySecret(key, wstVer.getNonceBinarySecretTypeURI());
            serverEntropy = eleFac.createEntropy(serverBS);
           
            // compute the secret key
            try {
                if (clientEntr != null && clientEntr.length > 0){
                    proofToken.setComputedKey(URI.create(wstVer.getCKPSHA1algorithmURI()));
                    proofToken.setProofTokenType(RequestedProofToken.COMPUTED_KEY_TYPE);
                    key = SecurityUtil.P_SHA1(clientEntr, key, keySize/8);
                }else{
                    proofToken.setProofTokenType(RequestedProofToken.BINARY_SECRET_TYPE);
                    proofToken.setBinarySecret(serverBS);
                }
            } catch (Exception ex){
                log.log(Level.SEVERE,
                        LogStringsMessages.WST_0013_ERROR_SECRET_KEY(wstVer.getCKPSHA1algorithmURI(), keySize, appliesTo), ex);
                throw new WSTrustException(LogStringsMessages.WST_0013_ERROR_SECRET_KEY(wstVer.getCKPSHA1algorithmURI(), keySize, appliesTo), ex);
            }
           
            // put the generated secret key into the IssuedTokenContext
            context.setProofKey(key);
        }else if(wstVer.getPublicKeyTypeURI().equals(keyType)){
            // Get UseKey from the RST
            UseKey useKey = rst.getUseKey();
            if (useKey != null){
                Element uk = (Element)eleFac.toElement(useKey.getToken().getTokenValue());
                context.getOtherProperties().put("ConfirmationKeyInfo", uk);
            }
            final Set certs = subject.getPublicCredentials();
            boolean addedClientCert = false;
            for(Object o : certs){
                if(o instanceof X509Certificate){
                    final X509Certificate clientCert = (X509Certificate)o;
                    context.setRequestorCertificate(clientCert);
                    addedClientCert = true;
                }
            }
            if(!addedClientCert && useKey == null){
                log.log(Level.SEVERE,
                        LogStringsMessages.WST_0034_UNABLE_GET_CLIENT_CERT());
                throw new WSTrustException(LogStringsMessages.WST_0034_UNABLE_GET_CLIENT_CERT());
            }
        }else if(wstVer.getBearerKeyTypeURI().equals(keyType)){
            //No proof key required
        }else{
            log.log(Level.SEVERE,
                    LogStringsMessages.WST_0025_INVALID_KEY_TYPE(keyType, appliesTo));
            throw new WSTrustException(LogStringsMessages.WST_0025_INVALID_KEY_TYPE(keyType, appliesTo));
        }
       
        // Create Lifetime
        Lifetime lifetime = rst.getLifetime();
        long currentTime = WSTrustUtil.getCurrentTimeWithOffset();
        long lifespan = -1;
        if (lifetime == null){
            lifespan = stsConfig.getIssuedTokenTimeout();
            lifetime = WSTrustUtil.createLifetime(currentTime, lifespan, wstVer);
          
        }else{
            lifespan = WSTrustUtil.getLifeSpan(lifetime);
        }
        context.setCreationTime(new Date(currentTime));
        context.setExpirationTime(new Date(currentTime + lifespan));
       
        //==============================================
        // Create RequestedSecurityToken and references
        //==============================================
       
        // Get STSTokenProvider
        STSTokenProvider tokenProvider = WSTrustFactory.getSTSTokenProvider();
        tokenProvider.generateToken(context);
       
        // Create RequestedSecurityToken
        final RequestedSecurityToken reqSecTok = eleFac.createRequestedSecurityToken();
        Token issuedToken = context.getSecurityToken();
       
        // Encrypt the token if required and the service certificate is available
        if (stsConfig.getEncryptIssuedToken()&& serCert != null){
            String keyWrapAlgo = (String) context.getOtherProperties().get(IssuedTokenContext.KEY_WRAP_ALGORITHM);
            Element encTokenEle = this.encryptToken((Element)issuedToken.getTokenValue(), serCert, appliesTo, encryptionAlgorithm, keyWrapAlgo);
            issuedToken = new GenericToken(encTokenEle);
        }
        reqSecTok.setToken(issuedToken);
       
        // Create RequestedAttachedReference and RequestedUnattachedReference
        final SecurityTokenReference raSTR = (SecurityTokenReference)context.getAttachedSecurityTokenReference();
        final SecurityTokenReference ruSTR = (SecurityTokenReference)context.getUnAttachedSecurityTokenReference();
        RequestedAttachedReference raRef =  null;
        if (raSTR != null){
            raRef = eleFac.createRequestedAttachedReference(raSTR);
        }
        RequestedUnattachedReference ruRef = null;
        if (ruSTR != null){
            ruRef = eleFac.createRequestedUnattachedReference(ruSTR);
        }
       
        //======================================
        // Create RequestSecurityTokenResponse
        //======================================
       
        // get Context
        URI ctx = null;
        final String rstCtx = rst.getContext();
        if (rstCtx != null){
            ctx = URI.create(rstCtx);
        }
     
        // Create RequestSecurityTokenResponse
View Full Code Here

    public BaseSTSResponse cancel(BaseSTSRequest rst, IssuedTokenContext context, Map map) throws WSTrustException {
        throw new UnsupportedOperationException("Unsupported operation: cancel");
    }

    public BaseSTSResponse validate(BaseSTSRequest request, IssuedTokenContext context) throws WSTrustException {
        RequestSecurityToken rst = (RequestSecurityToken)request;
       
        // Get STS certificate and private key
        Object[] certAndKey = this.getSTSCertAndPrivateKey();
        context.getOtherProperties().put(IssuedTokenContext.STS_CERTIFICATE, (X509Certificate)certAndKey[0]);
        context.getOtherProperties().put(IssuedTokenContext.STS_PRIVATE_KEY, (PrivateKey)certAndKey[1]);
        context.getOtherProperties().put(IssuedTokenContext.WS_TRUST_VERSION, wstVer);
        
        // get TokenType
        URI tokenType = rst.getTokenType();
        context.setTokenType(tokenType.toString());
       
        //Get ValidateTarget
        Element token = null;
        Element assertionInRST = (Element)stsConfig.getOtherOptions().get(WSTrustConstants.SAML_ASSERTION_ELEMENT_IN_RST);
        if (assertionInRST != null){
            token = assertionInRST;
        }else if (wstVer.getNamespaceURI().equals(WSTrustVersion.WS_TRUST_10_NS_URI)){
            // It is not well defined how to carry the security token
            // to be validated. ValidateTarget is only introduced in the
            // ws-trust 1.3. Here we assume the token is directly child element
            // of RST
            List<Object> exts = rst.getExtensionElements();
            if (exts.size() > 0){
                token = (Element)exts.get(0);
           
        }else{
            ValidateTarget vt = rst.getValidateTarget();
            token = (Element)vt.getAny();
        }
        context.setTarget(new GenericToken(token));
       
        // Get STSTokenProvider and validate the token
View Full Code Here

        }
        Token oboToken = stsConfig.getOBOToken();

        BaseSTSResponse result = null;
        try {
            final RequestSecurityToken request = createRequest(stsConfig, appliesTo, oboToken);
            
            result = invokeRST(request, stsConfig);
           
            final WSTrustClientContract contract = WSTrustFactory.createWSTrustClientContract();
            contract.handleRSTR(request, result, itc);
View Full Code Here

            throw new WebServiceException(LogStringsMessages.WST_0029_COULD_NOT_GET_STS_LOCATION(null));
        }
        BaseSTSResponse result = null;
        try{
            Token token = itc.getTarget();
            final RequestSecurityToken request = createRequestForValidatation(stsConfig, token);
            result = invokeRST(request, stsConfig);
            final WSTrustClientContract contract = WSTrustFactory.createWSTrustClientContract();
            contract.handleRSTR(request, result, itc);
        }catch (RemoteException ex) {
            log.log(Level.SEVERE,
View Full Code Here

            if (stsConfig.getOtherOptions().containsKey("Identity")){
                addServerIdentity(applTo, stsConfig.getOtherOptions().get("Identity"));
            }
        }

        final RequestSecurityToken rst= fact.createRSTForIssue(null,requestType, null,applTo,null,null,null);

        // Handle OnBehalfOf token
        if (oboToken != null){
            OnBehalfOf obo = fact.createOnBehalfOf(oboToken);
            rst.setOnBehalfOf(obo);
        }

        // Handle ActAs token
        Token actAsToken = (Token)stsConfig.getOtherOptions().get(STSIssuedTokenConfiguration.ACT_AS);
        if (actAsToken != null){
            ActAs actAs = fact.createActAs(actAsToken);
            rst.setActAs(actAs);
        }

        // Handle LifeTime requirement
        Integer lf = (Integer)stsConfig.getOtherOptions().get(STSIssuedTokenConfiguration.LIFE_TIME);
        if(lf != null){
            // Create Lifetime
            long lfValue = lf.longValue();
            if (lfValue > 0){
                long currentTime = WSTrustUtil.getCurrentTimeWithOffset();
                Lifetime lifetime = WSTrustUtil.createLifetime(currentTime, lfValue, wstVer);
                rst.setLifetime(lifetime);
            }
        }

        String tokenType = null;
        String keyType = null;
        long keySize = -1;
        String signWith = null;
        String encryptWith = null;
        String signatureAlgorithm = null;
        String encryptionAlgorithm = null;
        String keyWrapAlgorithm = null;
        String canonicalizationAlgorithm = null;
        Claims claims = null;
        if (wstVer.getNamespaceURI().equals(WSTrustVersion.WS_TRUST_13.getNamespaceURI())){
            SecondaryIssuedTokenParameters sitp = stsConfig.getSecondaryIssuedTokenParameters();
            if (sitp != null){
                SecondaryParameters sp = fact.createSecondaryParameters();
                tokenType = sitp.getTokenType();
                if (tokenType != null){
                    sp.setTokenType(URI.create(tokenType));
                }
                keyType = sitp.getKeyType();
                if (keyType != null){
                    sp.setKeyType(URI.create(keyType));
                }
                keySize = sitp.getKeySize();
                if (keySize > 0){
                    sp.setKeySize(keySize);
                }
                /*
                encryptWith = sitp.getEncryptWith();
                if (encryptWith != null){
                sp.setEncryptWith(URI.create(encryptWith));
                }
                signWith = sitp.getSignWith();
                if (signWith != null){
                sp.setSignWith(URI.create(signWith));
                }
                 */
                signatureAlgorithm = sitp.getSignatureAlgorithm();
                if (signatureAlgorithm != null){
                    sp.setSignatureAlgorithm(URI.create(signatureAlgorithm));
                }
                encryptionAlgorithm = sitp.getEncryptionAlgorithm();
                if (encryptionAlgorithm != null){
                    sp.setEncryptionAlgorithm(URI.create(encryptionAlgorithm));
                }

                canonicalizationAlgorithm = sitp.getCanonicalizationAlgorithm();
                if (canonicalizationAlgorithm != null){
                    sp.setCanonicalizationAlgorithm(URI.create(canonicalizationAlgorithm));
                }

                keyWrapAlgorithm = sitp.getKeyWrapAlgorithm();
                if(keyWrapAlgorithm != null){
                    sp.setKeyWrapAlgorithm(URI.create(keyWrapAlgorithm));
                }

                claims = sitp.getClaims();
                if (claims != null){
                    sp.setClaims(claims);
                }
                rst.setSecondaryParameters(sp);
            }
        }

        if (tokenType == null){
            tokenType = stsConfig.getTokenType();
            if (tokenType != null){
                rst.setTokenType(URI.create(tokenType));
            }
        }

        if (keyType == null){
            keyType = stsConfig.getKeyType();
            if (keyType != null){
                rst.setKeyType(URI.create(keyType));
            }
        }

        if (keySize < 1){
            keySize = stsConfig.getKeySize();
            if (keySize > 0){
                rst.setKeySize(keySize);
            }
        }

        /*
        if (encryptWith == null){
        encryptWith = stsConfig.getEncryptWith();
        if (encryptWith != null){
        rst.setEncryptWith(URI.create(encryptWith));
        }
        }
       
        if (signWith == null){
        signWith = stsConfig.getSignWith();
        if (signWith != null){
        rst.setSignWith(URI.create(signWith));
        }
        }
         */

        if (signatureAlgorithm == null){
            signatureAlgorithm = stsConfig.getSignatureAlgorithm();
            if (signatureAlgorithm != null){
                rst.setSignatureAlgorithm(URI.create(signatureAlgorithm));
            }
        }

        if (encryptionAlgorithm == null){
            encryptionAlgorithm = stsConfig.getEncryptionAlgorithm();
            if (encryptionAlgorithm != null){
                rst.setEncryptionAlgorithm(URI.create(encryptionAlgorithm));
            }
        }

        if (canonicalizationAlgorithm == null){
            canonicalizationAlgorithm = stsConfig.getCanonicalizationAlgorithm();
            if (canonicalizationAlgorithm != null){
                rst.setCanonicalizationAlgorithm(URI.create(canonicalizationAlgorithm));
            }
        }

        if (claims == null){
            claims = stsConfig.getClaims();
            if (claims != null){
                rst.setClaims(fact.createClaims(claims));
            }
        }

        int len = 32;
        if (keySize > 0){
            len = (int)keySize/8;
        }

        if (wstVer.getSymmetricKeyTypeURI().equals(keyType)){
            final SecureRandom secRandom = new SecureRandom();
            final byte[] nonce = new byte[len];
            secRandom.nextBytes(nonce);
            final BinarySecret binarySecret = fact.createBinarySecret(nonce, wstVer.getNonceBinarySecretTypeURI());
            final Entropy entropy = fact.createEntropy(binarySecret);
            rst.setEntropy(entropy);
            rst.setComputedKeyAlgorithm(URI.create(wstVer.getCKPSHA1algorithmURI()));
        }else if (wstVer.getPublicKeyTypeURI().equals(keyType) && keySize > 1 ){
            // Create a RSA key pairs for use with UseKey
            KeyPairGenerator kpg;
            try{
                kpg = KeyPairGenerator.getInstance("RSA");
            //RSAKeyGenParameterSpec rsaSpec = new RSAKeyGenParameterSpec((int)keySize, RSAKeyGenParameterSpec.F0);
            //kpg.initialize(rsaSpec);
            }catch (NoSuchAlgorithmException ex){
                throw new WSTrustException("Unable to create key pairs for UseKey", ex);
            }
            //catch (InvalidAlgorithmParameterException ex){
            //    throw new WSTrustException("Unable to create key pairs for UseKey", ex);
            //}
            kpg.initialize((int)keySize);
            KeyPair keyPair = kpg.generateKeyPair();

            // Create the Sig attribute Value for UseKey
            // String sig = "uuid-" + UUID.randomUUID().toString();

            // Create the UseKey element in RST
            KeyInfo keyInfo = createKeyInfo(keyPair.getPublic());
            final DocumentBuilderFactory docFactory = WSITXMLFactory.createDocumentBuilderFactory(WSITXMLFactory.DISABLE_SECURE_PROCESSING);
            Document doc = null;
            try{
                doc = docFactory.newDocumentBuilder().newDocument();
                keyInfo.marshal(new DOMStructure(doc), null);
            }catch(ParserConfigurationException ex){
                log.log(Level.SEVERE,
                        LogStringsMessages.WST_0039_ERROR_CREATING_DOCFACTORY(), ex);
                throw new WSTrustException(LogStringsMessages.WST_0039_ERROR_CREATING_DOCFACTORY(), ex);
            }catch(MarshalException ex){
                log.log(Level.SEVERE,
                        LogStringsMessages.WST_0039_ERROR_CREATING_DOCFACTORY(), ex);
                throw new WSTrustException(LogStringsMessages.WST_0039_ERROR_CREATING_DOCFACTORY(), ex);
            }
            Token token = new GenericToken(doc.getDocumentElement());
            UseKey useKey = fact.createUseKey(token, null);
            rst.setUseKey(useKey);

            // Put the key pair and the sig in the STSConfiguration
            stsConfig.getOtherOptions().put(WSTrustConstants.USE_KEY_RSA_KEY_PAIR, keyPair);
        //stsConfig.getOtherOptions().put(WSTrustConstants.USE_KEY_SIGNATURE_ID, sig); */
        }
View Full Code Here

    private RequestSecurityToken createRequestForValidatation(final STSIssuedTokenConfiguration stsConfig, final Token token){
        WSTrustVersion wstVer = WSTrustVersion.getInstance(stsConfig.getProtocol());
        WSTrustElementFactory fact = WSTrustElementFactory.newInstance(wstVer);
        final URI requestType = URI.create(wstVer.getValidateRequestTypeURI());
        final URI tokenType = URI.create(wstVer.getValidateStatuesTokenType());
        final RequestSecurityToken rst= fact.createRSTForValidate(tokenType, requestType);
        if (wstVer.getNamespaceURI().equals(WSTrustVersion.WS_TRUST_10_NS_URI)){
            rst.getAny().add(token.getTokenValue());
        }else {
            ValidateTarget vt = fact.createValidateTarget(token);
            rst.setValidateTarget(vt);
        }
       
        return rst;
    }
View Full Code Here

        final STSConfiguration config = getConfiguration();
        Source rstrEle = null;
        try{
            // Get RequestSecurityToken
            final WSTrustElementFactory eleFac = WSTrustElementFactory.newInstance(wstVer);
            final RequestSecurityToken rst = parseRST(rstElement, config);
           
            String appliesTo = null;
            final AppliesTo applTo = rst.getAppliesTo();
            if(applTo != null){
                appliesTo = WSTrustUtil.getAppliesToURI(applTo);
            }
           
            if (appliesTo == null){
                appliesTo = DEFAULT_APPLIESTO;
            }
           
            if(rst.getRequestType().toString().equals(wstVer.getIssueRequestTypeURI())){
                rstrEle = issue(config, appliesTo, eleFac, rst);               
            }else if(rst.getRequestType().toString().equals(wstVer.getCancelRequestTypeURI())){
                rstrEle = cancel(config, appliesTo, eleFac, rst);
            }else if(rst.getRequestType().toString().equals(wstVer.getRenewRequestTypeURI())){
                rstrEle = renew(config, appliesTo, eleFac, rst);
            }else if(rst.getRequestType().toString().equals(wstVer.getValidateRequestTypeURI())){
                rstrEle = validate(config, appliesTo, eleFac, rst);
            }           
        } catch (Exception ex){
            //ex.printStackTrace();
            throw new WebServiceException(ex);
View Full Code Here

            }
        }catch(Exception xe){
            throw new WSTrustException("Error occurred while trying to parse RST stream", xe);
        }
        WSTrustElementFactory fact = WSTrustElementFactory.newInstance(wstVer);
        RequestSecurityToken rst = fact.createRSTFrom(ele);

        // handling SAML assertion in RST; assume there is one one
        // in it fro OnBehalfOf, ActAs or ValidateTarget.
        NodeList list = ele.getElementsByTagNameNS("*", "Assertion");
        if (list.getLength() > 0){
View Full Code Here

TOP

Related Classes of com.sun.xml.ws.security.trust.elements.RequestSecurityToken

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.