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

标签 spring-boot websocket spring-webflux spring-websocket java-websocket

我正在运行带有暴露的 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/

相关文章:

spring-boot - 带有Jersey的Spring Boot 2.1.0

java - 可以将 HTML5 网络套接字连接到 Java 套接字吗?

junit - 使用 WebTestClient 和 ControllerAdvice 单元测试 Spring Controller

java - 如何在热源上使用 groupBy

spring - 如何使用Spring boot向Prometheus中的目标添加标签?

java - Spring Boot中等待数据库连接无一异常(exception)

java - 从我所有的 Controller 访问一个变量

spring - 从Grails看不到 Spring 启动RestController

javascript - 尝试 console.log 我从 socket.io 收到的消息时收到 401~UNAUTHORIZED

java - GlassFish 4 或 Tyrus 中的错误 : Decoder#willDecode is called twice for each ByteBuffer?