带有Spring后端的WebSocket在一段时间后失去连接,不会调用onclose

时间:2015-06-15 09:04:24

标签: spring spring-security websocket basic-authentication spring-websocket

在我们的spring应用程序中,大多数控制器都受到oauth安全保护。 Websockets是基本的。在访问websocket登录用户之前要求输入websocket连接的用户名和哈希密码。两者都将被生成,但是目前为了测试目的,它总是返回相同的信用额度。

信息的URL如下所示:

 https://user:debaee4affbeaba909a184066981d55a@localhost:8000/project-name/chat/info

正确打开WebSocket。我们可以发送少量消息,然后通过代理发送给用户。以下是Chrome工具的请求信息:

Remote Address:127.0.0.1:8000
Request URL:https://benny:debaee4affbeaba909a184066981d55a@localhost:8000/project-name/chat/033/7szz8k_f/xhr_send
Request Method:POST
Status Code:204 No Content

Response Headers:
HTTP/1.1 204 No Content
server: Apache-Coyote/1.1
x-content-type-options: nosniff
x-xss-protection: 1; mode=block
cache-control: no-cache, no-store, max-age=0, must-revalidate
pragma: no-cache
expires: 0
strict-transport-security: max-age=31536000 ; includeSubDomains
x-frame-options: DENY
access-control-allow-origin: https://localhost:8000
access-control-allow-credentials: true
vary: Origin
content-type: text/plain;charset=UTF-8
date: Mon, 15 Jun 2015 08:22:43 GMT
Connection: keep-alive

Request Headers:
POST /project-name/chat/033/7szz8k_f/xhr_send HTTP/1.1
Host: localhost:8000
Connection: keep-alive
Content-Length: 143
Origin: https://localhost:8000
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36
Content-Type: text/plain;charset=UTF-8
Accept: */*
Referer: https://localhost:8000/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,pl;q=0.6
Cookie: JSESSIONID=FF967D3DD1247C1D572C15CF8A3D5E8E; i18next=en; language=pl; tmhDynamicLocale.locale=%22pl-pl%22

["SEND\npriority:9\ndestination:/random/chat/1/FUNNY\ncontent-length:49\n\n{\"message\":\"sfsdf\",\"display\":\"The great wizard.\"}\u0000"]

但是在发送另一个请求一分钟后,我们得到了404响应。如果之前发出任何SEND请求并不重要。我们可以在该时间跨度内写入50条以上的消息,然后我们会得到404条消息。

示例404请求数据如下:

Remote Address:127.0.0.1:8000
Request URL:https://hill:debaee4affbeaba909a184066981d55a@localhost:8000/project-name/chat/033/7szz8k_f/xhr_send
Request Method:POST
Status Code:404 Not Found

Response Headers:
HTTP/1.1 404 Not Found
server: Apache-Coyote/1.1
x-content-type-options: nosniff
x-xss-protection: 1; mode=block
cache-control: no-cache, no-store, max-age=0, must-revalidate
pragma: no-cache
expires: 0
strict-transport-security: max-age=31536000 ; includeSubDomains
x-frame-options: DENY
content-length: 0
date: Mon, 15 Jun 2015 08:24:17 GMT
Connection: keep-alive

Request Headers:
POST /project-name/chat/033/7szz8k_f/xhr_send HTTP/1.1
Host: localhost:8000
Connection: keep-alive
Content-Length: 143
Origin: https://localhost:8000
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36
Content-Type: text/plain;charset=UTF-8
Accept: */*
Referer: https://localhost:8000/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,pl;q=0.6
Cookie: JSESSIONID=FF967D3DD1247C1D572C15CF8A3D5E8E; i18next=en; language=pl; tmhDynamicLocale.locale=%22pl-pl%22

Request Payload:
["SEND\npriority:9\ndestination:/random/chat/1/FUNNY\ncontent-length:49\n\n{\"message\":\"yhgfh\",\"username\":\"The great wizard.\"}\u0000"]

设置stomp时我们设置函数以响应onclose:

socket.client = new SockJS(targetUrl);
socket.stomp = Stomp.over(socket.client);
socket.stomp.connect({}, startListener);
socket.stomp.onclose = reconnect;

使用重新连接功能(在AngularJS中):

var reconnect = function() {
                    $log.debug('Reconnect called');
                    $timeout(function() {
                        initialize();
                    }, this.RECONNECT_TIMEOUT);
};

但是从不调用该函数。

聊天控制器非常简单:

@Controller
public class StageChatController {

    @Inject
    private SimpMessagingTemplate template;

    @Inject
    private ChatMessageRepository chatMessageRepository;

@MessageMapping("/chat/{channel}/{type}")
    public void sendMessage(@DestinationVariable Long channel, @DestinationVariable ChatType type, ChatMessageDto message) {
        ChatMessage chatMessage = new ChatMessage();

        chatMessage.setDatestamp(LocalDateTime.now());
        chatMessage.setMessage(message.getMessage());
        chatMessage.setChannelId(channel);
        chatMessage.setChatType(type);
        chatMessage.setDisplayName(message.getDisplay());

        chatMessage = this.chatMessageRepository.save(chatMessage);

        this.template.convertAndSend("/channel/" + project + "/" + type, chatMessage);
    }

聊天的安全性会覆盖聊天网址的oauth安全性:

@Configuration
    @EnableWebSecurity
    @Order(2)
    static class BasicAccessConfig extends WebSecurityConfigurerAdapter {

        @Inject
        private OAuth2ClientContextFilter oauth2ClientContextFilter;

        @Value("${project.name.chat.token}")
        private String chat_token;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            //@formatter:off
            http
            .requestMatcher(new AntPathRequestMatcher("/chat/**/*"))
            .authorizeRequests().anyRequest().authenticated()
            .and()
            .httpBasic()
            .and()
            .anonymous().disable()
            .csrf().disable()
            .addFilterBefore(this.oauth2ClientContextFilter, SecurityContextPersistenceFilter.class);
            ;
            //@formatter:on
        }

        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/assets/**");
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication().withUser("hill").password(this.chat_token).authorities("read_chat");
        }
    }

0 个答案:

没有答案