001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common Development
008: * and Distribution License("CDDL") (collectively, the "License"). You
009: * may not use this file except in compliance with the License. You can obtain
010: * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
011: * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
012: * language governing permissions and limitations under the License.
013: *
014: * When distributing the software, include this License Header Notice in each
015: * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
016: * Sun designates this particular file as subject to the "Classpath" exception
017: * as provided by Sun in the GPL Version 2 section of the License file that
018: * accompanied this code. If applicable, add the following below the License
019: * Header, with the fields enclosed by brackets [] replaced by your own
020: * identifying information: "Portions Copyrighted [year]
021: * [name of copyright owner]"
022: *
023: * Contributor(s):
024: *
025: * If you wish your version of this file to be governed by only the CDDL or
026: * only the GPL Version 2, indicate your decision by adding "[Contributor]
027: * elects to include this software in this distribution under the [CDDL or GPL
028: * Version 2] license." If you don't indicate a single choice of license, a
029: * recipient has the option to distribute your version of this file under
030: * either the CDDL, the GPL Version 2 or to extend the choice of license to
031: * its licensees as provided above. However, if you add GPL Version 2 code
032: * and therefore, elected the GPL Version 2 license, then the option applies
033: * only if the new code is made subject to such option by the copyright
034: * holder.
035: */
036:
037: /*
038: * TrustPluginImpl.java
039: *
040: * Created on January 2, 2006, 10:57 AM
041: *
042: * To change this template, choose Tools | Template Manager
043: * and open the template in the editor.
044: */
045:
046: package com.sun.xml.ws.security.trust.impl;
047:
048: import com.sun.xml.ws.api.security.trust.Claims;
049: import com.sun.xml.ws.api.security.trust.WSTrustException;
050: import com.sun.xml.ws.addressing.policy.Address;
051: import com.sun.xml.ws.mex.client.MetadataClient;
052: import com.sun.xml.ws.mex.client.PortInfo;
053: import com.sun.xml.ws.mex.client.schema.Metadata;
054: import com.sun.xml.ws.policy.AssertionSet;
055: import com.sun.xml.ws.policy.impl.bindings.AppliesTo;
056: import com.sun.xml.ws.policy.Policy;
057: import com.sun.xml.ws.policy.PolicyAssertion;
058: import com.sun.xml.ws.policy.sourcemodel.PolicyModelGenerator;
059: import com.sun.xml.ws.policy.sourcemodel.PolicySourceModel;
060: import com.sun.xml.ws.policy.sourcemodel.XmlPolicyModelMarshaller;
061: import com.sun.xml.ws.security.IssuedTokenContext;
062: import com.sun.xml.ws.security.impl.IssuedTokenContextImpl;
063: import com.sun.xml.ws.security.impl.policy.PolicyUtil;
064: import com.sun.xml.ws.security.policy.IssuedToken;
065: import com.sun.xml.ws.security.policy.Issuer;
066: import com.sun.xml.ws.security.policy.RequestSecurityTokenTemplate;
067: import com.sun.xml.ws.security.trust.*;
068: import com.sun.xml.ws.security.trust.elements.BinarySecret;
069: import com.sun.xml.ws.security.trust.elements.Entropy;
070: import com.sun.xml.ws.security.trust.elements.Lifetime;
071: import com.sun.xml.ws.security.trust.elements.RequestSecurityToken;
072: import com.sun.xml.ws.security.trust.elements.RequestSecurityTokenResponse;
073: import com.sun.xml.ws.security.trust.impl.bindings.ClaimsType;
074: import com.sun.xml.ws.security.trust.impl.bindings.ObjectFactory;
075: import com.sun.xml.ws.security.trust.impl.bindings.RequestSecurityTokenResponseType;
076: import com.sun.xml.ws.security.trust.impl.bindings.RequestSecurityTokenType;
077: import com.sun.xml.ws.security.trust.impl.elements.ClaimsImpl;
078: import com.sun.xml.ws.security.trust.util.WSTrustUtil;
079: import java.io.ByteArrayInputStream;
080: import java.io.ByteArrayOutputStream;
081: import java.net.URI;
082: import java.net.URL;
083: import java.net.URISyntaxException;
084: import java.net.MalformedURLException;
085: import java.rmi.RemoteException;
086: import java.security.SecureRandom;
087: import java.util.ArrayList;
088: import java.util.Arrays;
089: import java.util.Collection;
090: import java.util.Iterator;
091: import java.util.List;
092: import java.util.Map;
093: import java.util.Set;
094: import javax.xml.bind.util.JAXBResult;
095: import javax.xml.namespace.QName;
096: import javax.xml.parsers.DocumentBuilder;
097: import javax.xml.parsers.DocumentBuilderFactory;
098: import javax.xml.stream.XMLOutputFactory;
099: import javax.xml.stream.XMLStreamWriter;
100: import javax.xml.transform.dom.DOMResult;
101: import javax.xml.ws.Dispatch;
102: import javax.xml.ws.RespectBindingFeature;
103: import javax.xml.ws.Service;
104: import javax.xml.ws.WebServiceException;
105: import javax.xml.ws.WebServiceFeature;
106: import javax.xml.bind.JAXBElement;
107:
108: import java.util.logging.Level;
109: import java.util.logging.Logger;
110: import com.sun.xml.ws.security.trust.logging.LogDomainConstants;
111:
112: import javax.xml.ws.soap.AddressingFeature;
113:
114: import com.sun.xml.ws.security.trust.logging.LogStringsMessages;
115: import org.w3c.dom.Document;
116:
117: import org.w3c.dom.Element;
118:
119: import com.sun.xml.ws.api.security.trust.client.STSIssuedTokenConfiguration;
120:
121: /**
122: *
123: * @author hr124446
124: */
125: public class TrustPluginImpl implements TrustPlugin {
126:
127: private static final Logger log = Logger.getLogger(
128: LogDomainConstants.TRUST_IMPL_DOMAIN,
129: LogDomainConstants.TRUST_IMPL_DOMAIN_BUNDLE);
130:
131: private final Configuration config;
132: private static WSTrustElementFactory fact = WSTrustElementFactory
133: .newInstance();
134:
135: private static final String PRE_CONFIGURED_STS = "PreconfiguredSTS";
136: private static final String NAMESPACE = "namespace";
137: private static final String CONFIG_NAMESPACE = "";
138: private static final String ENDPOINT = "endPoint";
139: private static final String METADATA = "metadata";
140: private static final String WSDL_LOCATION = "wsdlLocation";
141: private static final String SERVICE_NAME = "serviceName";
142: private static final String PORT_NAME = "portName";
143: private static final String REQUEST_SECURITY_TOKEN_TEMPLATE = "RequestSecurityTokenTemplate";
144: private static final String CLAIMS = "Claims";
145: private static final String DIALECT = "Dialect";
146:
147: /** Creates a new instance of TrustPluginImpl */
148: public TrustPluginImpl(Configuration config) {
149: this .config = config;
150: }
151:
152: public void process(IssuedTokenContext itc) throws WSTrustException {
153: String appliesTo = itc.getEndpointAddress();
154: STSIssuedTokenConfiguration stsConfig = (STSIssuedTokenConfiguration) itc
155: .getSecurityPolicy().get(0);
156: String stsURI = stsConfig.getSTSEndpoint();
157: if (stsURI == null) {
158: log.log(Level.SEVERE, LogStringsMessages
159: .WST_0029_COULD_NOT_GET_STS_LOCATION(appliesTo));
160: throw new WebServiceException(LogStringsMessages
161: .WST_0029_COULD_NOT_GET_STS_LOCATION(appliesTo));
162: }
163:
164: URI wsdlLocation = null;
165: QName serviceName = null;
166: QName portName = null;
167:
168: final String metadataStr = stsConfig.getSTSMEXAddress();
169: if (metadataStr != null) {
170: wsdlLocation = URI.create(metadataStr);
171: } else {
172: final String namespace = stsConfig.getSTSNamespace();
173: String wsdlLocationStr = stsConfig.getSTSWSDLLocation();
174: if (wsdlLocationStr == null) {
175: wsdlLocationStr = stsURI;
176: } else {
177: final String serviceNameStr = stsConfig
178: .getSTSServiceName();
179: if (serviceNameStr != null && namespace != null) {
180: serviceName = new QName(namespace, serviceNameStr);
181: }
182:
183: final String portNameStr = stsConfig.getSTSPortName();
184: if (portNameStr != null && namespace != null) {
185: portName = new QName(namespace, portNameStr);
186: }
187: }
188: wsdlLocation = URI.create(wsdlLocationStr);
189: }
190:
191: RequestSecurityTokenResponse result = null;
192: try {
193: final RequestSecurityToken request = createRequest(null,
194: stsConfig, appliesTo);
195:
196: result = invokeRST(request, wsdlLocation, serviceName,
197: portName, stsURI);
198: final WSTrustClientContract contract = WSTrustFactory
199: .createWSTrustClientContract(config);
200: contract.handleRSTR(request, result, itc);
201: } catch (RemoteException ex) {
202: log.log(Level.SEVERE, LogStringsMessages
203: .WST_0016_PROBLEM_IT_CTX(stsURI, appliesTo), ex);
204: throw new WSTrustException(LogStringsMessages
205: .WST_0016_PROBLEM_IT_CTX(stsURI, appliesTo), ex);
206: } catch (URISyntaxException ex) {
207: log.log(Level.SEVERE, LogStringsMessages
208: .WST_0016_PROBLEM_IT_CTX(stsURI, appliesTo), ex);
209: throw new WSTrustException(LogStringsMessages
210: .WST_0016_PROBLEM_IT_CTX(stsURI, appliesTo));
211: }
212: }
213:
214: /**
215: * Obtain the Token by using WS-Trust or WS-SecureConversation.
216: * @param issuedToken, an instance of <sp:IssuedToken> or <sp:SecureConversation> assertion
217: * @return issuedTokenContext, a context containing the issued Token and related information
218: */
219: public IssuedTokenContext process(final PolicyAssertion token,
220: final PolicyAssertion localToken, final String appliesTo) {
221: final IssuedToken issuedToken = (IssuedToken) token;
222: final RequestSecurityTokenTemplate rstTemplate = issuedToken
223: .getRequestSecurityTokenTemplate();
224:
225: URI stsURI = getSTSURI(issuedToken);
226: URI wsdlLocation = null;
227: QName serviceName = null;
228: QName portName = null;
229:
230: // Get STS information from IssuedToken
231: if (stsURI != null) {
232: URI metadataAddress = getAddressFromMetadata(issuedToken);
233:
234: if (metadataAddress != null) {
235: wsdlLocation = metadataAddress;
236: } else {
237: wsdlLocation = stsURI;
238: }
239: } else if (localToken != null) {
240: // Get STS information from local configuration
241: if (PRE_CONFIGURED_STS.equals(localToken.getName()
242: .getLocalPart())) {
243: final Map<QName, String> attrs = localToken
244: .getAttributes();
245: final String namespace = attrs.get(new QName(
246: CONFIG_NAMESPACE, NAMESPACE));
247: String stsEPStr = attrs.get(new QName(CONFIG_NAMESPACE,
248: ENDPOINT));
249: if (stsEPStr == null) {
250: stsEPStr = attrs.get(new QName(CONFIG_NAMESPACE,
251: ENDPOINT.toLowerCase()));
252: }
253: if (stsEPStr != null) {
254: stsURI = URI.create(stsEPStr);
255: }
256:
257: final String metadataStr = attrs.get(new QName(
258: CONFIG_NAMESPACE, METADATA));
259: if (metadataStr != null) {
260: wsdlLocation = URI.create(metadataStr);
261: }
262:
263: final String wsdlLocationStr = attrs.get(new QName(
264: CONFIG_NAMESPACE, WSDL_LOCATION));
265: if (wsdlLocationStr != null) {
266: wsdlLocation = URI.create(wsdlLocationStr);
267: }
268:
269: final String serviceNameStr = attrs.get(new QName(
270: CONFIG_NAMESPACE, SERVICE_NAME));
271: if (serviceNameStr != null && namespace != null) {
272: serviceName = new QName(namespace, serviceNameStr);
273: }
274:
275: if (wsdlLocation == null) {
276: wsdlLocation = stsURI;
277: }
278:
279: final String portNameStr = attrs.get(new QName(
280: CONFIG_NAMESPACE, PORT_NAME));
281: if (portNameStr != null && namespace != null) {
282: portName = new QName(namespace, portNameStr);
283: }
284: }
285: }
286:
287: if (stsURI == null) {
288: log.log(Level.SEVERE, LogStringsMessages
289: .WST_0029_COULD_NOT_GET_STS_LOCATION(appliesTo));
290: throw new WebServiceException(LogStringsMessages
291: .WST_0029_COULD_NOT_GET_STS_LOCATION(appliesTo));
292: }
293:
294: RequestSecurityTokenResponse result = null;
295: try {
296: final RequestSecurityToken request = createRequest(
297: rstTemplate, null, appliesTo);
298:
299: // handle Claims.
300: // Not: should be in the RequestSecurityTokenTemplate api. Workaround for now.
301: Claims claims = getClaims(token, appliesTo);
302: if (claims != null) {
303: request.setClaims(claims);
304: }
305:
306: result = invokeRST(request, wsdlLocation, serviceName,
307: portName, stsURI.toString());
308: final IssuedTokenContext itc = new IssuedTokenContextImpl();
309: final WSTrustClientContract contract = WSTrustFactory
310: .createWSTrustClientContract(config);
311: contract.handleRSTR(request, result, itc);
312: return itc;
313: } catch (RemoteException ex) {
314: log.log(Level.SEVERE, LogStringsMessages
315: .WST_0016_PROBLEM_IT_CTX(stsURI, appliesTo), ex);
316: throw new WebServiceException(LogStringsMessages
317: .WST_0016_PROBLEM_IT_CTX(stsURI, appliesTo), ex);
318: } catch (URISyntaxException ex) {
319: log.log(Level.SEVERE, LogStringsMessages
320: .WST_0016_PROBLEM_IT_CTX(stsURI, appliesTo), ex);
321: throw new WebServiceException(LogStringsMessages
322: .WST_0016_PROBLEM_IT_CTX(stsURI, appliesTo));
323: } catch (WSTrustException ex) {
324: log.log(Level.SEVERE, LogStringsMessages
325: .WST_0016_PROBLEM_IT_CTX(stsURI, appliesTo), ex);
326: throw new WebServiceException(LogStringsMessages
327: .WST_0016_PROBLEM_IT_CTX(stsURI, appliesTo));
328: }
329: }
330:
331: private RequestSecurityToken createRequest(
332: final RequestSecurityTokenTemplate rstTemplate,
333: final STSIssuedTokenConfiguration stsConfig,
334: final String appliesTo) throws URISyntaxException,
335: WSTrustException, NumberFormatException {
336: final URI requestType = URI
337: .create(WSTrustConstants.ISSUE_REQUEST);
338: AppliesTo applTo = null;
339: if (appliesTo != null) {
340: applTo = WSTrustUtil.createAppliesTo(appliesTo);
341: }
342:
343: long keySize = -1;
344: String keyType = null;
345: String tokenTypeStr = null;
346: if (rstTemplate != null) {
347: keySize = rstTemplate.getKeySize();
348: keyType = rstTemplate.getKeyType();
349: tokenTypeStr = rstTemplate.getTokenType();
350: } else if (stsConfig != null) {
351: keySize = stsConfig.getKeySize();
352: keyType = stsConfig.getKeyType();
353: tokenTypeStr = stsConfig.getTokenType();
354: }
355:
356: int len = 32;
357: if (keySize > 0) {
358: len = (int) keySize / 8;
359: }
360:
361: final SecureRandom secRandom = new SecureRandom();
362: final byte[] nonce = new byte[len];
363: secRandom.nextBytes(nonce);
364: final BinarySecret binarySecret = fact.createBinarySecret(
365: nonce, BinarySecret.NONCE_KEY_TYPE);
366: final Entropy entropy = fact.createEntropy(binarySecret);
367: URI tokenType = URI
368: .create(WSTrustConstants.SAML11_ASSERTION_TOKEN_TYPE);
369: if (tokenTypeStr != null) {
370: tokenType = new URI(tokenTypeStr.trim());
371: }
372: final URI context = null;
373: final Claims claims = null;
374: final Lifetime lifetime = null;
375: final RequestSecurityToken rst = fact.createRSTForIssue(
376: tokenType, requestType, context, applTo, claims,
377: entropy, lifetime);
378:
379: if (keySize > 0) {
380: rst.setKeySize(keySize);
381: }
382:
383: if (keyType != null) {
384: rst.setKeyType(new URI(keyType.trim()));
385: }
386: rst.setComputedKeyAlgorithm(URI
387: .create(WSTrustConstants.CK_PSHA1));
388:
389: if (log.isLoggable(Level.FINE)) {
390: log.log(Level.FINE, LogStringsMessages
391: .WST_1006_CREATED_RST_ISSUE(elemToString(rst)));
392: }
393:
394: return rst;
395: }
396:
397: private RequestSecurityTokenResponse invokeRST(
398: final RequestSecurityToken request, final URI wsdlLocation,
399: QName serviceName, QName portName, String stsURI)
400: throws RemoteException, WSTrustException {
401:
402: if (serviceName == null || portName == null) {
403: //we have to get the serviceName and portName through MEX
404: if (log.isLoggable(Level.FINE)) {
405: log.log(Level.FINE, LogStringsMessages
406: .WST_1012_SERVICE_PORTNAME_MEX(serviceName,
407: portName));
408: }
409:
410: final QName[] names = doMexRequest(wsdlLocation.toString(),
411: stsURI);
412: serviceName = names[0];
413: portName = names[1];
414: }
415:
416: Service service = null;
417: try {
418: // Work around for issue 338
419: String url = wsdlLocation.toString();
420: // if (url.endsWith("/mex")){
421: // int index = url.lastIndexOf("/mex");
422: // url = url.substring(0, index);
423: //}
424: service = Service.create(new URL(url), serviceName);
425: } catch (MalformedURLException ex) {
426: log.log(Level.SEVERE, LogStringsMessages
427: .WST_0041_SERVICE_NOT_CREATED(wsdlLocation
428: .toString()), ex);
429: throw new WebServiceException(LogStringsMessages
430: .WST_0041_SERVICE_NOT_CREATED(wsdlLocation
431: .toString()), ex);
432: }
433: final Dispatch<Object> dispatch = service.createDispatch(
434: portName, fact.getContext(), Service.Mode.PAYLOAD,
435: new WebServiceFeature[] { new RespectBindingFeature(),
436: new AddressingFeature(false) });
437: //Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE, new WebServiceFeature[]{new AddressingFeature(false)});
438: //WSBinding wsbinding = (WSBinding) dispatch.getBinding();
439: //AddressingVersion addVer = wsbinding.getAddressingVersion();
440: //SOAPVersion sv = wsbinding.getSOAPVersion();
441:
442: //dispatch = addAddressingHeaders(dispatch);
443: if (stsURI != null) {
444: dispatch
445: .getRequestContext()
446: .put(
447: javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
448: stsURI);
449: }
450: dispatch.getRequestContext().put(
451: WSTrustConstants.IS_TRUST_MESSAGE, "true");
452: dispatch.getRequestContext().put(
453: WSTrustConstants.REQUEST_SECURITY_TOKEN_ISSUE_ACTION,
454: WSTrustConstants.REQUEST_SECURITY_TOKEN_ISSUE_ACTION);
455:
456: //RequestSecurityTokenResponse rstr = null;
457: // try{
458: // MessageFactory factory = sv.saajMessageFactory;
459: // SOAPMessage message = factory.createMessage();
460: // message.getSOAPBody().addDocument(fact.toElement(request).getOwnerDocument());
461: // SOAPHeader header = message.getSOAPHeader();
462: // SOAPHeaderElement action = header.addHeaderElement(addVer.actionTag);
463: // action.addTextNode(WSTrustConstants.REQUEST_SECURITY_TOKEN_ISSUE_ACTION);
464: // SOAPHeaderElement to = header.addHeaderElement(addVer.toTag);
465: // to.addTextNode(stsURI.toString());
466: // SOAPHeaderElement msgID = header.addHeaderElement(addVer.messageIDTag);
467: // msgID.addTextNode("uuid:" + UUID.randomUUID().toString());
468: // SOAPHeaderElement replyTo = header.addHeaderElement(addVer.replyToTag);
469: // SOAPElement add = replyTo.addChildElement(new QName(addVer.nsUri, "Address"));
470: // add.addTextNode(AddressingVersion.W3C.getAnonymousUri());
471: //SOAPMessage response = (SOAPMessage)dispatch.invoke(message);
472: // SOAPBody rsp = response.getSOAPBody();
473: // Element rspEle = rsp.extractContentAsDocument().getDocumentElement();
474: // rstr = fact.createRSTRFrom(rspEle);
475: // } catch(Exception ex){
476: // ex.printStackTrace();
477: // }
478:
479: final RequestSecurityTokenResponse rstr = fact
480: .createRSTRFrom((JAXBElement) dispatch.invoke(fact
481: .toJAXBElement(request)));
482: if (log.isLoggable(Level.FINE)) {
483: log
484: .log(
485: Level.FINE,
486: LogStringsMessages
487: .WST_1014_RESPONSE_INVOKING_RST(elemToString(rstr)));
488: }
489: return rstr;
490: }
491:
492: /**
493: * This method uses mex client api to issue a mex request and return the
494: * matching service name and port name
495: * @param stsURI URI to the STS. Mex request will be issued to this address
496: * @return List of 2 QName objects. The first one will be serviceName
497: * and the second one will be portName.
498: */
499: protected static QName[] doMexRequest(final String wsdlLocation,
500: final String stsURI) throws WSTrustException {
501:
502: final QName[] serviceInfo = new QName[2];
503: final MetadataClient mexClient = new MetadataClient();
504:
505: final Metadata metadata = mexClient
506: .retrieveMetadata(wsdlLocation);
507:
508: //this method gives the names of services and the corresponding port details
509: if (metadata != null) {
510: final List<PortInfo> ports = mexClient
511: .getServiceInformation(metadata);
512:
513: //we have to iterate through this to get the appropriate serviceName and portname
514: for (PortInfo port : ports) {
515: final String uri = port.getAddress();
516:
517: //if the stsAddress what we have matches the address of this port, return
518: //this port information
519: if (uri.equals(stsURI)) {
520: serviceInfo[0] = port.getServiceName();
521: serviceInfo[1] = port.getPortName();
522: break;
523: }
524:
525: }
526:
527: if (serviceInfo[0] == null || serviceInfo[1] == null) {
528: log.log(Level.SEVERE, LogStringsMessages
529: .WST_0042_NO_MATCHING_SERVICE_MEX(stsURI));
530: throw new WSTrustException(LogStringsMessages
531: .WST_0042_NO_MATCHING_SERVICE_MEX(stsURI));
532: }
533: } else {
534: log.log(Level.SEVERE, LogStringsMessages
535: .WST_0017_SERVICE_PORTNAME_ERROR(wsdlLocation
536: .toString()));
537: throw new WSTrustException(LogStringsMessages
538: .WST_0017_SERVICE_PORTNAME_ERROR(wsdlLocation
539: .toString()));
540: }
541:
542: return serviceInfo;
543: }
544:
545: /**
546: * method to examine the IssuedToken assertion and return the URI of the Issuer
547: * endpoint reference.
548: * @param issuedToken The issuedToken assertion
549: * @return The URI of the Issuer in IssuedToken, which is nothing but the URI of STS.
550: */
551: private URI getSTSURI(final IssuedToken issuedToken) {
552: final Issuer issuer = issuedToken.getIssuer();
553: if (issuer != null) {
554: final Address address = issuer.getAddress();
555: if (address != null) {
556: return address.getURI();
557: }
558: }
559: return null;
560: }
561:
562: private URI getAddressFromMetadata(final IssuedToken issuedToken) {
563: final PolicyAssertion issuer = (PolicyAssertion) issuedToken
564: .getIssuer();
565: PolicyAssertion addressingMetadata = null;
566: PolicyAssertion metadata = null;
567: PolicyAssertion metadataSection = null;
568: PolicyAssertion metadataReference = null;
569: Address address = null;
570: if (issuer != null) {
571: address = ((Issuer) issuer).getAddress();
572:
573: if (issuer.hasNestedAssertions()) {
574: final Iterator<PolicyAssertion> iterator = issuer
575: .getNestedAssertionsIterator();
576: while (iterator.hasNext()) {
577: final PolicyAssertion assertion = iterator.next();
578: if (WSTrustUtil.isAddressingMetadata(assertion)) {
579: addressingMetadata = assertion;
580: break;
581: }
582: }
583: }
584: }
585:
586: if (addressingMetadata != null) {
587: if (addressingMetadata.hasNestedAssertions()) {
588: final Iterator<PolicyAssertion> iterator = addressingMetadata
589: .getNestedAssertionsIterator();
590: while (iterator.hasNext()) {
591: final PolicyAssertion assertion = iterator.next();
592: if (WSTrustUtil.isMetadata(assertion)) {
593: metadata = assertion;
594: break;
595: }
596: }
597: }
598: }
599:
600: if (metadata != null) {
601: if (metadata.hasNestedAssertions()) {
602: final Iterator<PolicyAssertion> iterator = metadata
603: .getNestedAssertionsIterator();
604: while (iterator.hasNext()) {
605: final PolicyAssertion assertion = iterator.next();
606: if (WSTrustUtil.isMetadataSection(assertion)) {
607: metadataSection = assertion;
608: break;
609: }
610: }
611: }
612:
613: }
614:
615: if (metadataSection != null) {
616: if (metadataSection.hasNestedAssertions()) {
617: final Iterator<PolicyAssertion> iterator = metadataSection
618: .getNestedAssertionsIterator();
619: while (iterator.hasNext()) {
620: final PolicyAssertion assertion = iterator.next();
621: if (WSTrustUtil.isMetadataReference(assertion)) {
622: metadataReference = assertion;
623: break;
624: }
625: }
626: }
627:
628: }
629: if (metadataReference != null) {
630: if (metadataReference.hasNestedAssertions()) {
631: final Iterator<PolicyAssertion> iterator = metadataReference
632: .getNestedAssertionsIterator();
633: while (iterator.hasNext()) {
634: final PolicyAssertion assertion = iterator.next();
635: if (PolicyUtil.isAddress(assertion)) {
636: address = (Address) assertion;
637: // return address.getURI();
638: }
639: }
640: }
641:
642: }
643:
644: if (address != null) {
645: return address.getURI();
646: }
647:
648: return null;
649: }
650:
651: private Claims getClaims(final PolicyAssertion token,
652: String appliesTo) throws WSTrustException {
653: Claims claims = null;
654: final Iterator<PolicyAssertion> tokens = token
655: .getNestedAssertionsIterator();
656: while (tokens.hasNext()) {
657: final PolicyAssertion cToken = tokens.next();
658: if (REQUEST_SECURITY_TOKEN_TEMPLATE.equals(cToken.getName()
659: .getLocalPart())) {
660: final Iterator<PolicyAssertion> cTokens = cToken
661: .getNestedAssertionsIterator();
662: while (cTokens.hasNext()) {
663: final PolicyAssertion gToken = cTokens.next();
664: if (CLAIMS.equals(gToken.getName().getLocalPart())) {
665: try {
666: ByteArrayOutputStream baos = new ByteArrayOutputStream();
667: XMLOutputFactory xof = XMLOutputFactory
668: .newInstance();
669: XMLStreamWriter writer = xof
670: .createXMLStreamWriter(baos);
671:
672: AssertionSet set = AssertionSet
673: .createAssertionSet(Arrays
674: .asList(new PolicyAssertion[] { gToken }));
675: Policy policy = Policy
676: .createPolicy(Arrays
677: .asList(new AssertionSet[] { set }));
678: PolicySourceModel sourceModel = PolicyModelGenerator
679: .getGenerator().translate(policy);
680: XmlPolicyModelMarshaller pm = (XmlPolicyModelMarshaller) XmlPolicyModelMarshaller
681: .getXmlMarshaller(true);
682: pm.marshal(sourceModel, writer);
683:
684: DocumentBuilderFactory dbf = DocumentBuilderFactory
685: .newInstance();
686: dbf.setNamespaceAware(true);
687: DocumentBuilder db = dbf
688: .newDocumentBuilder();
689: Document doc = db
690: .parse(new ByteArrayInputStream(
691: baos.toByteArray()));
692: Element claimsEle = (Element) doc
693: .getElementsByTagNameNS("*",
694: "Claims").item(0);
695:
696: claims = new ClaimsImpl(ClaimsImpl
697: .fromElement(claimsEle));
698: writer.close();
699: } catch (Exception e) {
700: log
701: .log(
702: Level.SEVERE,
703: LogStringsMessages
704: .WST_0045_ERROR_UNMARSHALL_CLAIMS(appliesTo),
705: e);
706: throw new WebServiceException(
707: LogStringsMessages
708: .WST_0045_ERROR_UNMARSHALL_CLAIMS(appliesTo),
709: e);
710: }
711: }
712: }
713: }
714: }
715: return claims;
716: }
717:
718: /**
719: * Prints out the RST created as string.
720: * This method is primarily used for logging purposes.
721: */
722: private String elemToString(final RequestSecurityToken rst) {
723: try {
724: final javax.xml.bind.Marshaller marshaller = fact
725: .getContext().createMarshaller();
726: final JAXBElement<RequestSecurityTokenType> rstElement = (new ObjectFactory())
727: .createRequestSecurityToken((RequestSecurityTokenType) rst);
728: marshaller.setProperty(
729: javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT,
730: Boolean.TRUE);
731: final java.io.StringWriter writer = new java.io.StringWriter();
732: marshaller.marshal(rstElement, writer);
733: return writer.toString();
734: } catch (Exception e) {
735: log.log(Level.SEVERE, LogStringsMessages
736: .WST_1004_ERROR_MARSHAL_TO_STRING("RST"), e);
737:
738: throw new WebServiceException(LogStringsMessages
739: .WST_1004_ERROR_MARSHAL_TO_STRING("RST"), e);
740: }
741: }
742:
743: private String elemToString(final RequestSecurityTokenResponse rstr) {
744: try {
745: final javax.xml.bind.Marshaller marshaller = fact
746: .getContext().createMarshaller();
747: final JAXBElement<RequestSecurityTokenResponseType> rstrElement = (new ObjectFactory())
748: .createRequestSecurityTokenResponse((RequestSecurityTokenResponseType) rstr);
749: marshaller.setProperty(
750: javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT,
751: Boolean.TRUE);
752: final java.io.StringWriter writer = new java.io.StringWriter();
753: marshaller.marshal(rstrElement, writer);
754: return writer.toString();
755: } catch (Exception e) {
756: log.log(Level.SEVERE, LogStringsMessages
757: .WST_1004_ERROR_MARSHAL_TO_STRING("RSTR"), e);
758: throw new WebServiceException(LogStringsMessages
759: .WST_1004_ERROR_MARSHAL_TO_STRING("RSTR"), e);
760: }
761: }
762:
763: }
|