这似乎已经破坏了2.6.X
旧版本(我试过2.5.X
)没有表现出下面描述的行为。
步骤 1: 提供WebSecurityConfigurerAdapter
并为其配置STATELESS
会话创建策略:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().authorizeRequests()
.antMatchers("/test-user").hasRole("USER")
.antMatchers("/test-admin").hasRole("ADMIN")
.antMatchers("/error").authenticated()
.and().httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER").and()
.withUser("admin").password("{noop}password").roles("ADMIN", "USER");
}
}
第 2 步:设置一个简单的控制器
@Controller
public class ExampleController {
@GetMapping(path = {"test-user", "test-admin"})
public void test(HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_OK);
}
}
步骤 3:运行应用程序并向用户无权查看的资源发送请求
curl -v -u user:password http://localhost:8080/test-admin
预期行为:用户收到HTTP 403 Forbidden
响应状态代码和响应主体(如下所示):
{
"timestamp":"2022-02-04T23:42:41.621+00:00",
"status":403,
"error":"Forbidden",
"path":"/test-admin"
}
实际行为:用户收到HTTP 403 Forbidden
没有响应主体的响应状态代码
注意:如果STATELESS
从上述配置中删除会话创建策略,它将按预期工作。