我正在使用SimpUserRegistry
获取在线用户数(使用getUserCount()
)。它在我的本地计算机上运行良好,但在仅具有弹性IP且没有负载平衡器的AWS EC2实例(与Amazon Linux和Ubuntu进行尝试)上却无法正常运行。
EC2上的问题是,某些用户在连接时从未添加到注册表中,因此我得到了错误的结果。
我有SessionConnectedEvent
和SessionDisconnectEvent
的 session 监听器,在这里我使用SimpUserRegistry
( Autowiring )来获得用户的状态。如果有关系,我也是SimpUserRegistry
是消息传递 Controller 。
以下是websocket消息代理配置:
@Order(Ordered.HIGHEST_PRECEDENCE + 99)
@Configuration
@EnableWebSocketMessageBroker
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WebSocketMessageBrokerConfig extends AbstractWebSocketMessageBrokerConfigurer {
@NonNull
private SecurityChannelInterceptor securityChannelInterceptor;
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(1);
threadPoolTaskScheduler.setThreadGroupName("cb-heartbeat-");
threadPoolTaskScheduler.initialize();
config.enableSimpleBroker("/queue/", "/topic/")
.setTaskScheduler(threadPoolTaskScheduler)
.setHeartbeatValue(new long[] {1000, 1000});
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websocket")
.setAllowedOrigins("*")
.withSockJS();
}
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(securityChannelInterceptor);
}
}
下面是上面的config类中使用的 channel 拦截器:
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SecurityChannelInterceptor extends ChannelInterceptorAdapter {
@NonNull
private SecurityService securityService;
@Value("${app.auth.token.header}")
private String authTokenHeader;
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
StompCommand command = accessor.getCommand();
if (StompCommand.CONNECT.equals(command)) {
List<String> authTokenList = accessor.getNativeHeader(authTokenHeader);
if (authTokenList == null || authTokenList.isEmpty()) {
throw new AuthenticationFailureException("STOMP " + command + " missing " + this.authTokenHeader + " header!");
}
String accessToken = authTokenList.get(0);
AppAuth authentication = securityService.authenticate(accessToken);
log.info("STOMP {} authenticated. Authentication Token = {}", command, authentication);
accessor.setUser(authentication);
SecurityContextHolder.getContext().setAuthentication(authentication);
Principal principal = accessor.getUser();
if (principal == null) {
throw new RuntimeException("StompHeaderAccessor did not set the authenticated User for " + authentication);
}
}
return message;
}
}
我还有以下计划任务,该任务仅每两秒打印一次用户名:
@Component
@Slf4j
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class UserRegistryLoggingTask {
private SimpUserRegistry simpUserRegistry;
@Scheduled(fixedRate = 2000)
public void logUsersInUserRegistry() {
Set<String> userNames = simpUserRegistry.getUsers().stream().map(u -> u.getName()).collect(Collectors.toSet());
log.info("UserRegistry has {} users with IDs {}", userNames.size(), userNames);
}
}
而且有些用户名即使连接也永远不会显示。
SecurityService
类的实现-@Service
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class SecurityService {
private UserRepository userRepository;
private UserCredentialsRepository userCredentialsRepository;
private JwtHelper jwtHelper;
public User getUser() {
AppAuth auth = (AppAuth) SecurityContextHolder.getContext().getAuthentication();
User user = (User) auth.getUser();
return user;
}
public AppAuth authenticate(String accessToken) {
String username = jwtHelper.tryExtractSubject(accessToken);
if (username == null) {
throw new AuthenticationFailureException("Invalid access token!");
}
User user = userRepository.findByUsername(username);
if (user == null) {
throw new AuthenticationFailureException("Invalid access token!");
}
AppAuth authentication = new AppAuth(user);
return authentication;
}
}
更新
以下是在浏览器上登录SockJS的示例-
来自服务器的正确响应,带有
user-name
header :>>> CONNECT
AccessToken:eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJkb2cifQ.Wf8AO77LluHEfEv61TIvugEXxOqIXKjsJBO8QMQh-rF7tzf56lBkdpOruqc7UPf_Pmj6-dnHZ5raq2MnMpeG8Q
accept-version:1.1,1.0
heart-beat:10000,10000
<<< CONNECTED
version:1.1
heart-beat:1000,1000
user-name:5a590e411b96f841cc00027f
来自没有
user-name
header 的服务器的错误响应:>>> CONNECT
AccessToken:eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJtb3VzZSJ9.wqX5X_CSdHD8_7PZPiSzftGCuPz1ClQU0-F9RHCqOIIkMLzI4rt31_EAaykc8VojK2KGS6DcycWfAdMr2edzYg
accept-version:1.1,1.0
heart-beat:10000,10000
<<< CONNECTED
version:1.1
heart-beat:1000,1000
我还验证了
SecurityChannelInterceptor
正在对所有用户进行身份验证,即使user-name
不在CONNECTED
响应中也是如此。更新
我在heroku上部署了该应用程序。问题也在那里发生。
更新
发生问题时,
user
中的SessionConnectEvent
是SecurityChannelInterceptor
设置的一个,但user
中的SessionConnectedEvent
是null
。更新
AppAuth
类-public class AppAuth implements Authentication {
private final User user;
private final Collection<GrantedAuthority> authorities;
public AppAuth(User user) {
this.user = user;
this.authorities = Collections.singleton((GrantedAuthority) () -> "USER");
}
public User getUser() {
return this.user;
}
@Override
public String getName() {
return user.getId();
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public Object getCredentials() {
return null;
}
@Override
public Object getDetails() {
return null;
}
@Override
public Object getPrincipal() {
return new Principal() {
@Override
public String getName() {
return user.getId();
}
};
}
@Override
public boolean isAuthenticated() {
return true;
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
}
}
最佳答案
经过一些调试后,我可以通过在StompSubProtocolHandler
中添加一些记录器语句来跟踪此问题。
找到原因后,得出的结论是 channel 拦截器不是验证用户身份的正确位置。至少在我的用例中。
以下是 StompSubProtocolHandler
的一些代码段-handleMessageFromClient
方法将用户添加到stompAuthentications
映射并发布SessionConnectEvent
事件-
public void handleMessageFromClient(WebSocketSession session, WebSocketMessage<?> webSocketMessage, MessageChannel outputChannel) {
//...
SimpAttributesContextHolder.setAttributesFromMessage(message);
boolean sent = outputChannel.send(message);
if (sent) {
if (isConnect) {
Principal user = headerAccessor.getUser();
if (user != null && user != session.getPrincipal()) {
this.stompAuthentications.put(session.getId(), user);
}
}
if (this.eventPublisher != null) {
if (isConnect) {
publishEvent(new SessionConnectEvent(this, message, getUser(session)));
}
//...
然后
handleMessageToClient
从stompAuthentications
映射中检索用户并发布SessionConnectedEvent
-public void handleMessageToClient(WebSocketSession session, Message<?> message) {
//...
SimpAttributes simpAttributes = new SimpAttributes(session.getId(), session.getAttributes());
SimpAttributesContextHolder.setAttributes(simpAttributes);
Principal user = getUser(session);
publishEvent(new SessionConnectedEvent(this, (Message<byte[]>) message, user));
//...
上述方法使用的
getUser
方法-private Principal getUser(WebSocketSession session) {
Principal user = this.stompAuthentications.get(session.getId());
return user != null ? user : session.getPrincipal();
}
现在,当在
handleMessageToClient
片段之前执行handleMessageFromClient
片段时,就会出现问题。在这种情况下,永远不会将用户添加到DefaultSimpUserRegistry
中,因为它只会检查SessionConnectedEvent
。以下是
DefaultSimpUserRegistry
的事件监听器代码段-public void onApplicationEvent(ApplicationEvent event) {
//...
else if (event instanceof SessionConnectedEvent) {
Principal user = subProtocolEvent.getUser();
if (user == null) {
return;
}
//...
解决方案
解决方案是扩展
DefaultHandshakeHandler
并覆盖基于this answer的determineUser
方法。但是,当我使用SockJS时,这要求客户端发送auth-token作为查询参数。并讨论了查询参数要求的原因here。