Tobi Tiggers
Tobi Tiggers

Reputation: 452

How to secure a WebSocket endpoint in Java EE?

I followed this tutorial on setting up an websocket endpoint with Java EE:

https://technology.amis.nl/2013/06/22/java-ee-7-ejb-publishing-cdi-events-that-are-pushed-over-websocket-to-browser-client/

For obvious reasons there is some more work to be done regarding the security (e.g. no SSL and access restriction/authentication).

So my goal is to improve websocket security by

My Question: How can i verify the token which I created in the LoginBean at the ServerEndpoint?

Bonus Question: Did I miss some important parts in securing websockets in Java EE?

This is what I have so far:

ServerEndpoint

import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/user/endpoint/{token}")
public class ThisIsTheSecuredEndpoint {

    @OnOpen
    public void onOpen(@PathParam("token") String incomingToken, 
    Session session) throws IOException {

        //How can i check if the token is valid?

    }      
}

LoginBean

@ManagedBean
@SessionScoped
public class LoginBean {

public String login() {

    FacesContext facesContext = FacesContext.getCurrentInstance();
    HttpServletRequest request = (HttpServletRequest)facesContext.getExternalContext().getRequest();

    try {
        request.login("userID", "password");

        HttpSession session = request.getSession();

        // here we put the token in the session
        session.setAttribute("token", "someVeeeeryLongRandomValue123hfgrtwpqllkiw");


    } catch (ServletException e) {
        facesContext.addMessage(null, new FacesMessage("Login failed."));
        return "error";
    }

    return "home";
}

}

Javascipt

this is the code i want use to connect to the websocket:

// use SSL 
// retrive the token from session via EL-expression #{session.getAttribute("token")}
var wsUri = "wss://someHost.com/user/endpoint/#{session.getAttribute("token")}";
var websocket = new WebSocket(wsUri);

websocket.onerror = function(evt) { onError(evt) };

function onError(evt) {
    writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}

// For testing purposes
var output = document.getElementById("output");
websocket.onopen = function(evt) { onOpen(evt) };

function writeToScreen(message) {
    output.innerHTML += message + "<br>";
}

function onOpen() {
    writeToScreen("Connected to " + wsUri);
}

web-xml:

secure the "/user/*" directory with a login and enforce SSL communication

<security-constraint>
    ...
    <web-resource-name>Secured Area</web-resource-name>
    <url-pattern>pathToSecuredDicrtoy</url-pattern>       
     ...       
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
    ...
</security-constraint>
<login-config>
    <auth-method>FORM</auth-method> ...           
</login-config>

Note: I am using JSF

Any feedback would be highly appreciated.

Upvotes: 3

Views: 10795

Answers (1)

cassiomolin
cassiomolin

Reputation: 130837

You could use a Servlet Filter for authentication purposes.

Here's an example of a filter that I created a while ago to protect a chat endpoint. It extracts the access token from a query parameter called access-token and delegates the token validation to a bean called Authenticator.

You can easily adapt it to your needs:

/**
 * Access token filter for the chat websocket. Requests without a valid access token 
 * are refused with a <code>403</code>.
 *
 * @author cassiomolin
 */
@WebFilter("/chat/*")
public class AccessTokenFilter implements Filter {

    @Inject
    private Authenticator authenticator;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, 
            FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // Extract access token from the request
        String token = request.getParameter("access-token");
        if (token == null || token.trim().isEmpty()) {
            returnForbiddenError(response, "An access token is required to connect");
            return;
        }

        // Validate the token and get the user who the token has been issued for
        Optional<String> optionalUsername = authenticator.getUsernameFromToken(token);
        if (optionalUsername.isPresent()) {
            filterChain.doFilter(
                    new AuthenticatedRequest(
                            request, optionalUsername.get()), servletResponse);
        } else {
            returnForbiddenError(response, "Invalid access token");
        }
    }

    private void returnForbiddenError(HttpServletResponse response, String message) 
            throws IOException {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
    }

    @Override
    public void destroy() {

    }

    /**
     * Wrapper for a {@link HttpServletRequest} which decorates a 
     * {@link HttpServletRequest} by adding a {@link Principal} to it.
     *
     * @author cassiomolin
     */
    private static class AuthenticatedRequest extends HttpServletRequestWrapper {

        private String username;

        public AuthenticatedRequest(HttpServletRequest request, String username) {
            super(request);
            this.username = username;
        }

        @Override
        public Principal getUserPrincipal() {
            return () -> username;
        }
    }
}

The chat endpoint was something like:

@ServerEndpoint("/chat")
public class ChatEndpoint {

    private static final Set<Session> sessions = 
            Collections.synchronizedSet(new HashSet<>());

    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
        String username = session.getUserPrincipal().getName();
        welcomeUser(session, username);
    }

    ...

}

The application is available here.

Upvotes: 10

Related Questions