简体   繁体   中英

session is not getting timeout after specified time when adding servlet filter in java websocket

I have websocket in one of my webapplication used to populate the notification message. The entire application is a ear file and we have multipe war file in it and this websocket endpoint is one war file.

It contains below:

    @ServerEndpoint(value = "/message", configurator = WebSocketConfigurator.class)
    public class WebsocketEndpoint {
    @OnOpen
    public void onOpen(Session session){

    }
    @OnClose
    public void onClose() {

    }

    @OnError
    public void error(Session session, Throwable throwable) {

    }

    @OnMessage
    public void handleMessage(String message, final Session session) {
        synchronized (session) {
            if (session != null && session.isOpen()) {
                int count = 2;                                
                session.getAsyncRemote().sendText("" + count);
                session.setMaxIdleTimeout(-1);
            }
        }
    }

}

public class WebSocketConfigurator extends ServerEndpointConfig.Configurator  {
    private boolean isValidHost;
    @Override
    public boolean checkOrigin(String originHeaderValue) {
    try {
        URL url = new URL(originHeaderValue);
        String hostName = url.getHost();
        isValidHost = Utils.isValidHostName(hostName);
    } catch (Exception ex){
        logger.error("Error in check checkOrigin for websocket call: "+ex.getMessage());
    }
    return isValidHost;
}
}

I am calling the endpoint in first login where handshake will happen and get the message and then in every 2 mins it will call to get the message only no handshake since handshake is already there ui is as below:

var websocketUrl = new WebSocket("ws://localhost:7001/example/message");
webSocket.onopen = function() {
webSocket.send('');
}
var interval=  setInterval(function() {
        'pollMessage()' 
    }, 120*1000);

    function  pollMessage(){
        if(wsEndPoint.readyState==1){
            wsEndPoint.send('');
        }
        if(wsEndPoint.readyState ==2 || wsEndPoint.readyState==3){
            wsEndPoint.close();
            clearInterval(interval);
        }
        wsEndPoint.onmessage = function(message){ 
            alert(message);
        }
    }



@WebServlet(urlPatterns = {"/message"})
public class MessageWebsocketServlet extends HttpServlet
{
}

The above works fine without any issue.

But I want to authenticate the call for security.

So I added webfilter

@WebFilter(urlPatterns = {"/message"}, filterName = "AuthFilter",initParams = {
        @WebInitParam(name = "authorizationEnabled", value = "false")
})
@ServletSecurity(httpMethodConstraints = {@HttpMethodConstraint(value = "GET")})
public class MessageWebsocketServletFilter implements Filter{

 private FilterConfig config = null;

@Override
public void init(FilterConfig config) throws ServletException {
}
 @Override
public void doFilter(ServletRequest req, ServletResponse res,
                     FilterChain chain)
        throws ServletException, IOException {
//authentication logic goes here and it involved cross origin check and 
}
@Override
public void destroy() {
    config.getServletContext().log("Destroying SessionCheckerFilter");
}

}

We have configured 30 mins as session timeout and After adding the above filter when the user logged in and idle more than 30 mins the applicaiton is not getting session timed out.

Any pointer would be great help for me.

Short version:

From what I can see, it is because of the line session.setMaxIdleTimeout(-1);

Long version:

When opening a websocket connection, the client proceeds to a handshake. Following the websocket bible ( RFC 6455 section 1.3 ), the handshake starts with a HTTP communication.

However, once the handshake is successful, the communication switches to another protocol as stated:

HTTP/1.1 101 Switching Protocols

Upgrade: websocket

Connection: Upgrade

Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

The communication is not HTTP anymore. As far as I know, Java Servlet only handles HTTP communication. Consequently, any configuration regarding the servlet has no impact on the websocket configuration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM