Spring Boot - 如何有条件地启用/禁用会话

7
我使用Spring构建了一个REST API服务,并使用MongoDB启用了会话:
@Configuration
@EnableMongoHttpSession(maxInactiveIntervalInSeconds = Globals.SESSION_MAX_INTERVAL)
public class SessionConfig {

    @Bean
    public AbstractMongoSessionConverter createSessionConverterBean() {
        return new JacksonMongoSessionConverter(Collections.singletonList(new GeoModule()));
    }
}

我希望能够控制哪些连接应该生成会话。目前,每个HTTP请求都会生成一个会话,但是有些情况下并不需要会话,我不想在会话存储中混杂着永远不会使用的会话对象。

其中一种情况是独立的桌面应用程序,作为内容管理系统。这个应用程序不需要HTTP会话,因为身份验证是通过自定义授权头在应用程序端完成的。此应用程序也仅访问来自特定根路由映射的终端点:

公共流量路由到api.domain.com/pub,CMS流量通过api.domain.com/cpi路由。

如果能告诉Spring不需要为任何请求到达 /cpi 的会话就好了。如果更容易做到,桌面应用程序还提供了一个唯一的Origin

我的Web安全性看起来像这样:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .anyRequest()
            .permitAll()
            .and()
            .cors()
            .and()
            .httpBasic();
    http.csrf().disable(); // Self-implemented
}

我已经搜索了很多地方,但没有找到任何信息。有人能指点一下我吗?

谢谢!

2个回答

8
你可以按照以下方案添加多个安全配置。其中一个明确匹配所有/cpi请求,另一个处理其余请求。
你也可以通过这种方式配置不同的身份验证方法。
@Order(1)
@Configuration
public static class Custom1WebSecurityConfigurerAdapter extends 
WebSecurityConfigurerAdapter {
    http
                .antMatcher("/cpi/**")
                .authorizeRequests()
                ...

    http.sessionManagement() // dont create a session for this configuration
              .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}


@Order(2)
@Configuration
public static class Custom2WebSecurityConfigurerAdapter extends 
WebSecurityConfigurerAdapter {
    http
                .authorizeRequests()
                ...
}

添加第二个配置后,出现异常:UnsatisfiedDependencyException: Error creating bean with name 'baseSecurityConfig.CpiSecurityConfig': 通过方法 'setContentNegotationStrategy' 参数0表达的不满足依赖项; 嵌套异常是org.springframework.beans.factory.UnsatisfiedDependencyException: - mwieczorek
你能发一下你完整的SecurityConfiguration吗?我现在正在旅行,但明天可能能帮你。 - S. Dragomir

-1
你可以尝试在 application.yml 文件中输入以下内容。
server:
  servlet:
    session:
      persistent: false
      timeout: 0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接