2

我试图弄清楚为什么 Spring Session 没有设置会话标头并且仍在设置JSESSIONID. 另外,我试图确定为什么我的测试没有得到JSESSIONID浏览器所做的。我不是想使用redis,只是内存存储。

@RestController
@SpringBootApplication
public class Application {

    @RequestMapping( "/" )
    public String greeting() {
        return "hello";
    }



    @Configuration
    @Order( SecurityProperties.ACCESS_OVERRIDE_ORDER )
    protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Bean
        static SessionRepository<? extends ExpiringSession> repository() {
            return new MapSessionRepository( );
        }

        @Bean
        static HttpSessionStrategy httpSessionStrategy() {
            return new HeaderHttpSessionStrategy();
        }

        @Autowired
        void globalUserDetails( final AuthenticationManagerBuilder auth ) throws Exception {
            auth.inMemoryAuthentication().withUser( "admin" ).password( "admin" ).roles( "USER", "ADMIN" );
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.httpBasic()
                    .and()
                    .authorizeRequests()
                    .anyRequest().authenticated();
        }
    }

    public static void main( final String[] args ) {
        SpringApplication app = new SpringApplication( Application.class );
        app.setShowBanner( false );
        app.run( args );
    }
}

和一个测试班

@RunWith( SpringJUnit4ClassRunner.class )
@WebAppConfiguration
@SpringApplicationConfiguration( classes = { MockServletContext.class, Application.class } )
public class ApplicationTest {

    private MockMvc mockMvc = null;
    private MockHttpServletRequestBuilder requestBuilder;
    @Autowired private WebApplicationContext context;
    @Autowired private FilterChainProxy springSecurityFilterChain;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup( context )
                .addFilter( springSecurityFilterChain )
                .build();

        requestBuilder = get( "/" )
                .header( "Authorization", "Basic " + Base64.getEncoder().encodeToString( "admin:admin".getBytes() ) );
    }

    @Test
    public void getSessionToken() throws Exception {
        this.mockMvc.perform( requestBuilder )
                .andExpect( status().is2xxSuccessful() )
                .andExpect( header().string( "X-Auth-Token", notNullValue() ) );
    }

    @Test
    public void getJessionId() throws Exception {
     // response does not agree with an actual browser request which has a JSESSIONID
        this.mockMvc.perform( requestBuilder )
                .andExpect( status().is2xxSuccessful() )
                .andExpect( cookie().doesNotExist( "JSESSIONID" ) );
    }
}

这些是我登录时 chrome 的响应标题 /

HTTP/1.1 200 OK
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
X-Frame-Options: DENY
Set-Cookie: JSESSIONID=6D7E2CB0AAFDD3B5DB53BA77C0725750; Path=/; HttpOnly
Content-Type: text/html;charset=UTF-8
Content-Length: 5
Date: Fri, 29 May 2015 01:16:33 GMT

最后这是我的pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.xenoterracide</groupId>
    <artifactId>spring-session-test-case</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <!-- use UTF-8 for everything -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <parent>
        <groupId>io.spring.platform</groupId>
        <artifactId>platform-bom</artifactId>
        <version>1.1.2.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

为什么我没有得到X-Auth-Token标题而不是JESSIONIDCookie?为什么我的测试没有说我得到了JSESSIONIDcookie?

4

2 回答 2

1

您需要添加配置类做三件事:

  1. 启用SessionRepositoryFilter(这是通过@EnableSpringHttpSession注释完成的)
  2. 提供 bean 实现HttpSessionIdResolver接口 - 在您的情况下为 HeaderHttpSessionIdResolver
  3. 因为@EnableSpringHttpSession需要提供SessionRepository- 它也需要提供一个实现此接口的 bean(MapSessionRepository在下面的示例中使用)

示例配置:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.MapSessionRepository;
import org.springframework.session.config.annotation.web.http.EnableSpringHttpSession;
import org.springframework.session.web.http.HeaderHttpSessionIdResolver;
import org.springframework.session.web.http.HttpSessionIdResolver;

import java.util.concurrent.ConcurrentHashMap;

@Configuration
@EnableSpringHttpSession
public class HttpSessionConfig {

    @Bean
    MapSessionRepository sessionRepository() {
        return new MapSessionRepository(new ConcurrentHashMap<>());
    }

    @Bean
    public HttpSessionIdResolver httpSessionIdResolver() {
        return HeaderHttpSessionIdResolver.xAuthToken();
    }
}
于 2020-05-24T16:48:54.533 回答
0

您只需要定义正确的 HttpSessionIdResolver 实现即可。默认情况下,spring-session 使用 CookieHttpSessionIdResolver。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.web.http.HeaderHttpSessionIdResolver;
import org.springframework.session.web.http.HttpSessionIdResolver;

@Configuration
public class SessionConfig {

    @Bean
    public HttpSessionIdResolver httpSessionIdResolver() {
        return HeaderHttpSessionIdResolver.xAuthToken();
    }
}

至少它适用于 Spring Boot 2.2.5.RELEASE。

于 2020-04-03T10:06:39.227 回答