gpt4 book ai didi

spring-boot - Spring WebFlux 认证的 WebSocket 连接

转载 作者:行者123 更新时间:2023-12-04 17:31:49 25 4
gpt4 key购买 nike

我正在运行带有暴露的 WebSocket 端点的 Spring Boot@2.2.x 服务器。这是我的 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());
}
}

问题是我如何使用 Basic AuthenticationBearer Authenticationaccess_token 查询参数来实现建立 WS 连接的身份验证?

最好的选择是避免使用 Spring Security。

谢谢。

最佳答案

Websocket 连接以 升级 的 HTTP 请求开始。您可以在升级之前进行 JWT token 身份验证。在 spring boot 中,它的工作原理如下:

公开一个自定义 WebSocketService bean:

@Bean
public WebSocketService webSocketService(RequestUpgradeStrategy upgradeStrategy) {
return new HandshakeWebSocketService(upgradeStrategy);
}

在自己的类中实现RequestUpgradeStrategy接口(interface):

@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);
});
}

注意事项:

  • 以上类基于ReactorNettyRequestUpgradeStrategy

  • 返回reactorResponse.sendWebsocket是将连接升级为WebSocket连接的现有行为

  • 可以返回
  • reactorResponse.status 以停止正在升级的连接。例如,您可以在未授权连接的情况下返回 401 响应。

  • 查询参数和Authentication header 可以在握手信息中找到。如何进行身份验证本身不在问题范围内。

关于spring-boot - Spring WebFlux 认证的 WebSocket 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58895957/

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