Home » Java » java – Web-Socket Authentication and authorization on spring-boot and angular 8 project not working-Exceptionshub

java – Web-Socket Authentication and authorization on spring-boot and angular 8 project not working-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have created a j-hipster generated spring boot application and Angular 8 project. I have implemented login functionality, once logged in user receives a jwt token.
So whenever user request or call any api this token goes in headers.
In spring boot side I have override @doFilter method to authenticate api by fetching token from header and verifying them.
Now I want to use web-socket in application. I have written basic connect method in angular project and simple project in spring boot side.
But whenever I click connect button, I got error like full authentication required in eclipse IDE.
As per my research I we can’t send headers attached in stomp. So please can I know how to implement websocket in my project

Angular code

 _connect() {
console.log( sessionStorage.getItem('token'));
    //connect to stomp where stomp endpoint is exposed
    //let ws = new SockJS(http://localhost:8080/greeting);
    let wso = new SockJS(this.webSocketEndPoint);
    this.stompClient = Stomp.over(wso);
    const _this = this;
    _this.stompClient.connect({"Authorization": "Bearer " + sessionStorage.getItem('token')}, function (frame) {
      _this.stompClient.subscribe(_this.topic, function (sdkEvent) {
          _this.onMessageReceived(sdkEvent);
      });
      //_this.stompClient.reconnect_delay = 2000;
  }, this.errorCallBack);
};

Spring boot classes

@Configuration
@EnableWebSocketMessageBroker
public class WebsocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/api/ws/**").setAllowedOrigins("http://localhost:4200").withSockJS();
    }

@Controller
public class GreetingController {
    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {

        return new Greeting("Hello !");
    }
}
@Override
    public void doFilter(ServletRequest servletRequest, FilterChain f_chain, ServletResponse servletResponse)
        throws IOException, ServletException {
        HttpServletRequest rqust = (HttpServletRequest) servletRequest;
        String tokenRecved = tokenCheck(rqust);
        if (this.tokenProvider.validateToken(tokenRecved)) {
            Authentication auth = this.tokenProvider.getAuthentication(tokenRecved);
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
        f_chain.doFilter(servletRequest, servletResponse);
    }

    private String tokenCheck(rqust rqst){
        String bearerToken = rqst.getHeader(AUTHORIZATION_HEADER);
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
How to&Answers: