如何防止Spring生成默认的simpSessionId?

时间:2016-06-13 19:29:36

标签: spring-security spring-websocket spring-messaging

我正在尝试使用websockets和STOMP设置弹簧。

在客户端上,我发送一个标头变量 'simpSessionId':%SESSION_ID%

但是,在收到消息时,它总是将提供的头部放在一个名为nativeHeaders的密钥中,并在头根目录中放置一个默认的simpSessionId。

{simpMessageType=MESSAGE, stompCommand=SEND, nativeHeaders={SPRING.SESSION.ID=[5b1f11d0-ad92-4855-ae44-b2052ecd76d8], Content-Type=[application/json], X-Requested-With=[XMLHttpRequest], simpSessionId=[5b1f11d0-ad92-4855-ae44-b2052ecd76d8], accept-version=[1.2,1.1,1.0], heart-beat=[0,0], destination=[/mobile-server/ping], content-length=[15]}, simpSessionAttributes={}, simpSessionId=1, simpDestination=/mobile-server/ping}

如何让spring获取提供的会话ID?

被修改

好的,我有一个手机应用程序和一个网站点击同一台服务器。我需要能够在手机应用程序上设置一个webocket。

在手机应用程序上,我通过传统的REST端点登录服务器,如果成功,我会在响应中收到会话ID。

我在手机上使用webstomp-client,Spring 4.1.9,Spring Security 4.1,Spring Session 1.2.0。

我理想情况下使用令牌登录套接字CONNECT上的STOMP websocket,但我知道他目前是不可能的,因为webstomp-client不会在CONNECT上传递自定义标头。

我有两个问题:

  • 如何在后续请求中传递我在REST登录中检索的会话ID?我已经尝试添加诸如SPRING.SESSION.ID之类的标题,但是逐步执行代码我总是看到消息处理返回到simpSessionId,它始终默认为1,2等。我尝试扩展AbstractSessionWebsocketMessageBrokerConfigurer,但它它不会获取我的会话ID,它总是在simpSessionAttributes中查找,它始终为空。

  • 代码似乎也尝试获取http会话,这是一个Web浏览器方案。我假设我应该忽略这个

  • 会话过期。可能已过期的会话策略应该是什么?我不应该也传递一个remember-me风格的身份验证令牌吗?或者我应该依靠一些永恒的无状态会话?这对我来说并不清楚,这方面似乎没有记载。

显然,我做错了。这是我的配置:

@Configuration   @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1200)   公共类SessionConfig {

@Inject
ContentNegotiationManager contentNegotiationManager;

@Bean
public RedisConnectionFactory redisConnectionFactory(
        @Value("${spring.redis.host}") String host,
        @Value("${spring.redis.password}") String password,
        @Value("${spring.redis.port}") Integer port) {
    JedisConnectionFactory redis = new JedisConnectionFactory();
    redis.setUsePool(true);
    redis.setHostName(host);
    redis.setPort(port);
    redis.setPassword(password);
    redis.afterPropertiesSet();
    return redis;
}

@Bean
  public RedisTemplate<String,ExpiringSession> redisTemplate(RedisConnectionFactory connectionFactory) {
      RedisTemplate<String, ExpiringSession> template = new RedisTemplate<String, ExpiringSession>();
      template.setKeySerializer(new StringRedisSerializer());
      template.setHashKeySerializer(new StringRedisSerializer());
      template.setConnectionFactory(connectionFactory);
      return template;
  }

@Bean
public <S extends ExpiringSession>SessionRepositoryFilter<? extends ExpiringSession> sessionRepositoryFilter(SessionRepository<S> sessionRepository) {
    return new SessionRepositoryFilter<S>(sessionRepository);
}

@Bean
  public HttpSessionEventPublisher httpSessionEventPublisher() {
          return new HttpSessionEventPublisher();
  }

@Bean
public HttpSessionStrategy httpSessionStrategy(){
    return new SmartSessionStrategy();
}

@Bean
  public CookieSerializer cookieSerializer() {
          DefaultCookieSerializer serializer = new DefaultCookieSerializer();
          serializer.setCookieName("JSESSIONID"); 
          serializer.setCookiePath("/");
          serializer.setUseSecureCookie(true);
          serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$"); 
          return serializer;
  }

}

===

public class SessionWebApplicationInitializer extends AbstractHttpSessionApplicationInitializer {

    public SessionWebApplicationInitializer() {
    }

    public SessionWebApplicationInitializer(Class<?>... configurationClasses) {
        super(configurationClasses);
    }

    @Override
    protected void beforeSessionRepositoryFilter(ServletContext servletContext) {
        Dynamic registration = servletContext.addFilter("openSessionInViewFilter", new OpenSessionInViewFilter());
        if (registration == null) {
            throw new IllegalStateException(
                    "Duplicate Filter registration for openSessionInViewFilter. Check to ensure the Filter is only configured once.");
        }
        registration.setAsyncSupported(false);
        EnumSet<DispatcherType> dispatcherTypes = getSessionDispatcherTypes();
        registration.addMappingForUrlPatterns(dispatcherTypes, false,"/*");
    }

}

==

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig<S extends ExpiringSession> extends AbstractSessionWebsocketMessageBrokerConfigurer<S>{

    @Inject
    SessionRepository<S> sessionRepository;

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic", "/queue");

        config.setApplicationDestinationPrefixes("/mobile-server");

        config.setUserDestinationPrefix("/mobile-user");

    }

    @Override
    public void configureStompEndpoints(StompEndpointRegistry registry) {
        registry
            .addEndpoint("/ws")
            .setHandshakeHandler(new SessionHandShakeHandler(new TomcatRequestUpgradeStrategy()))
            .setAllowedOrigins("*")
            .withSockJS()
            .setSessionCookieNeeded(false)
            ;
    }

    @Override
    public void configureWebSocketTransport(WebSocketTransportRegistration registration) {
        registration.setMessageSizeLimit(512 * 1024);
        registration.setSendBufferSizeLimit(1024 * 1024);
        registration.setSendTimeLimit(40000);
    }

    @Bean
    public WebSocketConnectHandler<S> webSocketConnectHandler(SimpMessageSendingOperations messagingTemplate, UsorManager userMgr) {
        return new WebSocketConnectHandler<S>(messagingTemplate, userMgr);
    }

    @Bean
    public WebSocketDisconnectHandler<S> webSocketDisconnectHandler(SimpMessageSendingOperations messagingTemplate, WebSocketManager repository) {
        return new WebSocketDisconnectHandler<S>(messagingTemplate, repository);
    }

}

====

@Configuration
public class WebSocketSecurity extends AbstractSecurityWebSocketMessageBrokerConfigurer{

    ApplicationContext context = null;

    public void setApplicationContext(ApplicationContext context) {
        this.context = context;
    }

    @Override
    protected boolean sameOriginDisabled() {
        return true;
    }

    @Override
    protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
        messages
            .nullDestMatcher().permitAll()
            .simpSubscribeDestMatchers("/user/queue/errors").permitAll()
            .simpDestMatchers("/mobile-server/ping").authenticated()
            .simpDestMatchers("/mobile-server/csrf").authenticated()
            .simpDestMatchers("/mobile-server/**").hasRole("ENDUSER")
            .simpSubscribeDestMatchers("/user/**", "/topic/**").hasRole("ENDUSER")
            .anyMessage().denyAll();
    }

}

=== 为简洁起见,我删除了一些其他安全配置。

@Configuration @EnableWebSecurity @Order(100) 公共类SecurityConfig扩展了WebSecurityConfigurerAdapter {

private static final String REMEMBER_ME_COOKIE = "SPRING_SECURITY_REMEMBER_ME_COOKIE";

@Inject
FilterInvocationSecurityMetadataSource securityMetadataSource;

@Inject
SessionRepositoryFilter<? extends ExpiringSession> sessionRepositoryFilter;

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {

    DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
    provider.setSaltSource(saltSource);
    provider.setUserDetailsService(userMgr);
    provider.setPasswordEncoder(passwordEncoder);
    provider.setMessageSource(messages);
    auth.authenticationProvider(provider);

}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
}

@Bean
public AuthenticationTokenProcessingFilter authenticationTokenProcessingFilter() throws Exception{
    return new AuthenticationTokenProcessingFilter(authenticationManagerBean());
}

@Bean
public FilterSecurityInterceptor myFilterSecurityInterceptor(
        AuthenticationManager authenticationManager, 
        AccessDecisionManager accessDecisionManager,
        FilterInvocationSecurityMetadataSource metadataSource){
    FilterSecurityInterceptor interceptor = new FilterSecurityInterceptor();
    interceptor.setAuthenticationManager(authenticationManager);
    interceptor.setAccessDecisionManager(accessDecisionManager);
    interceptor.setSecurityMetadataSource(securityMetadataSource);
    interceptor.setSecurityMetadataSource(metadataSource);
    return interceptor;
}

@Bean
public AccessDecisionManager accessDecisionManager(SiteConfig siteConfig){
    URLBasedSecurityExpressionHandler expressionHandler = new URLBasedSecurityExpressionHandler();
    expressionHandler.setSiteConfig(siteConfig);

    WebExpressionVoter webExpressionVoter = new WebExpressionVoter();
    webExpressionVoter.setExpressionHandler(expressionHandler);

    return new AffirmativeBased(Lists.newArrayList(
            webExpressionVoter,
            new RoleVoter(),
            new AuthenticatedVoter()
    ));
}

public PasswordFixingAuthenticationProvider customAuthenticationProvider(PasswordEncoder passwordEncoder, SaltSource saltSource){
    PasswordFixingAuthenticationProvider provider = new PasswordFixingAuthenticationProvider();
    provider.setUserDetailsService(userMgr);
    provider.setPasswordEncoder(passwordEncoder);
    provider.setSaltSource(saltSource);

    return provider;
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .addFilterBefore(sessionRepositoryFilter, ChannelProcessingFilter.class)
        .antMatcher("/ws/**")
        .exceptionHandling()
            .accessDeniedPage("/mobile/403")
            .and()
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
        .csrf().disable()
        .authorizeRequests()
            .antMatchers("/ws").permitAll()
            .antMatchers("/ws/websocket").permitAll()
            .antMatchers("/ws/**").denyAll();           
       .anyRequest().requiresSecure()

    ;
}

}

===

  public class SmartSessionStrategy implements HttpSessionStrategy {

    private HttpSessionStrategy browser;

    private HttpSessionStrategy api;

    private RequestMatcher browserMatcher = null;

    public SmartSessionStrategy(){
        this.browser = new CookieHttpSessionStrategy();
        HeaderHttpSessionStrategy headerSessionStrategy = new HeaderHttpSessionStrategy();
        headerSessionStrategy.setHeaderName(CustomSessionRepositoryMessageInterceptor.SPRING_SESSION_ID_ATTR_NAME);
        this.api = headerSessionStrategy;
    }

    @Override
    public String getRequestedSessionId(HttpServletRequest request) {
        return getStrategy(request).getRequestedSessionId(request);
    }

    @Override
    public void onNewSession(Session session, HttpServletRequest request, HttpServletResponse response) {
        getStrategy(request).onNewSession(session, request, response);
    }

    @Override
    public void onInvalidateSession(HttpServletRequest request, HttpServletResponse response) {
        getStrategy(request).onInvalidateSession(request, response);
    }

    private HttpSessionStrategy getStrategy(HttpServletRequest request) {
        if(this.browserMatcher != null)
            return this.browserMatcher.matches(request) ? this.browser : this.api;

        return SecurityRequestUtils.isApiRequest(request) ? this.api : this.browser;
    }
  }

1 个答案:

答案 0 :(得分:2)

我认为这个问题是基于无效的期望开始的。您无法传递会话ID,也不能传入。您无法在STOMP协议级别登录,也不是它的工作方式。

虽然STOMP协议允许在CONNECT帧中传递用户凭证,这对于STOMP over TCP更有用。在HTTP场景中,我们已经拥有了可依赖的身份验证和授权机制。当您到达STOMP CONNECT时,您必须通过WebSocket握手URL的身份验证和授权。

如果您还没有阅读过,那么我将从Authentication上的Spring参考文档开始获取STOMP / WebSocket消息:

  

进行WebSocket握手并进行新的WebSocket会话时   创建后,Spring的WebSocket支持自动传播   java.security.Principal从HTTP请求到WebSocket   会话。之后,每个消息都流经应用程序   WebSocket会话充满了用户信息。它的   以邮件形式显示在邮件中。

换句话说,身份验证与现有Web应用程序相同。公开WebSocket端点的URL只是应用程序的另一个HTTP端点。所有其他HTTP端点都受到保护的方式与WebSocket握手的安全方式相同。就像其他HTTP端点一样,您不会传递会话ID。相反,您在通过cookie维护的现有HTTP会话中。

除非Spring Security首先对HTTP URL进行身份验证和授权,否则无法建立握手。从那里,STOMP会话将获取经过身份验证的用户,Spring Security提供了进一步授权单个STOMP消息的方法。

这一切都应该无缝地发挥作用。无需通过STOMP登录或随时传递Spring Session ID。