Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get endpoint path in ChannelInterceptor with spring boot stomp?

I am new in stomp use spring boot 2.1.2.RELEASE. I have multi endpoint and config a ChannelInterceptor to get some info.

@Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {

        registry.addEndpoint("/endpoint1")
                .addInterceptors(new IpHandshakeInterceptor())
                .setAllowedOrigins(origin)
                .withSockJS();

        registry.addEndpoint("/endpoint2")
                .addInterceptors(new IpHandshakeInterceptor())
                .setAllowedOrigins(origin)
                .withSockJS();
        // other andpoint
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(myChannelInterceptor());
    }

All endpoint use myChannelInterceptor(actually, i want endpoint use its own ChannelInterceptor), i want do thing in ChannelInterceptor by endpoint path.

@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
  if (endpoint.equals("endpoint1")) {
  } else if (endpoint.equals("endpoint2")) {
  }
}

How can i get endpoint info in ChannelInterceptor?

like image 842
user1434702 Avatar asked Sep 01 '25 01:09

user1434702


1 Answers

You can use:

  1. In class IpHandshakeInterceptor write value to attributes map:

     @Override
     public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
         if (serverHttpRequest instanceof ServletServerHttpRequest) {
             ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) serverHttpRequest;
             HttpSession session = servletRequest.getServletRequest().getSession();
             //add value to session attributes
             map.put("endpoint", servletRequest.getURI().getPath());
         }
         // ... your logic ...
         return true;
     }
    
  2. In your myChannelInterceptor read value from session attributes:

     @Override
     public Message<?> preSend(final Message<?> message, final MessageChannel channel) throws AuthenticationException {
         final StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
         String endpoint=accessor.getSessionAttributes().get("endpoint").toString();
         // ... your logic ...
         return message;
     }
    
like image 154
Eldar Gaynutdinov Avatar answered Sep 03 '25 23:09

Eldar Gaynutdinov