问题描述
我正在使用spring boot开发Restful API服务器。我将项目配置为使用基本身份验证,如下所示。
I'm developing Restful API server by using spring boot. I configured my project to use basic authentication as below.
@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已创建。
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.
我的项目中没有其他安全配置。我想知道为什么会发生这种情况...
There are no other security configuration in my project. I wonder why this happen...
推荐答案
您是否尝试过使用 SessionCreationPolicy.STATELESS
。 :
Have you tried using SessionCreationPolicy.STATELESS
. There is a subtle difference between STATELESS
and NEVER
in the spring docs:
STATELESS
:Spring Security永远不会创建 HttpSession
,它永远不会用它来获取 SecurityContext
。
STATELESS
: Spring Security will never create an HttpSession
and it will never use it to obtain the SecurityContext
.
从不
:Spring Security永远不会创建一个 HttpSession
,但如果HttpSession已经存在则会使用。
NEVER
: Spring Security will never create an HttpSession
, but will use the HttpSession if it already exists.
所以我建议您清除所有Cookie,将其切换为 STATELESS
,然后重试。当您切换到 NEVER
时,可能已经有 HttpSession
。
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
.
这篇关于如何使spring boot永远不会发出会话cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!