本文介绍了使用来自websocket消息的spring-security和access principal保护Spring-Webscoket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring Security是一个非常好的框架,广泛用于Authentication&授权。

Spring Security is very nice framework widely used for Authentication & Authorization.

我要求使用j_spring_security_check对应用程序进行身份验证,并且只有授权用户才能向websocket处理程序发出请求。

I have a requirement in which the application to be authenticated using j_spring_security_check, and only authorized users can make request to websocket handler.

我根据

我有根据。

我希望从handleTextMessage处理程序访问 MyPrincipal 主体对象下面:

I want MyPrincipal principal object to be accessed from handleTextMessage handler as per below:

    @Override
    protected void handleTextMessage(WebSocketSession session,
            TextMessage message) throws Exception {
        System.out.println("Protocol: "+session.getAcceptedProtocol());
        TextMessage returnMessage = new TextMessage(message.getPayload()
                + " received at server");
        System.out.println("myAttrib="
                + session.getAttributes().get("myAttrib"));
        MyPrincipal user = (MyPrincipal) ((Authentication) session
                .getPrincipal()).getPrincipal();
        System.out.println("User: " + user.getUserId());
        session.sendMessage(returnMessage);
    }

请尽快重播。

推荐答案

在websocket配置中添加 HttpSessionHandshakeInterceptor 允许从 SpringSecurityContext WebsocketSession

Adding HttpSessionHandshakeInterceptor in websocket configuration allows to pass spring security principal object from SpringSecurityContext to WebsocketSession

编辑:
HandshakeInterceptor.java

public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor{

    @Override
    public boolean beforeHandshake(ServerHttpRequest request,
            ServerHttpResponse response, WebSocketHandler wsHandler,
            Map<String, Object> attributes) throws Exception {
        System.out.println("Before Handshake");
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    @Override
    public void afterHandshake(ServerHttpRequest request,
            ServerHttpResponse response, WebSocketHandler wsHandler,
            Exception ex) {
        System.out.println("After Handshake");
        super.afterHandshake(request, response, wsHandler, ex);
    }

}

websocket.xml

<bean id="websocket" class="co.syntx.example.websocket.handler.WebsocketEndPoint"/>

<websocket:handlers>
    <websocket:mapping path="/websocket" handler="websocket"/>
    <websocket:handshake-interceptors>
    <bean class="co.syntx.example.websocket.HandshakeInterceptor"/>
    </websocket:handshake-interceptors>
</websocket:handlers>

这篇关于使用来自websocket消息的spring-security和access principal保护Spring-Webscoket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 05:02