oauth2.0 创建名为'corsConfigurationSource'的Bean时出错

1bqhqjot  于 2022-11-21  发布在  其他
关注(0)|答案(1)|浏览(111)

尝试 解决 我 的 应用 程序 中 的 CORS 问题 。 在 Spring 文档 中 , 我 通过 设置 Csconfigurationsource 找到 了 问题 的 解决 方案 。 但 在 将 核心 配置 源 bean 添加 到 SecurityConfig 类 后 , 我 得到 以下 错误 :

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'corsConfigurationSource' defined in class path resource [com/amrut/prabhu/oauth2/client/SecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.cors.CorsConfigurationSource]: Factory method 'corsConfigurationSource' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/servlet/ServletRequest
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658) ~[spring-beans-5.3.22.jar:5.3.22]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:486) 
~[spring-beans-5.3.22.jar:5.3.22]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352) ~[spring-beans-5.3.22.jar:5.3.22]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195) ~[spring-beans-5.3.22.jar:5.3.22]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.22.jar:5.3.22]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.22.jar:5.3.22]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.22.jar:5.3.22]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.22.jar:5.3.22]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.22.jar:5.3.22]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.22.jar:5.3.22]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955) ~[spring-beans-5.3.22.jar:5.3.22]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.22.jar:5.3.22]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.22.jar:5.3.22]
        at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.refresh(ReactiveWebServerApplicationContext.java:66) ~[spring-boot-2.7.2.jar:2.7.2]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) ~[spring-boot-2.7.2.jar:2.7.2]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) ~[spring-boot-2.7.2.jar:2.7.2]      
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-2.7.2.jar:2.7.2]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.2.jar:2.7.2]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.2.jar:2.7.2]
        at com.amrut.prabhu.oauth2.client.SpringOauth2ClientApplication.main(SpringOauth2ClientApplication.java:11) ~[classes/:na]   
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.cors.CorsConfigurationSource]: Factory method 'corsConfigurationSource' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/servlet/ServletRequest
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.3.22.jar:5.3.22]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.22.jar:5.3.22]
        ... 19 common frames omitted
Caused by: java.lang.NoClassDefFoundError: javax/servlet/ServletRequest
        at com.amrut.prabhu.oauth2.client.SecurityConfig.corsConfigurationSource(SecurityConfig.java:28) ~[classes/:na]
        at com.amrut.prabhu.oauth2.client.SecurityConfig$$EnhancerBySpringCGLIB$$b06e6d35.CGLIB$corsConfigurationSource$1(<generated>) ~[classes/:na]
        at com.amrut.prabhu.oauth2.client.SecurityConfig$$EnhancerBySpringCGLIB$$b06e6d35$$FastClassBySpringCGLIB$$1638cfac.invoke(<generated>) ~[classes/:na]
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.3.22.jar:5.3.22]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) ~[spring-context-5.3.22.jar:5.3.22]
        at com.amrut.prabhu.oauth2.client.SecurityConfig$$EnhancerBySpringCGLIB$$b06e6d35.corsConfigurationSource(<generated>) ~[classes/:na]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:na]
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:na]
        at java.base/java.lang.reflect.Method.invoke(Unknown Source) ~[na:na]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.3.22.jar:5.3.22]
        ... 20 common frames omitted
Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletRequest
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source) ~[na:na]
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source) ~[na:na]
        at java.base/java.lang.ClassLoader.loadClass(Unknown Source) ~[na:na]
        ... 31 common frames omitted

中 的 每 一 个
SecurityConfig 配置 类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.oauth2.client.oidc.web.server.logout.OidcClientInitiatedServerLogoutSuccessHandler;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.authentication.logout.ServerLogoutSuccessHandler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

    @Bean 
    CorsConfigurationSource corsConfigurationSource() { 
        CorsConfiguration configuration = new CorsConfiguration(); 
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200")); 
        configuration.setAllowedMethods(Arrays.asList("GET","POST")); 
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 
        source.registerCorsConfiguration("/**", configuration); 
        return source; 
    } 

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http, ServerLogoutSuccessHandler handler) {
        http
            .cors()
            .and()
            .csrf().disable()           
                .authorizeExchange()
                .pathMatchers("/actuator/**", "/","/logout.html")
                .permitAll()
            .and()
                .authorizeExchange()
                .anyExchange()
                .authenticated()
            .and()
                .oauth2Login() // to redirect to oauth2 login page.
            .and()
                .logout()
                .logoutSuccessHandler(handler)
        ;

        return http.build();
    }

    @Bean
    public ServerLogoutSuccessHandler keycloakLogoutSuccessHandler(ReactiveClientRegistrationRepository repository) {

        OidcClientInitiatedServerLogoutSuccessHandler oidcLogoutSuccessHandler =
                new OidcClientInitiatedServerLogoutSuccessHandler(repository);

        oidcLogoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}/logout.html");

        return oidcLogoutSuccessHandler;
    }    
}

格式
我 的 依赖 项 Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.amrut.prabhu</groupId>
    <artifactId>spring-cloud-gateway-keycloak-oauth2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Spring Cloud Gateway Oauth2 With Keycloak</name>
    <description>spring cloud gateway with keycloak oauth2</description>
    <properties>
        <java.version>17</java.version>
        <spring-cloud.version>2021.0.1</spring-cloud.version>
        <lombok.version>1.18.22</lombok.version>
        <logback-access-spring-boot-starter.version>3.1.2</logback-access-spring-boot-starter.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>${lombok.version}</version>
      <optional>true</optional>
    </dependency>

    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

格式
有 什么 问题 吗 ?

1wnzp6jl

1wnzp6jl1#

在 React 式 应用 中 , 您 应该 构建 org.springframework.web.cors.reactive.CorsConfigurationSource ( 而 不是 用于 servlet 的 org.springframework.web.cors.CorsConfigurationSource ) 。
此外 , 在 构建 HTTP 安全 性 时 , 可能 需要 显 式 地 注入 bean :

http.cors().configurationSource(corsConfigurationSource());

中 的 每 一 个

# PS

你 可能 在 Baeldung 的 文章 中 找到 了 其他 方法 , 但 这 是 一 个 更 好 的 方法 :

  • 在 网关 中 不 配置 任何 有关 OAuth2 和 授权 的 内容
  • 授权 来自 实际 客户 端 ( 那些 向 网关 发送 请求 的 客户 端 ) 的 请求 , 使用 OAuth2 ( 或 更 好 的 OpenID/OIDC ) 客户 端 库 作为 您 在 客户 端 ( 如 angular-auth-oidc-client for Angular ) 中 使用 的 框架
  • 将 网关 后面 的 REST API 配置 为 资源 服务 器 ( 请 参阅 Spring 的 those tutorials , 如果 资源 服务 器 是 被动 的 , 请 参阅 "webflux" samples

# 完整 样品

我 刚刚 更新 了 this public repo 以 添加 网关 模块 。
Angular 应用 程序 位于 angular-workspace 文件 夹 中 。
api 是 一 个 具有 两 个 资源 服务 器 的 Maven 多 模块 项目 :user-proxies-apigreet-api 。 两者 都 使用 OAuth2 保护 。
网关 简单 如 :
第 一 次
如果 您 需要 设置 Keycloak 和 配置 资源 服务 器 安全 性 的 详细 说明 , 请 参阅 those tutorials

相关问题