簡體   English   中英

Spring RSocket over WebSocket - 從 HTTP Z21D6F40CFB511982A95424E0E27 訪問用戶信息

[英]Spring RSocket over WebSocket - Access user information from HTTP session

在我的 web 應用程序中,用戶使用用戶名/密碼組合登錄並獲得 session cookie。 在發起 WebSocket 連接時,我可以輕松訪問WebSocketHandler中的用戶信息,例如:

@Component
public class MyWebSocketHandler implements WebSocketHandler {
    @Override
    public Mono<Void> handle(WebSocketSession session) {
        // two ways to access security context information, either like this:
        Mono<Principal> principal = session.getHandshakeInfo().getPrincipal();

        // or like this
        Mono<SecurityContext> context = ReactiveSecurityContextHolder.getContext();

        //...
        return Mono.empty();
    }
}

Both reuse the HTTP session from the WebSocket handshake, I don't have to send additional authentication over the WebSocket itself. 對於 STOMP,同樣的事情也適用:我可以重用 HTTP session 的信息。

如何使用 RSocket 實現相同的目標? 例如,我如何在這樣的 MessageMapping 方法中獲取有關用戶的信息?:

@Controller
public class RSocketController {
    @MessageMapping("test-stream")
    public Flux<String> streamTest(RSocketRequester requester) {
        // this mono completes empty, no security context available :(
        Mono<SecurityContext> context = ReactiveSecurityContextHolder.getContext();

        return Flux.empty();
    }
}

I found many resources how to setup authentication with RSocket, but they all rely on an additional authentication after the WebSocket connection is established, but I specifically want to reuse the web session and don't want to send additional tokens over the websocket.

您是否嘗試過以下操作? 我在文檔中找到它:2.2 Secure Your RSocket Methods(可能需要向下滾動一點) https://spring.io/blog/2020/06/17/getting-started-with-rsocket-spring-security

@PreAuthorize("hasRole('USER')") // (1)
@MessageMapping("fire-and-forget")
public Mono<Void> fireAndForget(final Message request, @AuthenticationPrincipal UserDetails user) { // (2)
    log.info("Received fire-and-forget request: {}", request);
    log.info("Fire-And-Forget initiated by '{}' in the role '{}'", user.getUsername(), user.getAuthorities());
    return Mono.empty();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM