Spring security 6.2 JSESSIONID 未返回

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

我正在使用 Kotlin 创建一个 Spring Boot 应用程序。我已经配置了 WebSecurity,如下所示:


@Configuration
class SecurityConfig {

    @Autowired
    lateinit var dataSource: DataSource


    @Value("\${cors.originPatterns:default}")
    private val corsOriginPatterns: String = ""

    @Bean
    fun addCorsConfig(): WebMvcConfigurer {
        return object : WebMvcConfigurer {
            override fun addCorsMappings(registry: CorsRegistry) {
                registry.addMapping("/**")
                    .allowedMethods("*")
                    .allowedOriginPatterns("http://localhost:*")
                    .allowCredentials(true)
            }
        }
    }

    @Bean
    fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
        http {
            authorizeHttpRequests {
                authorize("/auth/*", permitAll)
                authorize(anyRequest, authenticated)

            }

        }


        return http.csrf { it.disable() } .build()
    }


    @Bean
    fun authenticationManager(
        userDetailsService: UserDetailsService,
        passwordEncoder: PasswordEncoder): AuthenticationManager {
        val authenticationProvider = DaoAuthenticationProvider()
        authenticationProvider.setUserDetailsService(userDetailsService)
        authenticationProvider.setPasswordEncoder(passwordEncoder)
        return ProviderManager(authenticationProvider)
    }



    @Bean
    fun passwordEncoder(): PasswordEncoder {
        return BCryptPasswordEncoder()
    }

    fun dataSource(): DataSource {
        return this.dataSource
    }
    @Bean
    fun users(dataSource: DataSource): UserDetailsManager {
        val users = JdbcUserDetailsManager(dataSource)
        return users
    }

}

我的

/login
端点如下所示:

@RestController
class LoginController(private val authenticationManager: AuthenticationManager) {

    data class LoginRequest(val username: String, val password: String)
    @PostMapping("/auth/login")
    fun login(@RequestBody loginRequest: LoginRequest): ResponseEntity<Void> {
        val authenticationRequest =
            UsernamePasswordAuthenticationToken.unauthenticated(
                loginRequest.username, loginRequest.password)
        val authenticationResponse = authenticationManager.authenticate(authenticationRequest)
        println(authenticationResponse)
        if (authenticationResponse != null && authenticationResponse.isAuthenticated) {
            return ResponseEntity.ok().build()
        } else {
            return ResponseEntity.status(401).build()
        }
    }
}

根据Spring Security关于持久性的文档会话管理

一旦您拥有对请求进行身份验证的应用程序,重要的是要考虑如何在未来的请求中保留和恢复生成的身份验证。

这是默认自动完成的,因此不需要额外的代码,[...]

持久化文档也提到默认情况下;

在 Spring Security 中,用户与未来请求的关联是使用

SecurityContextRepository
进行的。
SecurityContextRepository
的默认实现是
DelegatingSecurityContextRepository
,它委托给以下内容:

  • HttpSessionSecurityContextRepository
  • RequestAttributeSecurityContextRepository

所以我真的不知道我错过了什么,身份验证运行良好,检索数据库中的现有用户并进行身份验证。但是,我在响应中没有收到任何 JSESSIONID cookie。

当我显式配置会话管理时:

sessionManagement {
                sessionCreationPolicy = SessionCreationPolicy.ALWAYS
            }

我得到了 cookie,但即使我使用以下请求发送它,服务器也会返回 403 状态代码。

以下是我在设置

/auth/login
策略时调用
SessionCreationPolicy.ALWAYS
端点时的调试日志:

2024-01-08T18:53:30.092+01:00  INFO 49558 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2024-01-08T18:53:30.092+01:00  INFO 49558 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2024-01-08T18:53:30.094+01:00  INFO 49558 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
2024-01-08T18:53:30.115+01:00 DEBUG 49558 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Securing POST /auth/login
2024-01-08T18:53:30.126+01:00 DEBUG 49558 --- [nio-8080-exec-2] .s.s.w.s.ForceEagerSessionCreationFilter : Created session eagerly
2024-01-08T18:53:30.134+01:00 DEBUG 49558 --- [nio-8080-exec-2] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-01-08T18:53:30.139+01:00 DEBUG 49558 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Secured POST /auth/login
UsernamePasswordAuthenticationToken [Principal=org.springframework.security.core.userdetails.User [Username=signup test 2, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, CredentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_USER]], Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[ROLE_USER]]
2024-01-08T18:53:39.468+01:00 DEBUG 49558 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : Securing POST /readMessages
2024-01-08T18:53:39.470+01:00 DEBUG 49558 --- [nio-8080-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-01-08T18:53:39.472+01:00 DEBUG 49558 --- [nio-8080-exec-3] o.s.s.w.a.Http403ForbiddenEntryPoint     : Pre-authenticated entry point called. Rejecting access
2024-01-08T18:53:39.476+01:00 DEBUG 49558 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy        : Securing POST /error
2024-01-08T18:53:39.477+01:00 DEBUG 49558 --- [nio-8080-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2024-01-08T18:53:39.478+01:00 DEBUG 49558 --- [nio-8080-exec-3] o.s.s.w.a.Http403ForbiddenEntryPoint     : Pre-authenticated entry point called. Rejecting access


如有任何帮助,我们将不胜感激,提前致谢。

spring-boot kotlin spring-security
1个回答
0
投票

您的控制器不使用

SecurityContextRepository
。为了保持您的身份验证,您应该保存
authenticationResponse

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