pov*_*nko 5 websocket spring-boot spring-websocket java-websocket spring-webflux
我正在运行Spring Boot@2.2.x带有公开 WebSocket 端点的服务器。这是我的WebSocketConfiguration:
@Slf4j
@Configuration
public class WebSocketConfiguration {
private static final String WS_PATH = "/ws/notifications";
@Bean
public HandlerMapping webSocketHandlerMapping() {
Map<String, WebSocketHandler> handlersMap = new HashMap<>();
handlersMap.put(WS_PATH, session -> session.send(session.receive()
.map(WebSocketMessage::getPayloadAsText)
.doOnEach(logNext(log::info))
.map(msg -> format("notification for your msg: %s", msg))
.map(session::textMessage)));
SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
handlerMapping.setOrder(Ordered.HIGHEST_PRECEDENCE);
handlerMapping.setUrlMap(handlersMap);
return handlerMapping;
}
@Bean
public WebSocketHandlerAdapter handlerAdapter(WebSocketService webSocketService) {
return new WebSocketHandlerAdapter(webSocketService);
}
@Bean
public WebSocketService webSocketService() {
return new HandshakeWebSocketService(new ReactorNettyRequestUpgradeStrategy());
}
}
Run Code Online (Sandbox Code Playgroud)
问题是如何使用Basic Authentication或Bearer Authentication或access_token查询参数来实现建立 WS 连接的身份验证?
更好的选择是避免使用 Spring Security。
谢谢。
小智 3
Websocket 连接以 HTTP 请求开始Upgraded。您可以在升级之前进行 JWT 令牌身份验证。在 Spring Boot 中它的工作原理如下:
公开自定义WebSocketServicebean:
@Bean
public WebSocketService webSocketService(RequestUpgradeStrategy upgradeStrategy) {
return new HandshakeWebSocketService(upgradeStrategy);
}
Run Code Online (Sandbox Code Playgroud)
在您自己的类中实现该RequestUpgradeStrategy接口:
@Override
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, @Nullable String subProtocol, Supplier<HandshakeInfo> handshakeInfoFactory) {
ServerHttpResponse response = exchange.getResponse();
HttpServerResponse reactorResponse = getNativeResponse(response);
HandshakeInfo handshakeInfo = handshakeInfoFactory.get();
NettyDataBufferFactory bufferFactory = (NettyDataBufferFactory) response.bufferFactory();
var authResult = validateAuth(handshakeInfo);
if (authResult == unauthorised) return Mono.just(reactorResponse.status(rejectedStatus))
.flatMap(HttpServerResponse::send);
else return reactorResponse.sendWebsocket(subProtocol, //
this.maxFramePayloadLength,//
(in, out) -> {
ReactorNettyWebSocketSession session = new ReactorNettyWebSocketSession(in, out,
handshakeInfo,
bufferFactory,
this.maxFramePayloadLength);
return handler.handle(session);
});
}
Run Code Online (Sandbox Code Playgroud)
笔记:
上面的类是基于ReactorNettyRequestUpgradeStrategy.
返回reactorResponse.sendWebsocket是将连接升级为WebSocket连接的现有行为
reactorResponse.status可以返回以停止正在升级的连接。例如,您可以401在未经授权的连接的情况下返回响应。
查询参数和Authentication标头可以在握手信息中找到。如何进行身份验证本身超出了问题的范围。
| 归档时间: |
|
| 查看次数: |
2061 次 |
| 最近记录: |