I am using websocket in springboot. As my client side is authenticated through oauth2, so the access token is stored in localstorage (React JS). Now I want to open a websocket with stompjs to connect to my backend, what I did is
let stompClient = null;
let subscriber = null;
let connection;
...
const handleWebsocketConnection = () => {
if (connectedPromise !== null || alreadyConnectedOnce) {
// the connection is already being established
return;
}
connection = createConnection();
// listener = createListener();
// building absolute path so that websocket doesn't fail when deploying with a context path
const loc = window.location;
const baseHref = '';
let url = '//' + 'localhost:8080' + baseHref + '/websocket/tracker';
const authToken = localStorage.getItem('jhi-authenticationToken') || localStorage.getItem.get('jhi-authenticationToken');
if (authToken) {
url += '?access_token=' + authToken;
headers = {Authorization: `Bearer ${authToken}`};
}
console.log("auth_token", authToken)
console.log("url", url);
// const socket = new SockJS(url, null, {headers: {Authorization: `Bearer ${authToken}`}});
const socket = new SockJS(url);
stompClient = Stomp.over(socket);
stompClient.connect(headers, () => {
// console.log("header", headers)
subscribe();
connectedPromise('success');
connectedPromise = null;
sendActivity(window.location.pathname);
alreadyConnectedOnce = true;
});
}
const sendActivity = (page) => {
connection?.then(() => {
stompClient?.send(
'/topic/activity', // destination
JSON.stringify({ page }), // body
{} // header
);
});
};
const subscribe = () => {
console.log("call subscribe")
connection.then(() => {
subscriber = stompClient.subscribe('/topic/tracker', data => {
console.log("receive subscribe", data)
listenerObserver.next(JSON.parse(data.body));
});
});
};
...
In the backend, I have the follow websocket config:
General Security Configuration for both API and Websocket endpoints:
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
...
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringAntMatchers("/api/authenticate", "/websocket/**")
.and()
// .sessionManagement()
// .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// http
.addFilterBefore(corsFilter, CsrfFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
.and()
.headers()
.contentSecurityPolicy(jHipsterProperties.getSecurity().getContentSecurityPolicy())
.and()
.referrerPolicy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)
.and()
.permissionsPolicy().policy("camera=(), fullscreen=(self), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), sync-xhr=()")
.and()
.frameOptions()
.deny()
.and()
.authorizeRequests()
.antMatchers("/api/authenticate").permitAll()
...
.antMatchers("/api/auth-info").permitAll()
.antMatchers("/tracker/**").permitAll()
.antMatchers("/websocket/**").permitAll()
...
.and()
.oauth2Login()
.and()
.oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(authenticationConverter())
.and()
.and()
.oauth2Client();
// @formatter:on
}
...
}
Broker Configuration
@Configuration
@EnableWebSocketMessageBroker
public class WebsocketConfiguration implements WebSocketMessageBrokerConfigurer {
public static final String IP_ADDRESS = "IP_ADDRESS";
private final JHipsterProperties jHipsterProperties;
@Autowired
private UserService userService;
public WebsocketConfiguration(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
}
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
String[] allowedOrigins = Optional
.ofNullable(jHipsterProperties.getCors().getAllowedOrigins())
.map(origins -> origins.toArray(new String[0]))
.orElse(new String[0]);
registry
.addEndpoint("/websocket/tracker")
.setHandshakeHandler(defaultHandshakeHandler())
.setAllowedOrigins(allowedOrigins)
.withSockJS()
.setInterceptors(httpSessionHandshakeInterceptor());
}
@Bean
public HandshakeInterceptor httpSessionHandshakeInterceptor() {
return new HandshakeInterceptor() {
@Override
public boolean beforeHandshake(
ServerHttpRequest request,
ServerHttpResponse response,
WebSocketHandler wsHandler,
Map<String, Object> attributes
) throws Exception {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
attributes.put(IP_ADDRESS, servletRequest.getRemoteAddress());
}
return true;
}
@Override
public void afterHandshake(
ServerHttpRequest request,
ServerHttpResponse response,
WebSocketHandler wsHandler,
Exception exception
) {}
};
}
private DefaultHandshakeHandler defaultHandshakeHandler() {
return new DefaultHandshakeHandler() {
@Override
protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
Principal principal = request.getPrincipal();
if (principal == null) {
Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
principal = new AnonymousAuthenticationToken("WebsocketConfiguration", "anonymous", authorities);
}
return principal;
}
};
}
}
Websocket Security Config:
@Configuration
public class WebsocketSecurityConfiguration extends AbstractSecurityWebSocketMessageBrokerConfigurer {
@Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
messages
.simpTypeMatchers(SimpMessageType.CONNECT, SimpMessageType.HEARTBEAT, SimpMessageType.UNSUBSCRIBE, SimpMessageType.DISCONNECT).permitAll()
.nullDestMatcher()
.authenticated()
.simpDestMatchers("/topic/tracker")
.hasAuthority(AuthoritiesConstants.INTERNAL_STAFF)
// matches any destination that starts with /topic/
// (i.e. cannot send messages directly to /topic/)
// (i.e. cannot subscribe to /topic/messages/* to get messages sent to
// /topic/messages-user<id>)
.simpDestMatchers("/topic/**")
.authenticated()
// message types other than MESSAGE and SUBSCRIBE
.simpTypeMatchers(SimpMessageType.MESSAGE, SimpMessageType.SUBSCRIBE)
.denyAll()
// catch all
.anyMessage()
.denyAll();
}
/**
* Disables CSRF for Websockets.
*/
@Override
protected boolean sameOriginDisabled() {
return true;
}
}
My Endpoints:
@Controller
public class ActivityService implements ApplicationListener<SessionDisconnectEvent> {
private static final Logger log = LoggerFactory.getLogger(ActivityService.class);
private final SimpMessageSendingOperations messagingTemplate;
public ActivityService(SimpMessageSendingOperations messagingTemplate) {
this.messagingTemplate = messagingTemplate;
}
@MessageMapping("/topic/activity")
@SendTo("/topic/tracker")
public ActivityDTO sendActivity(@Payload ActivityDTO activityDTO, StompHeaderAccessor stompHeaderAccessor, Principal principal) {
activityDTO.setUserLogin(principal.getName());
activityDTO.setSessionId(stompHeaderAccessor.getSessionId());
activityDTO.setIpAddress(stompHeaderAccessor.getSessionAttributes().get(IP_ADDRESS).toString());
activityDTO.setTime(Instant.now());
log.debug("Sending user tracking data {}", activityDTO);
return activityDTO;
}
@Override
public void onApplicationEvent(SessionDisconnectEvent event) {
ActivityDTO activityDTO = new ActivityDTO();
activityDTO.setSessionId(event.getSessionId());
activityDTO.setPage("logout");
messagingTemplate.convertAndSend("/topic/tracker", activityDTO);
}
}
However, whenever function "handleWebsocketConnection" is called from my frontend, I received the error in my spring terminal:
2022-04-12 15:06:37.610 ERROR 48008 --- [ XNIO-1 I/O-4] o.s.w.s.m.StompSubProtocolHandler : Failed to send message to MessageChannel in session g34qfzzb:Failed to send message to ExecutorSubscribableChannel[clientInboundChannel]; nested exception is org.springframework.security.access.AccessDeniedException: Access is denied
It tells me that my access is denied to access that endpoint, and when I debug the code in function "determineUser", I got pricipal == null. So I believe spring does not parse my authorization header at all from the request. How to fix it?