You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cxf.apache.org by as...@apache.org on 2015/06/23 22:34:37 UTC
cxf git commit: [CXF-6267]: splitted policy dependent functionality,
renamed utility class
Repository: cxf
Updated Branches:
refs/heads/master 3dc064a3a -> 9c5f2a657
[CXF-6267]: splitted policy dependent functionality, renamed utility class
Project: http://git-wip-us.apache.org/repos/asf/cxf/repo
Commit: http://git-wip-us.apache.org/repos/asf/cxf/commit/9c5f2a65
Tree: http://git-wip-us.apache.org/repos/asf/cxf/tree/9c5f2a65
Diff: http://git-wip-us.apache.org/repos/asf/cxf/diff/9c5f2a65
Branch: refs/heads/master
Commit: 9c5f2a65793d73ea010661b5722087cbc692e334
Parents: 3dc064a
Author: Andrei Shakirin <an...@gmail.com>
Authored: Tue Jun 23 22:33:51 2015 +0200
Committer: Andrei Shakirin <an...@gmail.com>
Committed: Tue Jun 23 22:33:51 2015 +0200
----------------------------------------------------------------------
.../IssuedTokenInterceptorProvider.java | 14 +-
.../policy/interceptors/STSTokenHelper.java | 514 -------------------
.../ws/security/trust/STSTokenRetriever.java | 480 +++++++++++++++++
.../sts/stsclient/STSTokenHelperTest.java | 273 ----------
.../sts/stsclient/STSTokenRetrieverTest.java | 273 ++++++++++
5 files changed, 766 insertions(+), 788 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/cxf/blob/9c5f2a65/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/IssuedTokenInterceptorProvider.java
----------------------------------------------------------------------
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/IssuedTokenInterceptorProvider.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/IssuedTokenInterceptorProvider.java
index c14c73f..f8a4475 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/IssuedTokenInterceptorProvider.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/IssuedTokenInterceptorProvider.java
@@ -38,6 +38,8 @@ import org.apache.cxf.ws.policy.AssertionInfoMap;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.policy.PolicyUtils;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.cxf.ws.security.trust.STSTokenRetriever;
+import org.apache.cxf.ws.security.trust.STSTokenRetriever.TokenRequestParams;
import org.apache.cxf.ws.security.wss4j.PolicyBasedWSS4JInInterceptor;
import org.apache.cxf.ws.security.wss4j.PolicyBasedWSS4JOutInterceptor;
import org.apache.cxf.ws.security.wss4j.PolicyBasedWSS4JStaxInInterceptor;
@@ -117,7 +119,17 @@ public class IssuedTokenInterceptorProvider extends AbstractPolicyInterceptorPro
if (isRequestor(message)) {
IssuedToken itok = (IssuedToken)ais.iterator().next().getAssertion();
- SecurityToken tok = STSTokenHelper.getTokenByWSPolicy(message, itok, aim);
+ TokenRequestParams params = new TokenRequestParams();
+ params.setIssuer(itok.getIssuer());
+ params.setClaims(itok.getClaims());
+ if (itok.getPolicy() != null) {
+ params.setWspNamespace(itok.getPolicy().getNamespace());
+ }
+ params.setTrust10(NegotiationUtils.getTrust10(aim));
+ params.setTrust13(NegotiationUtils.getTrust13(aim));
+ params.setTokenTemplate(itok.getRequestSecurityTokenTemplate());
+
+ SecurityToken tok = STSTokenRetriever.getToken(message, params);
if (tok != null) {
assertIssuedToken(itok, aim);
http://git-wip-us.apache.org/repos/asf/cxf/blob/9c5f2a65/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/STSTokenHelper.java
----------------------------------------------------------------------
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/STSTokenHelper.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/STSTokenHelper.java
deleted file mode 100644
index 428da7e..0000000
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/STSTokenHelper.java
+++ /dev/null
@@ -1,514 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.ws.security.policy.interceptors;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.w3c.dom.Element;
-import org.apache.cxf.common.logging.LogUtils;
-import org.apache.cxf.interceptor.Fault;
-import org.apache.cxf.message.Message;
-import org.apache.cxf.message.MessageUtils;
-import org.apache.cxf.ws.addressing.AddressingProperties;
-import org.apache.cxf.ws.policy.AssertionInfoMap;
-import org.apache.cxf.ws.security.SecurityConstants;
-import org.apache.cxf.ws.security.tokenstore.SecurityToken;
-import org.apache.cxf.ws.security.tokenstore.TokenStore;
-import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils;
-import org.apache.cxf.ws.security.trust.STSClient;
-import org.apache.cxf.ws.security.trust.STSUtils;
-import org.apache.wss4j.common.ext.WSSecurityException;
-import org.apache.wss4j.common.saml.SamlAssertionWrapper;
-import org.apache.wss4j.dom.WSConstants;
-import org.apache.wss4j.policy.model.IssuedToken;
-import org.apache.wss4j.policy.model.Trust10;
-import org.apache.wss4j.policy.model.Trust13;
-
-public final class STSTokenHelper {
- private static final Logger LOG = LogUtils.getL7dLogger(STSTokenHelper.class);
- private static final String ASSOCIATED_TOKEN =
- STSTokenHelper.class.getName() + "-" + "Associated_Token";
-
- private STSTokenHelper() {
- }
-
- public static SecurityToken getTokenByWSPolicy(Message message, IssuedToken issuedToken,
- AssertionInfoMap aim) {
- TokenRequestParams params = new TokenRequestParams();
- params.setIssuer(issuedToken.getIssuer());
- params.setClaims(issuedToken.getClaims());
- if (issuedToken.getPolicy() != null) {
- params.setWspNamespace(issuedToken.getPolicy().getNamespace());
- }
- params.setTrust10(NegotiationUtils.getTrust10(aim));
- params.setTrust13(NegotiationUtils.getTrust13(aim));
- params.setTokenTemplate(issuedToken.getRequestSecurityTokenTemplate());
-
- return getToken(message, params);
- }
-
- public static SecurityToken getToken(Message message, TokenRequestParams params) {
- SecurityToken tok = retrieveCachedToken(message);
- if (tok == null) {
- tok = issueToken(message, params);
- } else {
- tok = renewToken(message, tok, params);
- }
-
- boolean cacheIssuedToken =
- MessageUtils.getContextualBoolean(
- message,
- SecurityConstants.CACHE_ISSUED_TOKEN_IN_ENDPOINT,
- true)
- && !isOneTimeUse(tok);
- if (cacheIssuedToken) {
- message.getExchange().getEndpoint().put(SecurityConstants.TOKEN, tok);
- message.getExchange().put(SecurityConstants.TOKEN, tok);
- message.getExchange().put(SecurityConstants.TOKEN_ID, tok.getId());
- message.getExchange().getEndpoint().put(SecurityConstants.TOKEN_ID,
- tok.getId());
- } else {
- message.put(SecurityConstants.TOKEN, tok);
- message.put(SecurityConstants.TOKEN_ID, tok.getId());
- }
- // ?
- TokenStoreUtils.getTokenStore(message).add(tok);
-
- return tok;
- }
-
- private static SecurityToken retrieveCachedToken(Message message) {
- boolean cacheIssuedToken =
- MessageUtils.getContextualBoolean(
- message,
- SecurityConstants.CACHE_ISSUED_TOKEN_IN_ENDPOINT,
- true);
- SecurityToken tok = null;
- if (cacheIssuedToken) {
- tok = (SecurityToken)message.getContextualProperty(SecurityConstants.TOKEN);
- if (tok == null) {
- String tokId = (String)message.getContextualProperty(SecurityConstants.TOKEN_ID);
- if (tokId != null) {
- tok = TokenStoreUtils.getTokenStore(message).getToken(tokId);
- }
- }
- } else {
- tok = (SecurityToken)message.get(SecurityConstants.TOKEN);
- if (tok == null) {
- String tokId = (String)message.get(SecurityConstants.TOKEN_ID);
- if (tokId != null) {
- tok = TokenStoreUtils.getTokenStore(message).getToken(tokId);
- }
- }
- }
- return tok;
- }
-
- private static SecurityToken issueToken(Message message, TokenRequestParams params) {
- AddressingProperties maps =
- (AddressingProperties)message
- .get("javax.xml.ws.addressing.context.outbound");
- if (maps == null) {
- maps = (AddressingProperties)message
- .get("javax.xml.ws.addressing.context");
- }
- STSClient client = STSUtils.getClientWithIssuer(message, "sts", params.getIssuer());
- synchronized (client) {
- try {
- // Transpose ActAs/OnBehalfOf info from original request to the STS client.
- Object token =
- message.getContextualProperty(SecurityConstants.STS_TOKEN_ACT_AS);
- if (token != null) {
- client.setActAs(token);
- }
- token =
- message.getContextualProperty(SecurityConstants.STS_TOKEN_ON_BEHALF_OF);
- if (token != null) {
- client.setOnBehalfOf(token);
- }
- Map<String, Object> ctx = client.getRequestContext();
- mapSecurityProps(message, ctx);
-
- Object o = message.getContextualProperty(SecurityConstants.STS_APPLIES_TO);
- String appliesTo = o == null ? null : o.toString();
- appliesTo = appliesTo == null
- ? message.getContextualProperty(Message.ENDPOINT_ADDRESS).toString()
- : appliesTo;
- boolean enableAppliesTo = client.isEnableAppliesTo();
-
- client.setMessage(message);
- Element onBehalfOfToken = client.getOnBehalfOfToken();
- Element actAsToken = client.getActAsToken();
-
- SecurityToken secToken =
- handleDelegation(
- message, onBehalfOfToken, actAsToken, appliesTo,
- enableAppliesTo
- );
- if (secToken == null) {
- secToken = getTokenFromSTS(message, client, maps, appliesTo, params);
- }
- storeDelegationTokens(
- message, secToken, onBehalfOfToken, actAsToken, appliesTo,
- enableAppliesTo);
- return secToken;
- } catch (RuntimeException e) {
- throw e;
- } catch (Exception e) {
- throw new Fault(e);
- } finally {
- client.setTrust((Trust10)null);
- client.setTrust((Trust13)null);
- client.setTemplate(null);
- client.setAddressingNamespace(null);
- }
- }
- }
-
- private static SecurityToken renewToken(
- Message message,
- SecurityToken tok,
- TokenRequestParams params) {
- String imminentExpiryValue =
- (String)message
- .getContextualProperty(SecurityConstants.STS_TOKEN_IMMINENT_EXPIRY_VALUE);
- long imminentExpiry = 10L;
- if (imminentExpiryValue != null) {
- imminentExpiry = Long.parseLong(imminentExpiryValue);
- }
-
- // If the token has not expired then we don't need to renew it
- if (!(tok.isExpired() || tok.isAboutToExpire(imminentExpiry))) {
- return tok;
- }
-
- // Remove token from cache
- message.getExchange().getEndpoint().remove(SecurityConstants.TOKEN);
- message.getExchange().getEndpoint().remove(SecurityConstants.TOKEN_ID);
- message.getExchange().remove(SecurityConstants.TOKEN_ID);
- message.getExchange().remove(SecurityConstants.TOKEN);
- TokenStoreUtils.getTokenStore(message).remove(tok.getId());
-
- // If the user has explicitly disabled Renewing then we can't renew a token,
- // so just get a new one
- STSClient client = STSUtils.getClientWithIssuer(message, "sts", params.getIssuer());
- if (!client.isAllowRenewing()) {
- return issueToken(message, params);
- }
-
- AddressingProperties maps =
- (AddressingProperties)message
- .get("javax.xml.ws.addressing.context.outbound");
- if (maps == null) {
- maps = (AddressingProperties)message
- .get("javax.xml.ws.addressing.context");
- }
- synchronized (client) {
- try {
- Map<String, Object> ctx = client.getRequestContext();
- mapSecurityProps(message, ctx);
-
- client.setMessage(message);
-
- if (maps != null) {
- client.setAddressingNamespace(maps.getNamespaceURI());
- }
-
- client.setTrust(params.getTrust10());
- client.setTrust(params.getTrust13());
-
- client.setTemplate(params.getTokenTemplate());
- return client.renewSecurityToken(tok);
- } catch (RuntimeException ex) {
- LOG.log(Level.WARNING, "Error renewing a token", ex);
- boolean issueAfterFailedRenew =
- MessageUtils
- .getContextualBoolean(
- message,
- SecurityConstants.STS_ISSUE_AFTER_FAILED_RENEW, true);
- if (issueAfterFailedRenew) {
- // Perhaps the STS does not support renewing, so try to issue a new token
- return issueToken(message, params);
- } else {
- throw ex;
- }
- } catch (Exception ex) {
- LOG.log(Level.WARNING, "Error renewing a token", ex);
- boolean issueAfterFailedRenew =
- MessageUtils
- .getContextualBoolean(
- message,
- SecurityConstants.STS_ISSUE_AFTER_FAILED_RENEW, true);
- if (issueAfterFailedRenew) {
- // Perhaps the STS does not support renewing, so try to issue a new token
- return issueToken(message, params);
- } else {
- throw new Fault(ex);
- }
- } finally {
- client.setTrust((Trust10)null);
- client.setTrust((Trust13)null);
- client.setTemplate(null);
- client.setAddressingNamespace(null);
- }
- }
- }
-
- // Check to see if the received token is a SAML2 Token with "OneTimeUse" set. If so,
- // it should not be cached on the endpoint, but only on the message.
- private static boolean isOneTimeUse(SecurityToken issuedToken) {
- Element token = issuedToken.getToken();
- if (token != null && "Assertion".equals(token.getLocalName())
- && WSConstants.SAML2_NS.equals(token.getNamespaceURI())) {
- try {
- SamlAssertionWrapper assertion = new SamlAssertionWrapper(token);
-
- if (assertion.getSaml2().getConditions() != null
- && assertion.getSaml2().getConditions().getOneTimeUse() != null) {
- return true;
- }
- } catch (WSSecurityException ex) {
- throw new Fault(ex);
- }
- }
-
- return false;
- }
-
- private static void mapSecurityProps(Message message, Map<String, Object> ctx) {
- for (String s : SecurityConstants.ALL_PROPERTIES) {
- Object v = message.getContextualProperty(s + ".it");
- if (v == null) {
- v = message.getContextualProperty(s);
- }
- if (!ctx.containsKey(s) && v != null) {
- ctx.put(s, v);
- }
- }
- }
-
- /**
- * Parse ActAs/OnBehalfOf appropriately. See if the required token is stored in the cache.
- */
- private static SecurityToken handleDelegation(
- Message message,
- Element onBehalfOfToken,
- Element actAsToken,
- String appliesTo,
- boolean enableAppliesTo) throws Exception {
- TokenStore tokenStore = TokenStoreUtils.getTokenStore(message);
- String key = appliesTo;
- if (!enableAppliesTo || key == null || "".equals(key)) {
- key = ASSOCIATED_TOKEN;
- }
- // See if the token corresponding to the OnBehalfOf Token is stored in the cache
- // and if it points to an issued token
- if (onBehalfOfToken != null) {
- String id = getIdFromToken(onBehalfOfToken);
- SecurityToken cachedToken = tokenStore.getToken(id);
- if (cachedToken != null) {
- Map<String, Object> properties = cachedToken.getProperties();
- if (properties != null && properties.containsKey(key)) {
- String associatedToken = (String)properties.get(key);
- SecurityToken issuedToken = tokenStore.getToken(associatedToken);
- if (issuedToken != null) {
- return issuedToken;
- }
- }
- }
- }
-
- // See if the token corresponding to the ActAs Token is stored in the cache
- // and if it points to an issued token
- if (actAsToken != null) {
- String id = getIdFromToken(actAsToken);
- SecurityToken cachedToken = tokenStore.getToken(id);
- if (cachedToken != null) {
- Map<String, Object> properties = cachedToken.getProperties();
- if (properties != null && properties.containsKey(key)) {
- String associatedToken = (String)properties.get(key);
- SecurityToken issuedToken = tokenStore.getToken(associatedToken);
- if (issuedToken != null) {
- return issuedToken;
- }
- }
- }
- }
- return null;
- }
-
- private static String getIdFromToken(Element token) {
- if (token != null) {
- // Try to find the "Id" on the token.
- if (token.hasAttributeNS(WSConstants.WSU_NS, "Id")) {
- return token.getAttributeNS(WSConstants.WSU_NS, "Id");
- } else if (token.hasAttributeNS(null, "ID")) {
- return token.getAttributeNS(null, "ID");
- } else if (token.hasAttributeNS(null, "AssertionID")) {
- return token.getAttributeNS(null, "AssertionID");
- }
- }
- return "";
- }
-
- private static void storeDelegationTokens(
- Message message,
- SecurityToken issuedToken,
- Element onBehalfOfToken,
- Element actAsToken,
- String appliesTo,
- boolean enableAppliesTo) throws Exception {
- if (issuedToken == null) {
- return;
- }
- TokenStore tokenStore = TokenStoreUtils.getTokenStore(message);
- String key = appliesTo;
- if (!enableAppliesTo || key == null || "".equals(key)) {
- key = ASSOCIATED_TOKEN;
- }
- if (onBehalfOfToken != null) {
- String id = getIdFromToken(onBehalfOfToken);
- SecurityToken cachedToken = tokenStore.getToken(id);
- if (cachedToken == null) {
- cachedToken = new SecurityToken(id);
- cachedToken.setToken(onBehalfOfToken);
- }
- Map<String, Object> properties = cachedToken.getProperties();
- if (properties == null) {
- properties = new HashMap<>();
- cachedToken.setProperties(properties);
- }
- properties.put(key, issuedToken.getId());
- tokenStore.add(cachedToken);
- }
- if (actAsToken != null) {
- String id = getIdFromToken(actAsToken);
- SecurityToken cachedToken = tokenStore.getToken(id);
- if (cachedToken == null) {
- cachedToken = new SecurityToken(id);
- cachedToken.setToken(actAsToken);
- }
- Map<String, Object> properties = cachedToken.getProperties();
- if (properties == null) {
- properties = new HashMap<>();
- cachedToken.setProperties(properties);
- }
- properties.put(key, issuedToken.getId());
- tokenStore.add(cachedToken);
- }
- }
-
- private static SecurityToken getTokenFromSTS(Message message, STSClient client,
- AddressingProperties maps, String appliesTo,
- TokenRequestParams params) throws Exception {
- client.setTrust(params.getTrust10());
- client.setTrust(params.getTrust13());
- client.setTemplate(params.getTokenTemplate());
- if (params.getWspNamespace() != null) {
- client.setWspNamespace(params.getWspNamespace());
- }
- if (maps != null && maps.getNamespaceURI() != null) {
- client.setAddressingNamespace(maps.getNamespaceURI());
- }
- if (params.getClaims() != null) {
- client.setClaims(params.getClaims());
- }
- return client.requestSecurityToken(appliesTo);
- }
-
- public static class TokenRequestParams {
- private Element issuer;
- private Trust10 trust10;
- private Trust13 trust13;
- private Element tokenTemplate;
- private String wspNamespace;
- private Element claims;
-
- public Element getIssuer() {
- return issuer;
- }
-
- public void setIssuer(Element issuer) {
- this.issuer = issuer;
- }
-
- public Trust10 getTrust10() {
- return trust10;
- }
-
- public void setTrust10(Trust10 trust10) {
- this.trust10 = trust10;
- }
-
- public Trust13 getTrust13() {
- return trust13;
- }
-
- public void setTrust13(Trust13 trust13) {
- this.trust13 = trust13;
- }
-
- public Element getTokenTemplate() {
- return tokenTemplate;
- }
-
- public void setTokenTemplate(Element tokenTemplate) {
- this.tokenTemplate = tokenTemplate;
- }
-
- public String getWspNamespace() {
- return wspNamespace;
- }
-
- public void setWspNamespace(String wspNamespace) {
- this.wspNamespace = wspNamespace;
- }
-
- public Element getClaims() {
- return claims;
- }
-
- public void setClaims(Element claims) {
- this.claims = claims;
- }
- }
-}
-
-/*
- * STSClient stsClient = new STSClient(bus); stsClient.setServiceQName(new QName(stsProps.get(STS_NAMESPACE),
- * stsProps.get(STS_SERVICE_NAME))); Map<String, Object> props = new HashMap<String, Object>(); for
- * (Map.Entry<String, String> entry : stsProps.entrySet()) { if
- * (SecurityConstants.ALL_PROPERTIES.contains(entry.getKey())) { props.put(entry.getKey(),
- * processFileURI(entry.getValue())); } } stsClient.setProperties(props);
- * stsClient.setWsdlLocation(stsProps.get(STS_WSDL_LOCATION)); stsClient.setEndpointQName(new
- * QName(stsProps.get(STS_NAMESPACE), stsProps.get(STS_ENDPOINT_NAME)));
- * stsClient.setAllowRenewingAfterExpiry(true); stsClient.setEnableLifetime(true);
- * stsClient.setTokenType(SAML2_TOKEN_TYPE); stsClient.setKeyType(BEARER_KEYTYPE); if (token != null) {
- * stsClient.setActAs(token); } token =
- * message.getContextualProperty(SecurityConstants.STS_TOKEN_ON_BEHALF_OF); if (token != null) {
- * stsClient.setOnBehalfOf(token); } Object o =
- * message.getContextualProperty(SecurityConstants.STS_APPLIES_TO); String appliesTo = null == o ? null :
- * o.toString(); appliesTo = null == appliesTo ?
- * message.getContextualProperty(Message.ENDPOINT_ADDRESS).toString() : appliesTo;
- * stsClient.setMessage(message);
- */
http://git-wip-us.apache.org/repos/asf/cxf/blob/9c5f2a65/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSTokenRetriever.java
----------------------------------------------------------------------
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSTokenRetriever.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSTokenRetriever.java
new file mode 100644
index 0000000..5c9c578
--- /dev/null
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSTokenRetriever.java
@@ -0,0 +1,480 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cxf.ws.security.trust;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.w3c.dom.Element;
+
+import org.apache.cxf.common.logging.LogUtils;
+import org.apache.cxf.interceptor.Fault;
+import org.apache.cxf.message.Message;
+import org.apache.cxf.message.MessageUtils;
+import org.apache.cxf.ws.addressing.AddressingProperties;
+import org.apache.cxf.ws.security.SecurityConstants;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils;
+import org.apache.wss4j.common.ext.WSSecurityException;
+import org.apache.wss4j.common.saml.SamlAssertionWrapper;
+import org.apache.wss4j.dom.WSConstants;
+import org.apache.wss4j.policy.model.Trust10;
+import org.apache.wss4j.policy.model.Trust13;
+
+/**
+ * A Helper utility class to cache STS token and issue or renew the token from STS.
+ */
+public final class STSTokenRetriever {
+ private static final Logger LOG = LogUtils.getL7dLogger(STSTokenRetriever.class);
+ private static final String ASSOCIATED_TOKEN =
+ STSTokenRetriever.class.getName() + "-" + "Associated_Token";
+
+ private STSTokenRetriever() {
+ }
+
+ public static SecurityToken getToken(Message message, TokenRequestParams params) {
+ SecurityToken tok = retrieveCachedToken(message);
+ if (tok == null) {
+ tok = issueToken(message, params);
+ } else {
+ tok = renewToken(message, tok, params);
+ }
+
+ boolean cacheIssuedToken =
+ MessageUtils.getContextualBoolean(
+ message,
+ SecurityConstants.CACHE_ISSUED_TOKEN_IN_ENDPOINT,
+ true)
+ && !isOneTimeUse(tok);
+ if (cacheIssuedToken) {
+ message.getExchange().getEndpoint().put(SecurityConstants.TOKEN, tok);
+ message.getExchange().put(SecurityConstants.TOKEN, tok);
+ message.getExchange().put(SecurityConstants.TOKEN_ID, tok.getId());
+ message.getExchange().getEndpoint().put(SecurityConstants.TOKEN_ID,
+ tok.getId());
+ } else {
+ message.put(SecurityConstants.TOKEN, tok);
+ message.put(SecurityConstants.TOKEN_ID, tok.getId());
+ }
+ // ?
+ TokenStoreUtils.getTokenStore(message).add(tok);
+
+ return tok;
+ }
+
+ private static SecurityToken retrieveCachedToken(Message message) {
+ boolean cacheIssuedToken =
+ MessageUtils.getContextualBoolean(
+ message,
+ SecurityConstants.CACHE_ISSUED_TOKEN_IN_ENDPOINT,
+ true);
+ SecurityToken tok = null;
+ if (cacheIssuedToken) {
+ tok = (SecurityToken)message.getContextualProperty(SecurityConstants.TOKEN);
+ if (tok == null) {
+ String tokId = (String)message.getContextualProperty(SecurityConstants.TOKEN_ID);
+ if (tokId != null) {
+ tok = TokenStoreUtils.getTokenStore(message).getToken(tokId);
+ }
+ }
+ } else {
+ tok = (SecurityToken)message.get(SecurityConstants.TOKEN);
+ if (tok == null) {
+ String tokId = (String)message.get(SecurityConstants.TOKEN_ID);
+ if (tokId != null) {
+ tok = TokenStoreUtils.getTokenStore(message).getToken(tokId);
+ }
+ }
+ }
+ return tok;
+ }
+
+ private static SecurityToken issueToken(Message message, TokenRequestParams params) {
+ AddressingProperties maps =
+ (AddressingProperties)message
+ .get("javax.xml.ws.addressing.context.outbound");
+ if (maps == null) {
+ maps = (AddressingProperties)message
+ .get("javax.xml.ws.addressing.context");
+ }
+ STSClient client = STSUtils.getClientWithIssuer(message, "sts", params.getIssuer());
+ synchronized (client) {
+ try {
+ // Transpose ActAs/OnBehalfOf info from original request to the STS client.
+ Object token =
+ message.getContextualProperty(SecurityConstants.STS_TOKEN_ACT_AS);
+ if (token != null) {
+ client.setActAs(token);
+ }
+ token =
+ message.getContextualProperty(SecurityConstants.STS_TOKEN_ON_BEHALF_OF);
+ if (token != null) {
+ client.setOnBehalfOf(token);
+ }
+ Map<String, Object> ctx = client.getRequestContext();
+ mapSecurityProps(message, ctx);
+
+ Object o = message.getContextualProperty(SecurityConstants.STS_APPLIES_TO);
+ String appliesTo = o == null ? null : o.toString();
+ appliesTo = appliesTo == null
+ ? message.getContextualProperty(Message.ENDPOINT_ADDRESS).toString()
+ : appliesTo;
+ boolean enableAppliesTo = client.isEnableAppliesTo();
+
+ client.setMessage(message);
+ Element onBehalfOfToken = client.getOnBehalfOfToken();
+ Element actAsToken = client.getActAsToken();
+
+ SecurityToken secToken =
+ handleDelegation(
+ message, onBehalfOfToken, actAsToken, appliesTo,
+ enableAppliesTo
+ );
+ if (secToken == null) {
+ secToken = getTokenFromSTS(message, client, maps, appliesTo, params);
+ }
+ storeDelegationTokens(
+ message, secToken, onBehalfOfToken, actAsToken, appliesTo,
+ enableAppliesTo);
+ return secToken;
+ } catch (RuntimeException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new Fault(e);
+ } finally {
+ client.setTrust((Trust10)null);
+ client.setTrust((Trust13)null);
+ client.setTemplate(null);
+ client.setAddressingNamespace(null);
+ }
+ }
+ }
+
+ private static SecurityToken renewToken(
+ Message message,
+ SecurityToken tok,
+ TokenRequestParams params) {
+ String imminentExpiryValue =
+ (String)message
+ .getContextualProperty(SecurityConstants.STS_TOKEN_IMMINENT_EXPIRY_VALUE);
+ long imminentExpiry = 10L;
+ if (imminentExpiryValue != null) {
+ imminentExpiry = Long.parseLong(imminentExpiryValue);
+ }
+
+ // If the token has not expired then we don't need to renew it
+ if (!(tok.isExpired() || tok.isAboutToExpire(imminentExpiry))) {
+ return tok;
+ }
+
+ // Remove token from cache
+ message.getExchange().getEndpoint().remove(SecurityConstants.TOKEN);
+ message.getExchange().getEndpoint().remove(SecurityConstants.TOKEN_ID);
+ message.getExchange().remove(SecurityConstants.TOKEN_ID);
+ message.getExchange().remove(SecurityConstants.TOKEN);
+ TokenStoreUtils.getTokenStore(message).remove(tok.getId());
+
+ // If the user has explicitly disabled Renewing then we can't renew a token,
+ // so just get a new one
+ STSClient client = STSUtils.getClientWithIssuer(message, "sts", params.getIssuer());
+ if (!client.isAllowRenewing()) {
+ return issueToken(message, params);
+ }
+
+ AddressingProperties maps =
+ (AddressingProperties)message
+ .get("javax.xml.ws.addressing.context.outbound");
+ if (maps == null) {
+ maps = (AddressingProperties)message
+ .get("javax.xml.ws.addressing.context");
+ }
+ synchronized (client) {
+ try {
+ Map<String, Object> ctx = client.getRequestContext();
+ mapSecurityProps(message, ctx);
+
+ client.setMessage(message);
+
+ if (maps != null) {
+ client.setAddressingNamespace(maps.getNamespaceURI());
+ }
+
+ client.setTrust(params.getTrust10());
+ client.setTrust(params.getTrust13());
+
+ client.setTemplate(params.getTokenTemplate());
+ return client.renewSecurityToken(tok);
+ } catch (RuntimeException ex) {
+ LOG.log(Level.WARNING, "Error renewing a token", ex);
+ boolean issueAfterFailedRenew =
+ MessageUtils
+ .getContextualBoolean(
+ message,
+ SecurityConstants.STS_ISSUE_AFTER_FAILED_RENEW, true);
+ if (issueAfterFailedRenew) {
+ // Perhaps the STS does not support renewing, so try to issue a new token
+ return issueToken(message, params);
+ } else {
+ throw ex;
+ }
+ } catch (Exception ex) {
+ LOG.log(Level.WARNING, "Error renewing a token", ex);
+ boolean issueAfterFailedRenew =
+ MessageUtils
+ .getContextualBoolean(
+ message,
+ SecurityConstants.STS_ISSUE_AFTER_FAILED_RENEW, true);
+ if (issueAfterFailedRenew) {
+ // Perhaps the STS does not support renewing, so try to issue a new token
+ return issueToken(message, params);
+ } else {
+ throw new Fault(ex);
+ }
+ } finally {
+ client.setTrust((Trust10)null);
+ client.setTrust((Trust13)null);
+ client.setTemplate(null);
+ client.setAddressingNamespace(null);
+ }
+ }
+ }
+
+ // Check to see if the received token is a SAML2 Token with "OneTimeUse" set. If so,
+ // it should not be cached on the endpoint, but only on the message.
+ private static boolean isOneTimeUse(SecurityToken issuedToken) {
+ Element token = issuedToken.getToken();
+ if (token != null && "Assertion".equals(token.getLocalName())
+ && WSConstants.SAML2_NS.equals(token.getNamespaceURI())) {
+ try {
+ SamlAssertionWrapper assertion = new SamlAssertionWrapper(token);
+
+ if (assertion.getSaml2().getConditions() != null
+ && assertion.getSaml2().getConditions().getOneTimeUse() != null) {
+ return true;
+ }
+ } catch (WSSecurityException ex) {
+ throw new Fault(ex);
+ }
+ }
+
+ return false;
+ }
+
+ private static void mapSecurityProps(Message message, Map<String, Object> ctx) {
+ for (String s : SecurityConstants.ALL_PROPERTIES) {
+ Object v = message.getContextualProperty(s + ".it");
+ if (v == null) {
+ v = message.getContextualProperty(s);
+ }
+ if (!ctx.containsKey(s) && v != null) {
+ ctx.put(s, v);
+ }
+ }
+ }
+
+ /**
+ * Parse ActAs/OnBehalfOf appropriately. See if the required token is stored in the cache.
+ */
+ private static SecurityToken handleDelegation(
+ Message message,
+ Element onBehalfOfToken,
+ Element actAsToken,
+ String appliesTo,
+ boolean enableAppliesTo) throws Exception {
+ TokenStore tokenStore = TokenStoreUtils.getTokenStore(message);
+ String key = appliesTo;
+ if (!enableAppliesTo || key == null || "".equals(key)) {
+ key = ASSOCIATED_TOKEN;
+ }
+ // See if the token corresponding to the OnBehalfOf Token is stored in the cache
+ // and if it points to an issued token
+ if (onBehalfOfToken != null) {
+ String id = getIdFromToken(onBehalfOfToken);
+ SecurityToken cachedToken = tokenStore.getToken(id);
+ if (cachedToken != null) {
+ Map<String, Object> properties = cachedToken.getProperties();
+ if (properties != null && properties.containsKey(key)) {
+ String associatedToken = (String)properties.get(key);
+ SecurityToken issuedToken = tokenStore.getToken(associatedToken);
+ if (issuedToken != null) {
+ return issuedToken;
+ }
+ }
+ }
+ }
+
+ // See if the token corresponding to the ActAs Token is stored in the cache
+ // and if it points to an issued token
+ if (actAsToken != null) {
+ String id = getIdFromToken(actAsToken);
+ SecurityToken cachedToken = tokenStore.getToken(id);
+ if (cachedToken != null) {
+ Map<String, Object> properties = cachedToken.getProperties();
+ if (properties != null && properties.containsKey(key)) {
+ String associatedToken = (String)properties.get(key);
+ SecurityToken issuedToken = tokenStore.getToken(associatedToken);
+ if (issuedToken != null) {
+ return issuedToken;
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ private static String getIdFromToken(Element token) {
+ if (token != null) {
+ // Try to find the "Id" on the token.
+ if (token.hasAttributeNS(WSConstants.WSU_NS, "Id")) {
+ return token.getAttributeNS(WSConstants.WSU_NS, "Id");
+ } else if (token.hasAttributeNS(null, "ID")) {
+ return token.getAttributeNS(null, "ID");
+ } else if (token.hasAttributeNS(null, "AssertionID")) {
+ return token.getAttributeNS(null, "AssertionID");
+ }
+ }
+ return "";
+ }
+
+ private static void storeDelegationTokens(
+ Message message,
+ SecurityToken issuedToken,
+ Element onBehalfOfToken,
+ Element actAsToken,
+ String appliesTo,
+ boolean enableAppliesTo) throws Exception {
+ if (issuedToken == null) {
+ return;
+ }
+ TokenStore tokenStore = TokenStoreUtils.getTokenStore(message);
+ String key = appliesTo;
+ if (!enableAppliesTo || key == null || "".equals(key)) {
+ key = ASSOCIATED_TOKEN;
+ }
+ if (onBehalfOfToken != null) {
+ String id = getIdFromToken(onBehalfOfToken);
+ SecurityToken cachedToken = tokenStore.getToken(id);
+ if (cachedToken == null) {
+ cachedToken = new SecurityToken(id);
+ cachedToken.setToken(onBehalfOfToken);
+ }
+ Map<String, Object> properties = cachedToken.getProperties();
+ if (properties == null) {
+ properties = new HashMap<>();
+ cachedToken.setProperties(properties);
+ }
+ properties.put(key, issuedToken.getId());
+ tokenStore.add(cachedToken);
+ }
+ if (actAsToken != null) {
+ String id = getIdFromToken(actAsToken);
+ SecurityToken cachedToken = tokenStore.getToken(id);
+ if (cachedToken == null) {
+ cachedToken = new SecurityToken(id);
+ cachedToken.setToken(actAsToken);
+ }
+ Map<String, Object> properties = cachedToken.getProperties();
+ if (properties == null) {
+ properties = new HashMap<>();
+ cachedToken.setProperties(properties);
+ }
+ properties.put(key, issuedToken.getId());
+ tokenStore.add(cachedToken);
+ }
+ }
+
+ private static SecurityToken getTokenFromSTS(Message message, STSClient client,
+ AddressingProperties maps, String appliesTo,
+ TokenRequestParams params) throws Exception {
+ client.setTrust(params.getTrust10());
+ client.setTrust(params.getTrust13());
+ client.setTemplate(params.getTokenTemplate());
+ if (params.getWspNamespace() != null) {
+ client.setWspNamespace(params.getWspNamespace());
+ }
+ if (maps != null && maps.getNamespaceURI() != null) {
+ client.setAddressingNamespace(maps.getNamespaceURI());
+ }
+ if (params.getClaims() != null) {
+ client.setClaims(params.getClaims());
+ }
+ return client.requestSecurityToken(appliesTo);
+ }
+
+ public static class TokenRequestParams {
+ private Element issuer;
+ private Trust10 trust10;
+ private Trust13 trust13;
+ private Element tokenTemplate;
+ private String wspNamespace;
+ private Element claims;
+
+ public Element getIssuer() {
+ return issuer;
+ }
+
+ public void setIssuer(Element issuer) {
+ this.issuer = issuer;
+ }
+
+ public Trust10 getTrust10() {
+ return trust10;
+ }
+
+ public void setTrust10(Trust10 trust10) {
+ this.trust10 = trust10;
+ }
+
+ public Trust13 getTrust13() {
+ return trust13;
+ }
+
+ public void setTrust13(Trust13 trust13) {
+ this.trust13 = trust13;
+ }
+
+ public Element getTokenTemplate() {
+ return tokenTemplate;
+ }
+
+ public void setTokenTemplate(Element tokenTemplate) {
+ this.tokenTemplate = tokenTemplate;
+ }
+
+ public String getWspNamespace() {
+ return wspNamespace;
+ }
+
+ public void setWspNamespace(String wspNamespace) {
+ this.wspNamespace = wspNamespace;
+ }
+
+ public Element getClaims() {
+ return claims;
+ }
+
+ public void setClaims(Element claims) {
+ this.claims = claims;
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/cxf/blob/9c5f2a65/services/sts/systests/basic/src/test/java/org/apache/cxf/systest/sts/stsclient/STSTokenHelperTest.java
----------------------------------------------------------------------
diff --git a/services/sts/systests/basic/src/test/java/org/apache/cxf/systest/sts/stsclient/STSTokenHelperTest.java b/services/sts/systests/basic/src/test/java/org/apache/cxf/systest/sts/stsclient/STSTokenHelperTest.java
deleted file mode 100644
index d349f07..0000000
--- a/services/sts/systests/basic/src/test/java/org/apache/cxf/systest/sts/stsclient/STSTokenHelperTest.java
+++ /dev/null
@@ -1,273 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cxf.systest.sts.stsclient;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.KeyManagementException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.BusFactory;
-import org.apache.cxf.configuration.jsse.TLSClientParameters;
-import org.apache.cxf.endpoint.Endpoint;
-import org.apache.cxf.endpoint.EndpointException;
-import org.apache.cxf.endpoint.EndpointImpl;
-import org.apache.cxf.interceptor.LoggingInInterceptor;
-import org.apache.cxf.interceptor.LoggingOutInterceptor;
-import org.apache.cxf.message.Exchange;
-import org.apache.cxf.message.ExchangeImpl;
-import org.apache.cxf.message.Message;
-import org.apache.cxf.message.MessageImpl;
-import org.apache.cxf.service.Service;
-import org.apache.cxf.service.ServiceImpl;
-import org.apache.cxf.service.model.BindingInfo;
-import org.apache.cxf.service.model.EndpointInfo;
-import org.apache.cxf.service.model.ServiceInfo;
-import org.apache.cxf.systest.sts.common.SecurityTestUtil;
-import org.apache.cxf.systest.sts.deployment.STSServer;
-import org.apache.cxf.testutil.common.AbstractBusClientServerTestBase;
-import org.apache.cxf.transport.http.HTTPConduit;
-import org.apache.cxf.ws.security.SecurityConstants;
-import org.apache.cxf.ws.security.policy.interceptors.STSTokenHelper;
-import org.apache.cxf.ws.security.tokenstore.SecurityToken;
-import org.apache.cxf.ws.security.trust.STSClient;
-
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-/**
- * Some tests for STSClient configuration.
- */
-public class STSTokenHelperTest extends AbstractBusClientServerTestBase {
- static final String STSPORT = allocatePort(STSServer.class);
- static final String STSPORT2 = allocatePort(STSServer.class, 2);
-
- private static final String STS_SERVICE_NAME =
- "{http://docs.oasis-open.org/ws-sx/ws-trust/200512/}SecurityTokenService";
- private static final String TOKEN_TYPE_SAML_2_0 =
- "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0";
-
- private static final String SERVICE_ENDPOINT_ASSYMETRIC =
- "http://localhost:8081/doubleit/services/doubleitasymmetric";
- private static final String STS_X509_WSDL_LOCATION_RELATIVE = "/SecurityTokenService/X509?wsdl";
- private static final String STS_X509_ENDPOINT_NAME = "{http://docs.oasis-open.org/ws-sx/ws-trust/200512/}X509_Port";
- private static final String KEY_TYPE_X509 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/PublicKey";
-
- private static final String SERVICE_ENDPOINT_TRANSPORT =
- "https://localhost:8081/doubleit/services/doubleittransportsaml1";
- private static final String STS_TRANSPORT_WSDL_LOCATION_RELATIVE = "/SecurityTokenService/Transport?wsdl";
- private static final String STS_TRANSPORT_ENDPOINT_NAME =
- "{http://docs.oasis-open.org/ws-sx/ws-trust/200512/}Transport_Port";
-
- private static final String CLIENTSTORE = "/clientstore.jks";
- private static final String KEYSTORE_PASS = "cspass";
- private static final String KEY_PASS = "ckpass";
-
- @BeforeClass
- public static void startServers() throws Exception {
- assertTrue(
- "Server failed to launch",
- // run the server in the same process
- // set this to false to fork
- launchServer(STSServer.class, true)
- );
- }
-
- @AfterClass
- public static void cleanup() throws Exception {
- SecurityTestUtil.cleanup();
- stopAllServers();
- }
-
- @Test
- public void testSTSAsymmetricBinding() throws Exception {
- Bus bus = BusFactory.getThreadDefaultBus();
- STSClient stsClient = initStsClientAsymmeticBinding(bus);
-
- MessageImpl message = prepareMessage(bus, stsClient, SERVICE_ENDPOINT_ASSYMETRIC);
- STSTokenHelper.TokenRequestParams params = new STSTokenHelper.TokenRequestParams();
-
- SecurityToken token = STSTokenHelper.getToken(message, params);
- validateSecurityToken(token);
- }
-
- @Test
- public void testSTSTransportBinding() throws Exception {
- // Setup HttpsURLConnection to get STS WSDL
- configureDefaultHttpsConnection();
-
- Bus bus = BusFactory.getThreadDefaultBus();
- STSClient stsClient = initStsClientTransportBinding(bus);
-
- TLSClientParameters tlsParams = prepareTLSParams();
- ((HTTPConduit)stsClient.getClient().getConduit()).setTlsClientParameters(tlsParams);
-
- MessageImpl message = prepareMessage(bus, stsClient, SERVICE_ENDPOINT_TRANSPORT);
- STSTokenHelper.TokenRequestParams params = new STSTokenHelper.TokenRequestParams();
-
- SecurityToken token = STSTokenHelper.getToken(message, params);
- validateSecurityToken(token);
- }
-
- private STSClient initStsClientAsymmeticBinding(Bus bus) {
- bus.getInInterceptors().add(new LoggingOutInterceptor());
- bus.getOutInterceptors().add(new LoggingInInterceptor());
- bus.getOutFaultInterceptors().add(new LoggingInInterceptor());
-
- STSClient stsClient = new STSClient(bus);
- stsClient.setWsdlLocation("http://localhost:" + STSPORT2 + STS_X509_WSDL_LOCATION_RELATIVE);
- stsClient.setServiceName(STS_SERVICE_NAME);
- stsClient.setEndpointName(STS_X509_ENDPOINT_NAME);
- stsClient.setTokenType(TOKEN_TYPE_SAML_2_0);
- stsClient.setKeyType(KEY_TYPE_X509);
- stsClient.setAllowRenewingAfterExpiry(true);
- stsClient.setEnableLifetime(true);
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(SecurityConstants.USERNAME, "alice");
- props.put(SecurityConstants.CALLBACK_HANDLER, "org.apache.cxf.systest.sts.common.CommonCallbackHandler");
- props.put(SecurityConstants.ENCRYPT_USERNAME, "mystskey");
- props.put(SecurityConstants.ENCRYPT_PROPERTIES, "clientKeystore.properties");
- props.put(SecurityConstants.SIGNATURE_PROPERTIES, "clientKeystore.properties");
- props.put(SecurityConstants.STS_TOKEN_USERNAME, "mystskey");
- props.put(SecurityConstants.STS_TOKEN_PROPERTIES, "clientKeystore.properties");
- props.put(SecurityConstants.STS_TOKEN_USE_CERT_FOR_KEYINFO, "true");
- props.put(SecurityConstants.IS_BSP_COMPLIANT, "false");
- stsClient.setProperties(props);
- return stsClient;
- }
-
- private STSClient initStsClientTransportBinding(Bus bus) {
- bus.getInInterceptors().add(new LoggingOutInterceptor());
- bus.getOutInterceptors().add(new LoggingInInterceptor());
- bus.getOutFaultInterceptors().add(new LoggingInInterceptor());
-
- STSClient stsClient = new STSClient(bus);
- stsClient.setWsdlLocation("https://localhost:" + STSPORT + STS_TRANSPORT_WSDL_LOCATION_RELATIVE);
- stsClient.setServiceName(STS_SERVICE_NAME);
- stsClient.setEndpointName(STS_TRANSPORT_ENDPOINT_NAME);
- stsClient.setTokenType(TOKEN_TYPE_SAML_2_0);
- stsClient.setAllowRenewingAfterExpiry(true);
- stsClient.setEnableLifetime(true);
-
- Map<String, Object> props = new HashMap<String, Object>();
- props.put(SecurityConstants.USERNAME, "alice");
- props.put(SecurityConstants.CALLBACK_HANDLER, "org.apache.cxf.systest.sts.common.CommonCallbackHandler");
- props.put(SecurityConstants.STS_TOKEN_USERNAME, "mystskey");
- props.put(SecurityConstants.STS_TOKEN_PROPERTIES, "clientKeystore.properties");
- props.put(SecurityConstants.STS_TOKEN_USE_CERT_FOR_KEYINFO, "true");
- props.put(SecurityConstants.IS_BSP_COMPLIANT, "false");
- stsClient.setProperties(props);
- return stsClient;
- }
-
- private MessageImpl prepareMessage(Bus bus, STSClient stsClient, String serviceAddress) throws EndpointException {
- MessageImpl message = new MessageImpl();
- message.put(SecurityConstants.STS_CLIENT, stsClient);
- message.put(Message.ENDPOINT_ADDRESS, serviceAddress);
-
- Exchange exchange = new ExchangeImpl();
- ServiceInfo si = new ServiceInfo();
- Service s = new ServiceImpl(si);
- EndpointInfo ei = new EndpointInfo();
- Endpoint ep = new EndpointImpl(bus, s, ei);
- ei.setBinding(new BindingInfo(si, null));
- message.setExchange(exchange);
- exchange.put(Endpoint.class, ep);
- return message;
- }
-
- private void configureDefaultHttpsConnection() throws NoSuchAlgorithmException, KeyStoreException,
- CertificateException, IOException, KeyManagementException {
- // For localhost testing only
- javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
-
- public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
- return "localhost".equals(hostname);
- }
- });
-
- TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory
- .getDefaultAlgorithm());
- KeyStore keyStore = loadClientKeystore();
- trustManagerFactory.init(keyStore);
- TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
- SSLContext sc = SSLContext.getInstance("SSL");
- sc.init(null, trustManagers, new java.security.SecureRandom());
- HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
- }
-
- private TLSClientParameters prepareTLSParams() throws KeyStoreException, IOException,
- NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
- TLSClientParameters tlsParams = new TLSClientParameters();
- tlsParams.setDisableCNCheck(true);
- KeyStore trustStore = loadClientKeystore();
-
- TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory
- .getDefaultAlgorithm());
- trustFactory.init(trustStore);
- TrustManager[] tm = trustFactory.getTrustManagers();
- tlsParams.setTrustManagers(tm);
-
- KeyStore keyStore = loadClientKeystore();
- KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
- keyFactory.init(keyStore, KEY_PASS.toCharArray());
- KeyManager[] km = keyFactory.getKeyManagers();
- tlsParams.setKeyManagers(km);
- return tlsParams;
- }
-
- private KeyStore loadClientKeystore() throws KeyStoreException, IOException, NoSuchAlgorithmException,
- CertificateException {
- KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
- InputStream keystoreStream = STSTokenHelperTest.class.getResourceAsStream(CLIENTSTORE);
- try {
- keystore.load(keystoreStream, KEYSTORE_PASS.toCharArray());
- } finally {
- keystoreStream.close();
- }
- return keystore;
- }
-
- private void validateSecurityToken(SecurityToken token) {
- Assert.assertNotNull(token);
- Assert.assertEquals(TOKEN_TYPE_SAML_2_0, token.getTokenType());
- Assert.assertNotNull(token.getId());
- Assert.assertTrue(token.getExpires().after(new Date()));
- Assert.assertEquals("Assertion", token.getToken().getLocalName());
- }
-
-}
http://git-wip-us.apache.org/repos/asf/cxf/blob/9c5f2a65/services/sts/systests/basic/src/test/java/org/apache/cxf/systest/sts/stsclient/STSTokenRetrieverTest.java
----------------------------------------------------------------------
diff --git a/services/sts/systests/basic/src/test/java/org/apache/cxf/systest/sts/stsclient/STSTokenRetrieverTest.java b/services/sts/systests/basic/src/test/java/org/apache/cxf/systest/sts/stsclient/STSTokenRetrieverTest.java
new file mode 100644
index 0000000..0f924c1
--- /dev/null
+++ b/services/sts/systests/basic/src/test/java/org/apache/cxf/systest/sts/stsclient/STSTokenRetrieverTest.java
@@ -0,0 +1,273 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.cxf.systest.sts.stsclient;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.CertificateException;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+
+import org.apache.cxf.Bus;
+import org.apache.cxf.BusFactory;
+import org.apache.cxf.configuration.jsse.TLSClientParameters;
+import org.apache.cxf.endpoint.Endpoint;
+import org.apache.cxf.endpoint.EndpointException;
+import org.apache.cxf.endpoint.EndpointImpl;
+import org.apache.cxf.interceptor.LoggingInInterceptor;
+import org.apache.cxf.interceptor.LoggingOutInterceptor;
+import org.apache.cxf.message.Exchange;
+import org.apache.cxf.message.ExchangeImpl;
+import org.apache.cxf.message.Message;
+import org.apache.cxf.message.MessageImpl;
+import org.apache.cxf.service.Service;
+import org.apache.cxf.service.ServiceImpl;
+import org.apache.cxf.service.model.BindingInfo;
+import org.apache.cxf.service.model.EndpointInfo;
+import org.apache.cxf.service.model.ServiceInfo;
+import org.apache.cxf.systest.sts.common.SecurityTestUtil;
+import org.apache.cxf.systest.sts.deployment.STSServer;
+import org.apache.cxf.testutil.common.AbstractBusClientServerTestBase;
+import org.apache.cxf.transport.http.HTTPConduit;
+import org.apache.cxf.ws.security.SecurityConstants;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.cxf.ws.security.trust.STSClient;
+import org.apache.cxf.ws.security.trust.STSTokenRetriever;
+
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+/**
+ * Some tests for STSClient configuration.
+ */
+public class STSTokenRetrieverTest extends AbstractBusClientServerTestBase {
+ static final String STSPORT = allocatePort(STSServer.class);
+ static final String STSPORT2 = allocatePort(STSServer.class, 2);
+
+ private static final String STS_SERVICE_NAME =
+ "{http://docs.oasis-open.org/ws-sx/ws-trust/200512/}SecurityTokenService";
+ private static final String TOKEN_TYPE_SAML_2_0 =
+ "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0";
+
+ private static final String SERVICE_ENDPOINT_ASSYMETRIC =
+ "http://localhost:8081/doubleit/services/doubleitasymmetric";
+ private static final String STS_X509_WSDL_LOCATION_RELATIVE = "/SecurityTokenService/X509?wsdl";
+ private static final String STS_X509_ENDPOINT_NAME = "{http://docs.oasis-open.org/ws-sx/ws-trust/200512/}X509_Port";
+ private static final String KEY_TYPE_X509 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/PublicKey";
+
+ private static final String SERVICE_ENDPOINT_TRANSPORT =
+ "https://localhost:8081/doubleit/services/doubleittransportsaml1";
+ private static final String STS_TRANSPORT_WSDL_LOCATION_RELATIVE = "/SecurityTokenService/Transport?wsdl";
+ private static final String STS_TRANSPORT_ENDPOINT_NAME =
+ "{http://docs.oasis-open.org/ws-sx/ws-trust/200512/}Transport_Port";
+
+ private static final String CLIENTSTORE = "/clientstore.jks";
+ private static final String KEYSTORE_PASS = "cspass";
+ private static final String KEY_PASS = "ckpass";
+
+ @BeforeClass
+ public static void startServers() throws Exception {
+ assertTrue(
+ "Server failed to launch",
+ // run the server in the same process
+ // set this to false to fork
+ launchServer(STSServer.class, true)
+ );
+ }
+
+ @AfterClass
+ public static void cleanup() throws Exception {
+ SecurityTestUtil.cleanup();
+ stopAllServers();
+ }
+
+ @Test
+ public void testSTSAsymmetricBinding() throws Exception {
+ Bus bus = BusFactory.getThreadDefaultBus();
+ STSClient stsClient = initStsClientAsymmeticBinding(bus);
+
+ MessageImpl message = prepareMessage(bus, stsClient, SERVICE_ENDPOINT_ASSYMETRIC);
+ STSTokenRetriever.TokenRequestParams params = new STSTokenRetriever.TokenRequestParams();
+
+ SecurityToken token = STSTokenRetriever.getToken(message, params);
+ validateSecurityToken(token);
+ }
+
+ @Test
+ public void testSTSTransportBinding() throws Exception {
+ // Setup HttpsURLConnection to get STS WSDL
+ configureDefaultHttpsConnection();
+
+ Bus bus = BusFactory.getThreadDefaultBus();
+ STSClient stsClient = initStsClientTransportBinding(bus);
+
+ TLSClientParameters tlsParams = prepareTLSParams();
+ ((HTTPConduit)stsClient.getClient().getConduit()).setTlsClientParameters(tlsParams);
+
+ MessageImpl message = prepareMessage(bus, stsClient, SERVICE_ENDPOINT_TRANSPORT);
+ STSTokenRetriever.TokenRequestParams params = new STSTokenRetriever.TokenRequestParams();
+
+ SecurityToken token = STSTokenRetriever.getToken(message, params);
+ validateSecurityToken(token);
+ }
+
+ private STSClient initStsClientAsymmeticBinding(Bus bus) {
+ bus.getInInterceptors().add(new LoggingOutInterceptor());
+ bus.getOutInterceptors().add(new LoggingInInterceptor());
+ bus.getOutFaultInterceptors().add(new LoggingInInterceptor());
+
+ STSClient stsClient = new STSClient(bus);
+ stsClient.setWsdlLocation("http://localhost:" + STSPORT2 + STS_X509_WSDL_LOCATION_RELATIVE);
+ stsClient.setServiceName(STS_SERVICE_NAME);
+ stsClient.setEndpointName(STS_X509_ENDPOINT_NAME);
+ stsClient.setTokenType(TOKEN_TYPE_SAML_2_0);
+ stsClient.setKeyType(KEY_TYPE_X509);
+ stsClient.setAllowRenewingAfterExpiry(true);
+ stsClient.setEnableLifetime(true);
+
+ Map<String, Object> props = new HashMap<String, Object>();
+ props.put(SecurityConstants.USERNAME, "alice");
+ props.put(SecurityConstants.CALLBACK_HANDLER, "org.apache.cxf.systest.sts.common.CommonCallbackHandler");
+ props.put(SecurityConstants.ENCRYPT_USERNAME, "mystskey");
+ props.put(SecurityConstants.ENCRYPT_PROPERTIES, "clientKeystore.properties");
+ props.put(SecurityConstants.SIGNATURE_PROPERTIES, "clientKeystore.properties");
+ props.put(SecurityConstants.STS_TOKEN_USERNAME, "mystskey");
+ props.put(SecurityConstants.STS_TOKEN_PROPERTIES, "clientKeystore.properties");
+ props.put(SecurityConstants.STS_TOKEN_USE_CERT_FOR_KEYINFO, "true");
+ props.put(SecurityConstants.IS_BSP_COMPLIANT, "false");
+ stsClient.setProperties(props);
+ return stsClient;
+ }
+
+ private STSClient initStsClientTransportBinding(Bus bus) {
+ bus.getInInterceptors().add(new LoggingOutInterceptor());
+ bus.getOutInterceptors().add(new LoggingInInterceptor());
+ bus.getOutFaultInterceptors().add(new LoggingInInterceptor());
+
+ STSClient stsClient = new STSClient(bus);
+ stsClient.setWsdlLocation("https://localhost:" + STSPORT + STS_TRANSPORT_WSDL_LOCATION_RELATIVE);
+ stsClient.setServiceName(STS_SERVICE_NAME);
+ stsClient.setEndpointName(STS_TRANSPORT_ENDPOINT_NAME);
+ stsClient.setTokenType(TOKEN_TYPE_SAML_2_0);
+ stsClient.setAllowRenewingAfterExpiry(true);
+ stsClient.setEnableLifetime(true);
+
+ Map<String, Object> props = new HashMap<String, Object>();
+ props.put(SecurityConstants.USERNAME, "alice");
+ props.put(SecurityConstants.CALLBACK_HANDLER, "org.apache.cxf.systest.sts.common.CommonCallbackHandler");
+ props.put(SecurityConstants.STS_TOKEN_USERNAME, "mystskey");
+ props.put(SecurityConstants.STS_TOKEN_PROPERTIES, "clientKeystore.properties");
+ props.put(SecurityConstants.STS_TOKEN_USE_CERT_FOR_KEYINFO, "true");
+ props.put(SecurityConstants.IS_BSP_COMPLIANT, "false");
+ stsClient.setProperties(props);
+ return stsClient;
+ }
+
+ private MessageImpl prepareMessage(Bus bus, STSClient stsClient, String serviceAddress) throws EndpointException {
+ MessageImpl message = new MessageImpl();
+ message.put(SecurityConstants.STS_CLIENT, stsClient);
+ message.put(Message.ENDPOINT_ADDRESS, serviceAddress);
+
+ Exchange exchange = new ExchangeImpl();
+ ServiceInfo si = new ServiceInfo();
+ Service s = new ServiceImpl(si);
+ EndpointInfo ei = new EndpointInfo();
+ Endpoint ep = new EndpointImpl(bus, s, ei);
+ ei.setBinding(new BindingInfo(si, null));
+ message.setExchange(exchange);
+ exchange.put(Endpoint.class, ep);
+ return message;
+ }
+
+ private void configureDefaultHttpsConnection() throws NoSuchAlgorithmException, KeyStoreException,
+ CertificateException, IOException, KeyManagementException {
+ // For localhost testing only
+ javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
+
+ public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
+ return "localhost".equals(hostname);
+ }
+ });
+
+ TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory
+ .getDefaultAlgorithm());
+ KeyStore keyStore = loadClientKeystore();
+ trustManagerFactory.init(keyStore);
+ TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
+ SSLContext sc = SSLContext.getInstance("SSL");
+ sc.init(null, trustManagers, new java.security.SecureRandom());
+ HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
+ }
+
+ private TLSClientParameters prepareTLSParams() throws KeyStoreException, IOException,
+ NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
+ TLSClientParameters tlsParams = new TLSClientParameters();
+ tlsParams.setDisableCNCheck(true);
+ KeyStore trustStore = loadClientKeystore();
+
+ TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory
+ .getDefaultAlgorithm());
+ trustFactory.init(trustStore);
+ TrustManager[] tm = trustFactory.getTrustManagers();
+ tlsParams.setTrustManagers(tm);
+
+ KeyStore keyStore = loadClientKeystore();
+ KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+ keyFactory.init(keyStore, KEY_PASS.toCharArray());
+ KeyManager[] km = keyFactory.getKeyManagers();
+ tlsParams.setKeyManagers(km);
+ return tlsParams;
+ }
+
+ private KeyStore loadClientKeystore() throws KeyStoreException, IOException, NoSuchAlgorithmException,
+ CertificateException {
+ KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
+ InputStream keystoreStream = STSTokenRetrieverTest.class.getResourceAsStream(CLIENTSTORE);
+ try {
+ keystore.load(keystoreStream, KEYSTORE_PASS.toCharArray());
+ } finally {
+ keystoreStream.close();
+ }
+ return keystore;
+ }
+
+ private void validateSecurityToken(SecurityToken token) {
+ Assert.assertNotNull(token);
+ Assert.assertEquals(TOKEN_TYPE_SAML_2_0, token.getTokenType());
+ Assert.assertNotNull(token.getId());
+ Assert.assertTrue(token.getExpires().after(new Date()));
+ Assert.assertEquals("Assertion", token.getToken().getLocalName());
+ }
+
+}