我正在将 Spring Cloud Gateway 应用程序设置为
OAuth2
客户端。在安全配置类中,我设置了一些白名单路径。如果任何未经授权的用户想要访问任何安全路径,他/她应该自动“重定向”到谷歌登录同意页面。但是,就我而言,这种自动重定向并没有发生。相反,在访问任何安全路径时,我收到了401
错误。波纹管是我的示例代码-
@SpringBootApplication
public class SsoApplication {
public static void main(String[] args) {
SpringApplication.run(SsoApplication.class, args);
}
@RestController
public class WelcomeController {
@GetMapping
public String openPath() {
return "this is open path";
}
@GetMapping("/secured")
public String securedPath() {
return "Accessing secured path";
}
}
}
@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {
@Bean
public SecurityWebFilterChain securityFilterChain(ServerHttpSecurity http) {
return http
.authorizeExchange(exchange -> exchange
.pathMatchers("/", "/*.css", "/*.js", "/favicon.ico").permitAll()
.pathMatchers("/actuator/**").permitAll()
.anyExchange().authenticated()
)
.exceptionHandling(exceptionHandling -> exceptionHandling
.authenticationEntryPoint(new HttpStatusServerEntryPoint(HttpStatus.UNAUTHORIZED)))
.oauth2Login(Customizer.withDefaults())
.build();
}
}
应用程序.yml
spring:
security:
oauth2:
client:
registration:
google:
client-id: #client_id#
client-secret: #secret#
redirect-uri: "{baseUrl}/login/oauth2/code/google"
server:
port: 9999
构建.gradle
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.1'
id 'io.spring.dependency-management' version '1.1.4'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
java {
sourceCompatibility = '17'
}
repositories {
mavenCentral()
}
ext {
set('springCloudVersion', "2023.0.0")
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'io.projectreactor:reactor-test'
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
我尝试过以下事情 -
在
@Order(Ordered.HIGHEST_PRECEDENCE)
SecurityWebFilterChain
。
从
@Configuration
SecurityConfig
注释
受限(我想知道为什么)! 3. 删除
@EnableWebFluxSecurity
并保留访问安全路径时出现 HTTP ERROR 401,不会重定向到登录页面。 4.在application.yml添加@Configuration
访问安全路径时出现 HTTP ERROR 401,不会重定向到登录页面。 在场景 1、3 中,如果我手动点击redirection-uri: "{baseUrl}/login/oauth2/code/google"
/oauth2/authorization/google
,它会将我重定向到登录页面。
我尝试使用spring-boot-starter-web
应用程序实现同样的事情;
一切都按预期进行。 更新
authenticationEntryPoint
应用程序中添加
spring-boot-web
。这就是为什么这个应用程序的行为正如 @ch4mp 指出的那样]知道为什么会在 spring-cloud-gateway
应用程序上发生这种情况吗?我能做些什么来解决这个问题?
oauth2Login
的 OAuth2 客户端的默认值)。
尝试删除 .exceptionHandling(exceptionHandling -> exceptionHandling
.authenticationEntryPoint(new HttpStatusServerEntryPoint(HttpStatus.UNAUTHORIZED)))