我正在运行Spring [email protected]
带有公开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());
}
}
问题是如何使用Basic Authentication
或Bearer Authentication
或access_token
查询参数实现用于建立WS连接的身份验证?
最好的选择是避免使用Spring Security。
谢谢。
Websocket连接从HTTP请求开始就开始了Upgraded
。您可以在升级之前执行JWT令牌认证。在春季启动中,其工作方式如下:
公开一个自定义WebSocketService
bean:
@Bean
public WebSocketService webSocketService(RequestUpgradeStrategy upgradeStrategy) {
return new HandshakeWebSocketService(upgradeStrategy);
}
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);
});
}
笔记:
以上课程基于ReactorNettyRequestUpgradeStrategy
。
返回的reactorResponse.sendWebsocket
是将连接升级到WebSocket连接的现有行为
reactorResponse.status
可以返回以停止升级连接。例如,您可以401
在未授权连接的情况下返回响应。
查询参数和Authentication
标头可以在握手信息中找到。如何进行身份验证本身不在问题范围内。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句