Reputation: 709
I have a Spring Boot project (2.0.0.RELEASE). I use JWT Token based authentication and authorization to secure REST. I also wanted to use Websocket with SockJS and use Token for socket authentication. I try to implement regarding this post, however I couldn't succeed.
First of all, my Security configuration is below;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final TokenAuthenticationService tokenAuthenticationService;
private final ObjectMapper mapper;
@Autowired
protected SecurityConfig(final TokenAuthenticationService tokenAuthenticationService, ObjectMapper mapper) {
super();
this.tokenAuthenticationService = tokenAuthenticationService;
this.mapper = mapper;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers()
.frameOptions().disable()
.and()
.authorizeRequests()
.antMatchers("/api/v3/auth").permitAll()
.antMatchers("/api/v3/signup").permitAll()
.antMatchers("/api/v3/websocket/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(new RestAuthenticationEntryPoint(mapper))
.and()
.addFilterBefore(new AuthenticationTokenFilter(tokenAuthenticationService), UsernamePasswordAuthenticationFilter.class)
.cors()
.and()
.csrf().disable();
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("GET");
config.addAllowedMethod("POST");
config.addAllowedMethod("PUT");
config.addAllowedMethod("DELETE");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
In application, to get a token, one should make a POST request to /api/v3/auth
. /api/v3/websocket
is the websocket endpoint. My Websocket Config class is below.
@Configuration
@EnableWebSocketMessageBroker
@Order(Ordered.HIGHEST_PRECEDENCE + 50)
public class SocketBrokerConfig implements WebSocketMessageBrokerConfigurer {
private static final Logger log = LoggerFactory.getLogger(SocketBrokerConfig.class);
private final TokenAuthenticationService authenticationService;
@Autowired
public SocketBrokerConfig(TokenAuthenticationService authenticationService) {
this.authenticationService = authenticationService;
}
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic", "/queue");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
log.info("registering websockets");
registry
.addEndpoint("/api/v3/websocket")
.setAllowedOrigins("*")
.withSockJS()
.setClientLibraryUrl("https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.1.4/sockjs.min.js")
.setWebSocketEnabled(false)
.setSessionCookieNeeded(false);
}
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(new ChannelInterceptorAdapter() {
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
log.info("in override " + accessor.getCommand());
if (StompCommand.CONNECT.equals(accessor.getCommand())) {
// Authentication auth = SecurityContextHolder.getContext().getAuthentication();
// String name = auth.getName(); //get logged in username
// System.out.println("Authenticated User : " + name);
String authToken = accessor.getFirstNativeHeader("x-auth-token");
log.info("Header auth token: " + authToken);
Principal principal = authenticationService.getUserFromToken(authToken);
if (Objects.isNull(principal))
return null;
accessor.setUser(principal);
} else if (StompCommand.DISCONNECT.equals(accessor.getCommand())) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (Objects.nonNull(authentication))
log.info("Disconnected Auth : " + authentication.getName());
else
log.info("Disconnected Sess : " + accessor.getSessionId());
}
return message;
}
@Override
public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
StompHeaderAccessor sha = StompHeaderAccessor.wrap(message);
// ignore non-STOMP messages like heartbeat messages
if (sha.getCommand() == null) {
log.warn("postSend null command");
return;
}
String sessionId = sha.getSessionId();
switch (sha.getCommand()) {
case CONNECT:
log.info("STOMP Connect [sessionId: " + sessionId + "]");
break;
case CONNECTED:
log.info("STOMP Connected [sessionId: " + sessionId + "]");
break;
case DISCONNECT:
log.info("STOMP Disconnect [sessionId: " + sessionId + "]");
break;
default:
break;
}
}
});
}
}
Also my Websocket Security Config class is;
@Configuration
public class SocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
@Override
protected boolean sameOriginDisabled() {
// We need to access this directly from apps, so can't do cross-site checks
return true;
}
}
Finally my test JS file is below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"/>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/test/ws">Test Client</a>
</div>
</div>
</nav>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.1.4/sockjs.min.js"></script>
<script type="application/javascript">
var endpoint = "http://192.168.0.58:8080/api/v3/auth";
var login = {username: "admin", password: "password"};
$.ajax({
type: "POST",
url: endpoint,
data: JSON.stringify(login),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
success: function (data) {
var socket = new SockJS("http://192.168.0.58:8080/api/v3/websocket/");
var stompClient = Stomp.over(socket);
var headers = {
'client-id': 'my-client-id',
'x-auth-token': data.data.token
};
stompClient.connect(headers, function (frame) {
console.log("Connected ?!");
console.log(frame);
stompClient.subscribe(
"/user/queue/admin",
function (message) {
console.log("Message arrived");
console.log(message);
}
);
});
}
});
</script>
</body>
</html>
After JS code get token from /api/v3/auth
, it tries to connect /api/v3/websocket
. However, the overridden ChannelInterceptorAdapter's preSend
method never invoked on Server side. Code never reach this method. In fact, CONNECT command never reach here, when I close the browser, DISCONNECT command reaches as an anonymousUser
. When JS trying to CONNECT, the authenticate method of my JsonWebTokenAuthenticationService
invokes repeatedly.
The console output of browser is;
XHROPTIONS
http://192.168.0.58:8080/api/v3/auth
[HTTP/1.1 200 4ms]
XHRPOST
http://192.168.0.58:8080/api/v3/auth
[HTTP/1.1 200 7ms]
Object { data: {…} }
index.html:123:12
Opening Web Socket...
stomp.min.js:8:1737
XHRGET
http://192.168.0.58:8080/api/v3/websocket/info?t=1523448356260
[HTTP/1.1 200 4ms]
XHRGET
http://192.168.0.58:8080/api/v3/websocket/848/s1t1xcij/eventsource
XHRGET
http://192.168.0.58:8080/api/v3/websocket/848/suu5lc11/eventsource
XHRPOST
http://192.168.0.58:8080/api/v3/websocket/848/zzjmmaf4/xhr?t=1523448359012
[HTTP/1.1 200 10012ms]
Whoops! Lost connection to http://192.168.0.58:8080/api/v3/websocket
I tried a lot of different code pieces around the internet but couldn't succeed.
My question is why my client's CONNECT command fall into overridden interceptor while DISCONNECT command fall?
I add my TokenAuthenticationService implementation below. I noticed that, if I put a debug point in authenticate method and wait couple of second and resume, websocket client connect and CONNECT command falls into preSend method.
What does happen when I stop authenticate method for a couple of seconds and why?
@Service
public class JsonWebTokenAuthenticationService implements TokenAuthenticationService {
private static final Logger log = LoggerFactory.getLogger(JsonWebTokenAuthenticationService.class);
@Value("security.token.secret.key")
private String secretKey;
private final UserRepository userRepository;
@Autowired
public JsonWebTokenAuthenticationService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public Authentication authenticate(HttpServletRequest request) {
final String token = request.getHeader("x-auth-token");
final Jws<Claims> tokenData = parseToken(token);
if (Objects.nonNull(tokenData)) {
User user = getUserFromToken(tokenData);
if (Objects.nonNull(user) && user.isEnabled()) {
return new UserAuthentication(user);
}
}
return null;
}
public Authentication getUserFromToken(String token) {
if (Objects.isNull(token))
return null;
final Jws<Claims> tokenData = parseToken(token);
if (Objects.nonNull(tokenData)) {
User user = getUserFromToken(tokenData);
if (Objects.nonNull(user) && user.isEnabled()) {
return new UserAuthentication(user);
}
}
return null;
}
private Jws<Claims> parseToken(final String token) {
if (Objects.nonNull(token)) {
try {
return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
} catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException
| SignatureException | IllegalArgumentException e) {
log.warn("Token parse failed", e);
return null;
}
}
return null;
}
private User getUserFromToken(final Jws<Claims> tokenData) {
try {
return userRepository.findByUsername(tokenData.getBody().get("username").toString());
} catch (UsernameNotFoundException e) {
log.warn("No user", e);
}
return null;
}
}
I added a Thread.sleep(2000)
(which I shouldn't) inside my AuthenticationTokenFilter#doFilter
method and JS client now connects, subscribes etc. And the STOMP's CONNECT command falls into ChannelInterceptorAdapter#preSend
method. It seemed a little strange to me.
Upvotes: 6
Views: 10492
Reputation: 709
After the EDIT2, I faced this problem. And it turned out all the problem caused by the router. Still I don't understand what happened, however it works now as expected.
Upvotes: 0