title: Spring Websockets Authentication with Spring Security and Keycloak
body: <p>I'm using Spring Boot (v1.5.10.RELEASE) to create a backend for an application written in Angular. The back is secured using spring security + keycloak. Now I'm adding a websocket, using STOMP over SockJS, and wanted to secure it. I'm trying to follow the docs at <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#websocket-stomp-authentication-token-based" rel="noreferrer">Websocket Token Authentication</a>, and it shows the following piece of code:</p>
  
  <pre><code>if (StompCommand.CONNECT.equals(accessor.getCommand())) {
    Authentication user = ... ; // access authentication header(s)
    accessor.setUser(user);
  }
  </code></pre>
  
  <p>I'm able to retrieve the bearer token from the client using:</p>
  
  <pre><code>String token = accessor.getNativeHeader("Authorization").get(0);
  </code></pre>
  
  <p>My question is, how can I convert that to an Authentication object? Or how to proceed from here? Because I always get 403. This is my websocket security config:</p>
  
  <pre><code>@Configuration
  public class WebSocketSecurityConfig extends 
       AbstractSecurityWebSocketMessageBrokerConfigurer {
  
  @Override
  protected void configureInbound(MessageSecurityMetadataSourceRegistry 
      messages) {
  messages.simpDestMatchers("/app/**").authenticated().simpSubscribeDestMatchers("/topic/**").authenticated()
      .anyMessage().denyAll();
  }
  
    @Override
    protected boolean sameOriginDisabled() {
      return true;
    }
  }
  </code></pre>
  
  <p>And this is the Web security configuration:</p>
  
  <pre><code>@EnableWebSecurity
  @EnableGlobalMethodSecurity(prePostEnabled = true)
  @Configuration
  public class WebSecurityConfiguration extends KeycloakWebSecurityConfigurerAdapter {
  
    @Override
    protected void configure(HttpSecurity http) throws Exception {
      http
          .csrf().disable()
          .authenticationProvider(keycloakAuthenticationProvider())
          .addFilterBefore(keycloakAuthenticationProcessingFilter(), BasicAuthenticationFilter.class)
          .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .sessionAuthenticationStrategy(sessionAuthenticationStrategy())
          .and()
          .authorizeRequests()
            .requestMatchers(new NegatedRequestMatcher(new AntPathRequestMatcher("/management/**")))
              .hasRole("USER");
    }
  
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
      return new NullAuthenticatedSessionStrategy();
    }
  
    @Bean
    public KeycloakConfigResolver KeycloakConfigResolver() {
      return new KeycloakSpringBootConfigResolver();
    }
  
  }
  </code></pre>
  
  <p>Any help or ideas are welcome.</p>