【问题标题】:How to make spring boot never issue session cookie?如何使spring boot永远不会发出会话cookie?
【发布时间】:2014-12-10 19:02:03
【问题描述】:

我正在使用 Spring Boot 开发 Restful API 服务器。我将我的项目配置为使用基本身份验证,如下所示。

@ComponentScan
@EnableAutoConfiguration
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    ...
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and()
            .csrf().disable()
            .authorizeRequests().anyRequest().hasRole("USER").and()
            .httpBasic();
    }
    ...
}

但是当我通过 Chrome-Postman-Plugin 测试 API 时,在第一次调用后,服务器从不需要用户凭据。我注意到创建了“JSESSIONID”cookie。

我的项目中没有其他安全配置。我想知道为什么会这样……

【问题讨论】:

  • 您的配置类是否扩展了 WebSecurityConfigurerAdapter?
  • 是的。我编辑了我的代码 sn-p。我想确保我的 api 服务器不管理任何会话..
  • 好的,首先,让我们验证是否强制执行了身份验证。你可以尝试用这个替换你的配置:http.csrf() .disable() .authorizeRequests() .anyRequest().authenticated()

标签: java spring spring-security


【解决方案1】:

我使用了以下选项

.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.formLogin().disable()
.httpBasic().disable()
.logout().disable()

得到错误 localhost 重定向您的次数过多

我在清除 cookie 后尝试过。 但是在我删除以下选项/行的那一刻 .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()... 它运作良好。这是针对 oauth2login() 的。可能是 oauth2login() 需要此会话状态。有什么解释?

当我没有这个时 .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()... 然后,它使用 cookie。我使用 google auth,因此,一旦我登录,它就允许后续调用而无需进行身份验证。 所有这些行为听起来都很合理且符合预期。

出于安全原因,一位专家告诉我关闭 cookie。除了关闭会话,我不知道这意味着什么......

【讨论】:

    【解决方案2】:

    它对我有用 “所以我建议你清除所有 cookie,将其切换到 STATELESS 并重试。可能是当你切换到 NEVER 时,你已经有一个 HttpSession。”

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .csrf().disable()
                .authorizeRequests()
                .anyRequest()
                .authenticated().and().httpBasic();
    
    }
    

    【讨论】:

      【解决方案3】:

      您是否尝试过使用SessionCreationPolicy.STATELESSspring docs中的STATELESSNEVER有细微的差别:

      STATELESS:Spring Security 永远不会创建HttpSession,也永远不会使用它来获取SecurityContext

      NEVER:Spring Security 永远不会创建HttpSession但如果 HttpSession 已经存在,则会使用它

      因此,我建议您清除所有 cookie,将其切换为 STATELESS,然后重试。当您切换到NEVER 时,可能已经有一个HttpSession

      【讨论】:

      • 感谢对歧义的警告。
      • 如果我想使用会话,但又不想让 spring security 创建一个呢?
      • 我使用了 STATELESS,但收到错误 localhost 将您重定向了太多次。我也在清除 cookie 后尝试过。这些我都用过。但除了 sessionManagement 之外,其他一切都很好。 csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .formLogin().disable() .httpBasic().disable() .logout().disable()
      猜你喜欢
      • 2020-06-02
      • 1970-01-01
      • 2016-08-10
      • 2012-04-01
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 2021-05-27
      相关资源
      最近更新 更多