如何使用基本路径在2个不同端口上处理具有 spring security 的执行器和服务器?

zlhcx6iw  于 2024-01-05  发布在  Spring
关注(0)|答案(1)|浏览(153)

我有一套

  1. # Server
  2. server.servlet.contextPath=/myapp/api
  3. server.port=8080
  4. # Actuator port
  5. management.health.probes.enabled=true
  6. management.server.port=8090
  7. management.endpoints.web.base-path=/myapp/api/actuator
  8. management.metrics.export.prometheus.enabled=true

字符串
像这样简单的授权

  1. @Bean
  2. fun filterChain(http: HttpSecurity): SecurityFilterChain {
  3. http.authorizeHttpRequests()
  4. .requestMatchers(HttpMethod.GET, "/actuator/health").permitAll() # Worked before when everything was on port 8080. Still works but with token
  5. .requestMatchers(HttpMethod.GET, "/myapp/api/actuator/health").permitAll() # Worked when actuator was on different port without token
  6. .requestMatchers(HttpMethod.GET, "/vehicles/**").permitAll()
  7. .anyRequest().authenticated()
  8. .and()
  9. .oauth2ResourceServer()
  10. .jwt()
  11. .jwtAuthenticationConverter(jwtAuthenticationConverter())
  12. return http.build()
  13. }


之前我用端口8080运行一切.现在我需要运行日志辅助端口.两者都必须有基本路径开始/myapp/API/.什么是最佳实践的方式做到这一点?

qv7cva1a

qv7cva1a1#

您可以为每个端口使用两个单独的SecurityConfigurerAdapter示例:

  1. @Configuration
  2. @EnableWebSecurity
  3. class SecurityConfig {
  4. @Bean
  5. fun actuatorSecurityConfigurerAdapter(): SecurityConfigurerAdapter {
  6. return object : SecurityConfigurerAdapter() {
  7. override fun configure(http: HttpSecurity) {
  8. http.antMatcher("/myapp/api/actuator/**")
  9. .authorizeRequests {
  10. it.antMatchers(HttpMethod.GET, "/myapp/api/actuator/health").permitAll()
  11. // Other actuator endpoints can be configured here
  12. }
  13. .anyRequest().authenticated()
  14. .and()
  15. .oauth2ResourceServer()
  16. .jwt()
  17. .jwtAuthenticationConverter(jwtAuthenticationConverter())
  18. }
  19. }
  20. }
  21. @Bean
  22. fun appSecurityConfigurerAdapter(): SecurityConfigurerAdapter {
  23. return object : SecurityConfigurerAdapter() {
  24. override fun configure(http: HttpSecurity) {
  25. http.antMatcher("/myapp/api/**")
  26. .authorizeRequests {
  27. it.antMatchers(HttpMethod.GET, "/myapp/api/vehicles/**").permitAll()
  28. // Other application endpoints can be configured here
  29. }
  30. .anyRequest().authenticated()
  31. .and()
  32. .oauth2ResourceServer()
  33. .jwt()
  34. .jwtAuthenticationConverter(jwtAuthenticationConverter())
  35. }
  36. }
  37. }
  38. @Bean
  39. fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
  40. http.csrf().disable() // Disable CSRF for simplicity
  41. http.apply(actuatorSecurityConfigurerAdapter())
  42. http.apply(appSecurityConfigurerAdapter())
  43. return http.build()
  44. }

字符串
actuatorSecurityConfigurerAdapter为执行器端点配置安全性,appSecurityConfigurerAdapter为应用程序端点配置安全性。securityFilterChain bean将这两种配置应用于整体安全设置。
通过这种方式,您可以为执行器和应用程序端点提供不同的安全配置,并且它们将基于指定的基本路径应用。

展开查看全部

相关问题