java 如何让 Spring Boot 从不发出会话 cookie?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26387003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:50:50  来源:igfitidea点击:

How to make spring boot never issue session cookie?

javaspringspring-security

提问by jyshin

I'm developing Restful API server by using spring boot. I configured my project to use basic authentication as below.

我正在使用 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();
    }
    ...
}

But when I tested the API by Chrome-Postman-Plugin, after first call, server never require user credential. And I noticed that 'JSESSIONID' cookie was created.

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

There are no other security configurations in my project. I wonder why this happens...

我的项目中没有其他安全配置。我想知道为什么会发生这种情况...

回答by Luke Bajada

Have you tried using SessionCreationPolicy.STATELESS. There is a subtle difference between STATELESSand NEVERin the spring docs:

您是否尝试过使用SessionCreationPolicy.STATELESS. 之间存在细微的差别STATELESS,并NEVER春季文档

STATELESS: Spring Security will never create an HttpSessionand it will never use it to obtain the SecurityContext.

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

NEVER: Spring Security will never create an HttpSession, but will use the HttpSession if it already exists.

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

So I would suggest that you clear all your cookies, switch it to STATELESSand try again. It could be that you had already an HttpSessionwhen you switched to NEVER.

因此,我建议您清除所有 cookie,将其切换到STATELESS并重试。可能是您在HttpSession切换到NEVER.

回答by Pankaj Sharma

its work for me "So I would suggest that you clear all your cookies, switch it to STATELESS and try again. It could be that you had already an HttpSession when you switched to NEVER."

它对我有用“所以我建议您清除所有 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();

}