简体   繁体   English

如何在Java EE中保护WebSocket端点?

[英]How to secure a WebSocket endpoint in Java EE?

I followed this tutorial on setting up an websocket endpoint with Java EE: 我按照本教程使用Java EE设置websocket端点:

https://technology.amis.nl/2013/06/22/java-ee-7-ejb-publishing-cdi-events-that-are-pushed-over-websocket-to-browser-client/ 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 ( eg no SSL and access restriction/authentication ). 出于显而易见的原因,在安全性方面还有很多工作要做( 例如,没有SSL和访问限制/身份验证 )。

So my goal is to improve websocket security by 所以我的目标是通过

  • using SSL (wss:// instead of ws://) - done 使用SSL(wss://而不是ws://)-完成
  • setup User authentification (web.xml) - done 设置用户身份验证(web.xml)-完成
  • enforce SSL communication (web.xml) - done 强制执行SSL通信(web.xml)-完成
  • secure the websocket connection with a token (limited lifetime) 使用令牌保护Websocket连接(使用寿命有限)

My Question: How can i verify the token which I created in the LoginBean at the ServerEndpoint? 我的问题:如何验证在ServerEndpoint在LoginBean中创建的令牌?

Bonus Question: Did I miss some important parts in securing websockets in Java EE? 奖励问题:我是否错过了在Java EE中保护Websocket的一些重要部分?

This is what I have so far: 这是我到目前为止的内容:

ServerEndpoint 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 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 javascipt的

this is the code i want use to connect to the websocket: 这是我要用于连接到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: 网络的XML:

secure the "/user/*" directory with a login and enforce SSL communication 使用登录名保护“ / user / *”目录并强制执行SSL通信

<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 注意:我正在使用JSF

Any feedback would be highly appreciated. 任何反馈将不胜感激。

You could use a Servlet Filter for authentication purposes. 您可以使用Servlet过滤器进行身份验证。

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 . 它从名为access-token的查询参数中提取访问令牌,并将令牌验证委派给名为Authenticator的bean。

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 . 该应用程序在此处可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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