问题
I'm developing a code-first WebService with Apache CXF + Spring. My web service expects the UsernameToken to be present in SOAP request header in order to authenticate the calling client. My question is, is there any way to add SOAP security header (UsernameToken) definition somewhere in the Java code or configuration file, so the generated WSDL will have the security (UsernameToken) included? Please advice.
Many thanks :)
回答1:
Information about required tokens can be published in WSDL using WS-Policies. For username token I use the following policy:
<wsp:Policy wsu:Id="UP_policy" xmlns:wsp="http://www.w3.org/ns/ws-policy"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<sp:SupportingTokens
xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702">
<wsp:Policy>
<sp:UsernameToken
sp:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/AlwaysToRecipient">
<wsp:Policy>
<sp:WssUsernameToken11 />
</wsp:Policy>
</sp:UsernameToken>
</wsp:Policy>
</sp:SupportingTokens>
</wsp:Policy>
It requires UT only for request message (AlwaysToRecipient
). To include such policy in your generated WSDL:
- save it to file available in classpath, e.g.
ut.policy.xml
- add
@Policies({ @Policy(uri = "ut.policy.xml") })
annotations to your service class or interface
I modified example CXF project. It shows how to do that. You can find it here.
As a result your WSDL will have appropriate instance of WS-SecurityPolicy attached, telling clients that Username token is expected:
<wsdl:definitions ...>
...
<wsdl:service name="GreeterService">
<wsdl:port binding="tns:GreeterServiceSoapBinding" name="GreeterPort">
<soap:address location="http://localhost:9000/SoapContext/GreeterPort"/>
</wsdl:port>
<wsp:PolicyReference URI="#UP_policy"/>
</wsdl:service>
<wsp:Policy xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy" wsu:Id="UP_policy">
<sp:SupportingTokens xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702">
<wsp:Policy>
<sp:UsernameToken sp:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/AlwaysToRecipient">
<wsp:Policy>
<sp:WssUsernameToken11/>
</wsp:Policy>
</sp:UsernameToken>
</wsp:Policy>
</sp:SupportingTokens>
</wsp:Policy>
</wsdl:definitions>
More about configuring WS-SecurityPolicy with CXF can be found here and how to handle any WS-Policy here.
来源:https://stackoverflow.com/questions/19721876/how-to-add-soap-security-header-usernametoken-information-to-code-first-webser