Spring Security对经过身份验证的会话管理的澄清

问题描述 投票:0回答:1

我用一个不同的、更具体的疑问来跟进我之前的问题,考虑以下场景:

  • 我当前正在使用 spring security 6 运行 Oauth2 资源服务器。客户端应用程序发送一个 JWT 令牌,其中包含一些由我的服务器正确验证的声明。
  • 此时,Spring Security 应该打开一个会话(或使用现有的会话)并将身份验证信息存储在会话 cookie 中
  • 来自该特定客户端应用程序的所有后续请求现在都应该经过身份验证,无需重复 JWT 验证,直到会话过期

但是,情况似乎并非如此,因为包含会话标头但不承载 JWT 的请求是未经授权的,这是我的过滤器链:

@Bean
public SecurityFilterChain oauth2Chain(HttpSecurity http) throws Exception {
    http
            // persist authentication
            // // session creation policy
            // .sessionManagement(httpSecuritySessionManagementConfigurer ->
            // httpSecuritySessionManagementConfigurer
            // .sessionCreationPolicy(SessionCreationPolicy.IF_NEEDED))
            // persist context
            .securityContext((securityContext) -> securityContext
                    .securityContextRepository(new HttpSessionSecurityContextRepository()))
            // default policy: jwt oauth2 on all requests
            .authorizeHttpRequests(authorize -> authorize
                    .anyRequest().authenticated())
            .oauth2ResourceServer((oauth2) -> oauth2.jwt(Customizer.withDefaults()));
    return http.build();
}

我也先尝试了默认的:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(authorize -> authorize
            .anyRequest().authenticated()
        )
        .oauth2ResourceServer((oauth2) -> oauth2.jwt(Customizer.withDefaults()));
    return http.build();
}

使客户端每个会话仅进行一次身份验证的正确方法是什么?我应该在某个时候显式创建会话吗?我只有:

@EnableSpringHttpSession
@Configuration
public class HtmlSessionConfig {
    @Bean
    public MapSessionRepository sessionRepository() {
        return new MapSessionRepository(new ConcurrentHashMap<>());
    }
}
java spring-boot spring-security jwt spring-security-oauth2
1个回答
0
投票

OAuth2 系统中的用户仅使用两个会话:

  • 在授权服务器上
  • 在客户端上(在授权代码流程期间需要会话来存储一些验证器,例如随机数或 PKCE(如果使用),并且在流程完成后存储令牌)

但是资源服务器一般是无状态的(没有会话)。状态随每个请求(令牌声明)一起发送。因此,将访问令牌与每个请求一起发送到资源服务器,并且该资源服务器针对每个请求验证它(解码并验证 JWT 或内省任何类型的令牌)是预期的行为。

© www.soinside.com 2019 - 2024. All rights reserved.