首页 > 解决方案 > 如何避免在 Spring Security 中为非 TokenRelay 页面应用 Token

问题描述

我在我的 Reactive 应用程序中使用 Spring Cloud Starter Security 和 Spring Boot Starter Ouath2 Client,并在 application.yml 中进行了配置,如下所示。

它将 Token 完美地应用于具有 TokenRelay 的页面,但问题是我必须配置它不应该将 Token 应用于没有 TokenRelay 的页面。我怎样才能成功呢?你能帮我找出那个问题吗?你可以在下面找到我的代码。

pom.xml

 <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>

应用程序.yml

 routes:
    - id: securedApp
      uri: http://localhost:51687
      predicates:
        - Path=/keycloak-oidc-code/**
      filters:
        - TokenRelay=
        - RemoveRequestHeader=Cookie
  filter:
    # Removes Expect Header that send to the services
    remove-hop-by-hop:
      headers:
        - expect
security:
  basic:
    enable: false
  ignored: /**
oauth2:
  client:
    registration:
      sample-authorization-code:
        id: MyApplication
        client-id: MyApplication
        client-secret:f607d7c5-991d-4605-843f-330f419ed143
        client-name: SecondApplication
        provider: keycloak
        redirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}'
        authorization-grant-type: authorization_code
        client-authentication-method: post
        scope: openid, address, fun
    provider:
        keycloak:
        issuer-uri: http://localhost:8080/auth/realms/MyApplication
server:
  port: 8001

安全配置.java

@EnableWebFluxSecurity
@Configuration
public class SecurityConfig
{

 @Bean
 SecurityWebFilterChain springSecurityFilterChain( ServerHttpSecurity http ) throws Exception
{


    return http.authorizeExchange().matchers( EndpointRequest.to( InfoEndpoint.class, HealthEndpoint.class)).permitAll().anyExchange().authenticated().and().oauth2Login().and().build();


}

}

标签: spring-securitytokenspring-security-oauth2

解决方案


您的方法缺少一点。您需要将非安全应用程序的新路由添加到 application.yml,并且您必须在 SecurityConfig.java 中提到的安全配置中允许该路由。

应用程序.yml

routes:
- id: testMyApplication
  uri: localhost:61307
  predicates:
  - Path=/myApplication/**

安全配置.java

return http.authorizeExchange().pathMatchers( "/myApplication/**"").
permitAll().anyExchange().authenticated().and().oauth2Login().and().build();

推荐阅读