将JWT令牌传递给SockJS

Man*_*Pap 9 javascript java websocket sockjs spring-boot

当SockJS发生握手时,我需要发送令牌。我尝试了许多建议的实现,但是调用了相同的异常

java.lang.IllegalArgumentException: JWT String argument cannot be null or empty.
Run Code Online (Sandbox Code Playgroud)

在后端 WebSocketConfig

@Configuration
@EnableWebSocketMessageBroker
@CrossOrigin
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/socket");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/websocket").withSockJS();
    }
}
Run Code Online (Sandbox Code Playgroud)

尝试与套接字建立连接的函数。普通的javascript。

function connect() {
    var socket = new SockJS('http://localhost:8889/websocket',
             null,
            {
                transports: ['xhr-streaming'], 
                headers: {'Authorization': 'Bearer eyJhbGciOiJIUzUxMiJ9...' }
            });
    stompClient = Stomp.over(socket);
    stompClient.connect({},function (frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        stompClient.subscribe('/socket/event', function (greeting) {
            showGreeting(JSON.parse(greeting.body).content);
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

问题出在握手上,这些标头似乎未正确传递令牌。我已经尝试过多种握手方式,但是我找不到正确的方式。

在握手之后尝试使用标头之前,我从这里得到了实现的想法,但我发现它立即需要令牌。

https://github.com/sockjs/sockjs-client/issues/196#issuecomment-61469141

编辑:添加WebSecurityConfig

@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
        .cors()
        .configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues())
        .and()
        .csrf()
        .disable()
        .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()

        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
        .authorizeRequests()
        .antMatchers("/login/**").permitAll()
        .antMatchers("/websocket/**").permitAll()
        .anyRequest().authenticated();
        // Custom JWT based security filter
        JwtAuthorizationTokenFilter authenticationTokenFilter = new JwtAuthorizationTokenFilter(userDetailsService(), jwtTokenUtil, tokenHeader);
        httpSecurity
        .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }//end configure(HttpSecurity)
Run Code Online (Sandbox Code Playgroud)

createAuthenticationToken

@ApiOperation(value = "Login with the user credentials",
            response = JwtAuthenticationResponse.class)
    @ApiResponses(value = {
            @ApiResponse(code = 401, message = "Unauthorized"),
            @ApiResponse(code = 404, message = "Not Found",response = ExceptionResponse.class),
            @ApiResponse(code = 400, message = "Bad Request",response = ExceptionResponse.class),
            @ApiResponse(code = 200 , message = "OK", response = JwtAuthenticationResponse.class)
    })
    @RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(
            @ApiParam(value = "User's email and password", required = true)
            @RequestBody JwtAuthenticationRequest authenticationRequest) 
            throws AuthenticationException {
        ResponseEntity<?> response;
        //authenticate the user
        final User user = userService.getByEmail(authenticationRequest.getEmail());
        try {
            authenticate(user.getUsername(), authenticationRequest.getPassword(),user.getId(),user.getAuthority().getName());
            // Reload password post-security so we can generate the token
            final UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUsername());
            final String token = jwtTokenUtil.generateToken(userDetails);
            // Return the token
            response  = ResponseEntity.ok(new JwtAuthenticationResponse(token,user.getUsername(),user.getFirstName(),user.getLastName(),
                    user.getEmail(),user.getId(),user.getAuthority().getName(),jwtTokenUtil.getExpirationTime(token)));
        }catch(NullPointerException e) {
            response = new ResponseEntity<>(new ExceptionResponse(404,"User Not Found","Authentication Failure"),HttpStatus.NOT_FOUND);
        }catch(AuthenticationException e) {
            response = new ResponseEntity<>(new ExceptionResponse(400,"Invalid E-mail or Password","Authentication Failure"),HttpStatus.BAD_REQUEST);
        }//end try
                return response;
    }//end createAuthenticationToken(JwtAuthenticationRequest)
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪(从后端与websocket进行握手和连接时,已经捕获了四次相同的异常)。我将其添加到pastebin上,因为它会破坏帖子。

例外

2019-05-16 11:36:17.936  WARN 11584 --- [nio-8889-exec-9] a.d.s.JwtAuthorizationTokenFilter        : couldn't find bearer string, will ignore the header
2019-05-16 11:36:17.937 ERROR 11584 --- [nio-8889-exec-9] a.d.s.JwtAuthorizationTokenFilter        : an error occured during getting username from token

java.lang.IllegalArgumentException: JWT String argument cannot be null or empty.
    at io.jsonwebtoken.lang.Assert.hasText(Assert.java:135) ~[jjwt-0.9.0.jar:0.9.0]
    at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:479) ~[jjwt-0.9.0.jar:0.9.0]
    at io.jsonwebtoken.impl.DefaultJwtParser.parseClaimsJws(DefaultJwtParser.java:541) ~[jjwt-0.9.0.jar:0.9.0]
    at package.security.JwtTokenUtil.getAllClaimsFromToken(JwtTokenUtil.java:59) ~[classes/:na]
    at package.security.JwtTokenUtil.getClaimFromToken(JwtTokenUtil.java:52) ~[classes/:na]
    at package.security.JwtTokenUtil.getUsernameFromToken(JwtTokenUtil.java:34) ~[classes/:na]
    at package.security.JwtAuthorizationTokenFilter.extractUsername(JwtAuthorizationTokenFilter.java:79) [classes/:na]
    at package.security.JwtAuthorizationTokenFilter.doFilterInternal(JwtAuthorizationTokenFilter.java:44) [classes/:na]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    ...
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) [spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) [spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) [spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-4.3.11.RELEASE.jar:4.3.11.RELEASE]
    ...
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1457) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_201]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_201]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.20.jar:8.5.20]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_201]
Run Code Online (Sandbox Code Playgroud)

Bhu*_*yal 4

服务器端配置来注册自定义身份验证拦截器。请注意,拦截器只需要验证并设置 CONNECT 消息上的用户标头。Spring 记录并保存经过身份验证的用户,并将其与同一会话上的后续 STOMP 消息相关联。以下示例展示了如何注册自定义身份验证拦截器:

\n\n
  @Configuration\n    @EnableWebSocketMessageBroker\n    public class MyConfig implements WebSocketMessageBrokerConfigurer {\n\n        @Override\n        public void configureClientInboundChannel(ChannelRegistration registration) {\n            registration.interceptors(new ChannelInterceptor() {\n                @Override\n                public Message<?> preSend(Message<?> message, MessageChannel channel) {\n                    StompHeaderAccessor accessor =\n                            MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);\n                    if (StompCommand.CONNECT.equals(accessor.getCommand())) {\n                        Authentication user = ... ; // access authentication header(s)\n                        accessor.setUser(user);\n                    }\n                    return message;\n                }\n            });\n        }\n    }\n
Run Code Online (Sandbox Code Playgroud)\n\n

另请注意,当您使用 Spring Security\xe2\x80\x99s 进行消息授权时,目前需要确保身份验证 ChannelInterceptor 配置位于 Spring Security\xe2\x80\x99s 之前。最好通过在 WebSocketMessageBrokerConfigurer 自己的实现中声明自定义拦截器来完成此操作,并用 @Order(Ordered.HIGHEST_PRECEDENCE + 99) 进行标记。

\n\n

另一种方式:\n同样,SockJS JavaScript 客户端不提供通过 SockJS 传输请求发送 HTTP 标头的方法。正如您所看到的 sockjs-client 问题 196。相反,它确实允许发送可用于发送令牌的查询参数,然后使用 Spring 您可以设置一些过滤器,该过滤器将使用提供的令牌来识别会话。,但这有其自身的缺点(例如,令牌可能会无意中与服务器日志中的 URL 一起记录)。

\n\n

参考号

\n