'How to Implement oAuth2 Authentication in Springboot Websocket(without Stomp and socketJS)

Trying to implement oAuth2 Authentication in Springboot Websocket(Without STOMP and SOCKETJS) in before handshake .

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    private final Logger LOG =  LoggerFactory.getLogger(getClass());
    
    
    @Autowired
    private NotificationService notificationService;
    
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(notificationService, "/notification").addInterceptors(new HttpSessionHandshakeInterceptor() 
                  {
                    @Override
                    public void afterHandshake(ServerHttpRequest request, 
                     ServerHttpResponse response, WebSocketHandler wsHandler, 
                     @Nullable Exception ex) {

                        super.afterHandshake(request, response, wsHandler, ex);

                    }

                    @Override
                    public boolean beforeHandshake(ServerHttpRequest request, 
                     ServerHttpResponse response, WebSocketHandler wsHandler, 
                      Map<String, Object> attributes) throws Exception {
                              boolean b = super.beforeHandshake(request, response, 
                     wsHandler, attributes) && 
                  ((PreAuthenticatedAuthenticationToken) 
                request.getPrincipal()).isAuthenticated();
                        return b;
                    }
                     }).setAllowedOrigins("*");

Above code throws null pointer exception



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source