gpt4 book ai didi

java - 使用 spring-security 和来自 websocket 消息的访问主体来保护 Spring-Websocket

转载 作者:行者123 更新时间:2023-11-29 05:18:38 25 4
gpt4 key购买 nike

Spring Security 是一个非常好的框架,广泛用于身份验证和授权。

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

我已经根据 http://malalanayake.wordpress.com/2014/06/27/spring-security-on-rest-api/ 配置了 Spring Security

而且我已经根据 http://syntx.io/using-websockets-in-java-using-spring-4/ 配置了 websocket .

我希望从 handleTextMessage 处理程序访问 MyPrincipal 主体对象,如下所示:

    @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 允许将 spring 安全主体对象从 SpringSecurityContext 传递到 WebsocketSession

编辑:握手拦截器.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>

关于java - 使用 spring-security 和来自 websocket 消息的访问主体来保护 Spring-Websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25640872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com