3

我有一个独立的网络服务客户端。当调用任何 web 方法时,必须将附加的“cookie”字符串隐式(而不是作为 web 方法参数)传递给 WS。另一端的 WS 必须能够获取字符串并使用它。如何做到这一点?

我通过以下方式调用服务:

Service srv = Service.create(new URL(WSDL), QNAME);
myClassPort = srv.getPort(MyClass.class);

我需要在第一行之前放置一些代码,这样每次我通过 myClassPort 调用一些远程方法时,客户端都会发送这个“cookie”字符串。谢谢。

4

2 回答 2

7

By default JAX-WS web services and clients are stateless. When a client makes a request, the server responds and sets a cookie on the connection, if it participates in a session. But, the JAX-WS client ignores that cookie and the server treats subsequent requests as new interaction. When the session is enabled, JAX-WS client sends the same cookie with each subsequent request so that server can keep track of the client session.

So you should not be using either cookies or HTTP sessions with web services. Return a token ID as part of the response; then the client can send that along with the next request.

Anyway:

JAX-WS web service clients must be configured to maintain session information (such as cookies), using the javax.xml.ws.session.maintain property. Other web service stacks may have similar mechanisms.

On the Server Side

JAX-WS uses some handy annotations defined by Common Annotations for the Java Platform (JSR 250), to inject the web service context and declaring lifecycle methods. WebServiceContext holds the context information pertaining to a request being served.

You don't need to implement javax.xml.rpc.server.ServiceLifecycle. With JAX-WS Web Service all you need to do is mark a field or method with @Resource. The type element MUST be either java.lang.Object or javax.xml.ws.WebServiceContext.

@WebService
public class HelloWorld {
    @Resource
    private WebServiceContext wsContext;
    public void sayHello(){
        MessageContext mc = wsContext.getMessageContext();
        HttpSession session = ((javax.servlet.http.HttpServletRequest)mc.get(MessageContext.SERVLET_REQUEST)).getSession();

     }
}
于 2012-04-18T16:44:30.513 回答
0

这个问题有一些误导性的答案,所以我将尝试强调当前的最佳实践。这些建议中的大多数都是 OWASP 安全指南的一部分,我强烈建议任何从事 Web 开发工作的人进行审查。

1) 始终使用临时(会话范围)cookie。

2) 所有cookies都应该受到保护和加密。

3) 不要在请求有效载荷中传递令牌

4) 对于任何返回可能被发送回服务器的数据的请求,请在您的响应中包含一个随机数(单次使用令牌)。

5) 后面的请求应该(必须)包括 nonce 和 cookie

同样,我的建议是查看 OWASP 指南并相应地进行。您可能想考虑使用服务提供商进行身份验证 - 这比自己制作解决方案要聪明得多,因为实际上有一百万个细节都必须正确。Auth0.com 就是其中之一。

于 2018-04-20T19:39:47.263 回答