带有 JWT 令牌的 Spring Security 和 Websocket

Posted

技术标签:

【中文标题】带有 JWT 令牌的 Spring Security 和 Websocket【英文标题】:Spring Security and Websocket with JWT Token 【发布时间】:2018-09-21 07:32:28 【问题描述】:

我有一个 Spring Boot 项目 (2.0.0.RELEASE)。我使用基于 JWT 令牌的身份验证和授权来保护 REST。我还想将 Websocket 与 SockJS 一起使用,并使用 Token 进行套接字身份验证。我尝试实现关于this post,但是我无法成功。

首先,我的安全配置如下;

@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);
    

在应用程序中,要获取令牌,应向/api/v3/auth 发出 POST 请求。 /api/v3/websocket 是 websocket 端点。我的 Websocket Config 类如下。

@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;

                
            
        );

    

我的 Websocket 安全配置类也是;

@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;
    

最后我的测试JS文件如下。

<!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>

JS 代码从/api/v3/auth 获取令牌后,尝试连接/api/v3/websocket。但是,覆盖的 ChannelInterceptorAdapter 的 preSend 方法从未在服务器端调用。代码永远不会达到这个方法。事实上,CONNECT 命令永远不会到达这里,当我关闭浏览器时,DISCONNECT 命令会到达anonymousUser。当 JS 尝试连接时,我的 JsonWebTokenAuthenticationService 的 authenticate 方法会重复调用。

浏览器的控制台输出是;

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

我在互联网上尝试了很多不同的代码片段,但都没有成功。

我的问题是为什么我的客户的 CONNECT 命令落入被覆盖的拦截器而 DISCONNECT 命令落入?

**EDIT1**

我在下面添加了我的 TokenAuthenticationService 实现。我注意到,如果我在身份验证方法中放置一个调试点并等待几秒钟并恢复,websocket 客户端连接和 CONNECT 命令落入 preSend 方法。

当我停止验证方法几秒钟后会发生什么?为什么?

@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;
    

**EDIT2**

我在AuthenticationTokenFilter#doFilter 方法中添加了一个Thread.sleep(2000)(我不应该这样做),JS 客户端现在连接、订阅等。STOMP 的 CONNECT 命令属于ChannelInterceptorAdapter#preSend 方法。我觉得有点奇怪。

【问题讨论】:

【参考方案1】:

EDIT2之后,我面对的是this problem。事实证明,所有问题都是由路由器引起的。我仍然不明白发生了什么,但它现在按预期工作。

【讨论】:

以上是关于带有 JWT 令牌的 Spring Security 和 Websocket的主要内容,如果未能解决你的问题,请参考以下文章

使用带有令牌的 spring 安全插件的一个好习惯

带有加密 JWT 访问令牌的 Spring Boot OAuth2

带有刷新令牌工作流问题的 Java Spring JWT

使用带有spring security的keycloak JWT令牌时如何修复403

带有 JWT auth 和 csrf 令牌的 Spring Boot STATELESS 应用程序

Spring OAuth/JWT 从访问令牌中获取额外信息