引起原因:java.lang.IllegalArgumentException:模式不能为 null 或为空

2024-01-26

我正在使用 Spring Boot v2.5.2 开发 Spring Boot 微服务项目。

Erorr

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Pattern cannot be null or empty
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:486) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1334) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.8.jar:5.3.8]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.8.jar:5.3.8]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.5.2.jar:2.5.2]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-2.5.2.jar:2.5.2]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434) ~[spring-boot-2.5.2.jar:2.5.2]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:338) ~[spring-boot-2.5.2.jar:2.5.2]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-2.5.2.jar:2.5.2]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) ~[spring-boot-2.5.2.jar:2.5.2]
    at com.example.PhotoAppApiUsersApplication.main(PhotoAppApiUsersApplication.java:17) ~[classes/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalArgumentException: Pattern cannot be null or empty
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.3.8.jar:5.3.8]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.8.jar:5.3.8]
    ... 21 common frames omitted
Caused by: java.lang.IllegalArgumentException: Pattern cannot be null or empty
    at org.springframework.util.Assert.hasText(Assert.java:289) ~[spring-core-5.3.8.jar:5.3.8]
    at org.springframework.security.web.util.matcher.AntPathRequestMatcher.<init>(AntPathRequestMatcher.java:113) ~[spring-security-web-5.5.1.jar:5.5.1]
    at org.springframework.security.web.util.matcher.AntPathRequestMatcher.<init>(AntPathRequestMatcher.java:98) ~[spring-security-web-5.5.1.jar:5.5.1]
    at org.springframework.security.web.util.matcher.AntPathRequestMatcher.<init>(AntPathRequestMatcher.java:86) ~[spring-security-web-5.5.1.jar:5.5.1]
    at org.springframework.security.web.util.matcher.AntPathRequestMatcher.<init>(AntPathRequestMatcher.java:75) ~[spring-security-web-5.5.1.jar:5.5.1]
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.setFilterProcessesUrl(AbstractAuthenticationProcessingFilter.java:358) ~[spring-security-web-5.5.1.jar:5.5.1]
    at com.example.security.WebSecurity.getAuthenticationFilter(WebSecurity.java:43) ~[classes/:na]
    at com.example.security.WebSecurity.configure(WebSecurity.java:34) ~[classes/:na]
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:217) ~[spring-security-config-5.5.1.jar:5.5.1]
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:315) ~[spring-security-config-5.5.1.jar:5.5.1]
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:93) ~[spring-security-config-5.5.1.jar:5.5.1]
    at com.example.security.WebSecurity$$EnhancerBySpringCGLIB$$340b667b.init(<generated>) ~[classes/:na]
    at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:338) ~[spring-security-config-5.5.1.jar:5.5.1]
    at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:300) ~[spring-security-config-5.5.1.jar:5.5.1]
    at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:38) ~[spring-security-config-5.5.1.jar:5.5.1]
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:127) ~[spring-security-config-5.5.1.jar:5.5.1]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.3.8.jar:5.3.8]
    ... 22 common frames omitted

pom.xml

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.2</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>PhotoAppApiConfigServer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>PhotoAppApiConfigServer</name>
    <description>Photo App Eureka Discovery Service</description>
    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>2020.0.3</spring-cloud.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>

        <!-- <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bus-amqp</artifactId>
        </dependency> -->
        <!-- <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency> -->

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </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>

应用程序属性

server.port=0
spring.application.name=users-ws

eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
eureka.client.serviceUrl.defaultZone=http://localhost:8010/eureka

eureka.instance.hostname=localhost
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=${spring.application.name}:${spring.application.instance_id:${random.value}}

spring.config.import=optional:configserver:http://locahost:8012

# MYSQL

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.sql.init.platform=mysql
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.show_sql=true

WebAecurity.java

@Configuration
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
    @Autowired
    private Environment env;
    
    @Autowired
    private UsersService userService;
    
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
//      http.authorizeRequests().antMatchers("/users/**").permitAll();
        
        // If Allow only IP address of API gateway  ==> Works well
        http.authorizeRequests().antMatchers("/**").hasIpAddress(env.getProperty("gateway.ip"))
        .and()
        .addFilter(getAuthenticationFilter())
        ;
    }

    private AuthenticationFilter getAuthenticationFilter() throws Exception {
        AuthenticationFilter authenticationFilter = new AuthenticationFilter(userService, env, authenticationManager());
        // This works with login path i.e http://localhost:8082/users-ws/login
//      authenticationFilter.setAuthenticationManager(authenticationManager());
        
        authenticationFilter.setFilterProcessesUrl(env.getProperty("login.url.apth"));
        return authenticationFilter;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder);
    }
}

验证过滤器.java

public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    
    private UsersService userService;
    private Environment env;
    
    public AuthenticationFilter(UsersService usersService, Environment environment, AuthenticationManager authenticationManager) {
        this.userService = usersService;
        this.env = environment;
        super.setAuthenticationManager(authenticationManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {

        try {
            LoginRequestModel creds = new ObjectMapper().readValue(request.getInputStream(), LoginRequestModel.class);

            return getAuthenticationManager().authenticate(
                    new UsernamePasswordAuthenticationToken(
                            creds.getEmail(), 
                            creds.getPassword(), 
                            new ArrayList<>()));
        } catch (IOException e) {
            return (Authentication) new RuntimeException(e);
        }
    }
    
    @Override
    protected void successfulAuthentication(HttpServletRequest request, 
                                            HttpServletResponse response, 
                                            FilterChain chain,
                                            Authentication authResult) throws IOException, ServletException {
        
        // Get Username (here emailId) from principal object
        String username = ((User) authResult.getPrincipal()).getUsername();
        
        // Based on Username (i.e emailId) find User from DB
        UserDto userDto = userService.getUserDetailsByEmail(username);
        
        // Create JWT
        String token = Jwts.builder()
            .setSubject(userDto.getUserId())
            .setExpiration(new Date(System.currentTimeMillis()+Long.parseLong(env.getProperty("token.expiration_time"))))
            .signWith(SignatureAlgorithm.HS512, env.getProperty("toke.secret"))
            .compact();
        
        // Add it into Response Header to be able to pass in the subsequent requets
        response.addHeader("token", token);
        response.addHeader("userId", userDto.getUserId());
        
        System.out.println("TOKEN="+token);
        System.out.println("USERID="+userDto.getUserId());
    }
}

在您的安全配置中,您使用的属性占位符在您的安全配置中没有匹配的值应用程序属性 file:

@Configuration
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
    // ...

    private AuthenticationFilter getAuthenticationFilter() throws Exception {
        // ...
        authenticationFilter.setFilterProcessesUrl(env.getProperty("login.url.apth")); // there is no value attributed to the 'login.url.apth' property key
        return authenticationFilter;
    }

    // ...
}

If the login.url.apth仍在其他地方定义(环境变量、系统属性或其他属性源),然后确保您使用适当的密钥,因为似乎已经存在拼写错误login.url.pa[ap]th.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

引起原因:java.lang.IllegalArgumentException:模式不能为 null 或为空 的相关文章

随机推荐

  • 省略 C++ 模板中的参数

    调用模板函数时可以省略函数名后面的类型吗 作为示例 请考虑以下函数 template
  • System.Move 和字符串数组

    我正在尝试将一些数组元素 字符串 移动到其他位置 当我使用System Move FastMM4 报告泄漏 这是一个显示问题的小片段 procedure TForm1 Button2Click Sender TObject type TAr
  • control.Show 和 BringToFront 之间有什么区别?

    显示 隐藏和 BringToFront SendToBack 有什么区别 在什么情况下我们应该使用一对而不是另一对 Show 相当于设置Visible true 它不会改变控件的 Z 顺序 如果控件被 Z 顺序前面的某个其他控件关闭 用户仍
  • Android BatteryManager 对所有属性检索调用返回 0

    我在尝试访问 Android 设备电池的大部分统计数据时遇到问题 例如BATTERY PROPERTY CAPACITY BATTERY PROPERTY CHARGE COUNTER or BATTERY PROPERTY CURRENT
  • 通过 user_id 获取 Google App Engine 用户

    In GAE http code google com appengine 你能查一下User http code google com appengine docs python users userclass html与 User 对象
  • 多台物理机上的 Vagrant VM

    我看到 Vagrant 有一个 AWS 插件 支持使用 Vagrant 来配置和运行多个 ec2 实例 AWS 之外是否存在此功能 使用示例 目前我在一台机器上有 5 个虚拟机 通过 VagrantFile 可以直接设置和管理 我现在可以访
  • 如何检查 Smarty 变量是否已分配?

    如何检查特定值是否已分配给 Smarty 以及是否未分配 默认 值 Answer if this gt cismarty gt get template vars test null this gt cismarty gt assign t
  • Quarkus 日志追踪,相当于 Spring Cloud Sleuth

    日志跟踪是非常重要的事情 所以我稍微研究了一下这段代码 将请求 ID 与响应 ID 进行匹配 连接 这适用于跟踪来自 来自我的 ws rs 资源的请求响应 Provider public class LoggingFilter implem
  • 为什么内部 Lua 字符串以它们的方式存储?

    我想要一个简单的字符串表来存储一堆常量 我想 嘿 Lua 可以做到这一点 让我使用其中的一些函数 这主要在lstring h lstring c文件中 我使用的是5 2 我先展示我好奇的代码 它来自 lobject h Header for
  • 如何将图像从本机反应发送到本机模块?

    Problem 我正在尝试将一组图像 保存在本地资源文件夹的 javascript 端 发送到本机端 iOS 和 Android 本机端处理图像并返回新图像 这是有效的 因为我尝试发送图像 URL 使用基于互联网的图像而不是本地图像 并且本
  • 除了snow SOCK之外的集群并行计算

    最近 R2 14 中添加的对并行计算的直接支持在我脑海中引发了一个问题 在 R 中创建集群有很多选项 我使用snow定期进行SOCK集群 但我知道还有其他方式 例如MPI 我用的是SOCKsnow集群 因为我不需要安装任何额外的软件 我使用
  • Facebook FQL 流限制?

    我想了解我的墙的完整历史 但我似乎在六月的某个时候就达到了极限 我进行了多次这样的调用 SELECT created time message FROM stream WHERE source id MY USER ID LIMIT 50
  • AWK 使用标题拆分大型 CSV 文件并根据列值打印输出文件

    我有一个大约 800 mb 的 CSV 文件 需要使用 AWK 对其进行拆分 该文件有一列 其中包含 ID 我想用它来分割文件 我熟悉 知道如何使用 Perl 完成此任务 但不熟悉 AWK 因为我只使用过几次 在 perl 中 我将使用 T
  • IIS 仅要求特定文件夹的登录凭据

    我在 IIS 7 上有一个网站 其中有几个子文件夹 该站点是使用 net 2 构建的 并以集成模式在池中运行 除了名为 Reports 的文件夹下的所有 aspx 文件外 整个网站运行良好 当用户尝试访问该文件夹下的任何 aspx 页面时
  • 启动期间自动挂载单独分区时 systemd/udev 依赖失败

    编辑 当我尝试使用带有任何安装点的单独分区时 而不仅仅是使用单独的分区时 就会发生这种情况 var 我正在使用 Buildroot 构建嵌入式 Linux 系统 我尝试为 var 使用单独的分区 但任何安装点都会发生这种情况 我的init系
  • 当我 Assembly.Load 肯定存在的程序集时,为什么会出现 FileNotFoundException?

    在我的 Windows Azure 角色 C 代码中 我执行以下操作 Assembly Load Microsoft WindowsAzure ServiceRuntime and FileNotFoundException被抛出 问题是存
  • Matplotlib 样式表未应用

    我一直在尝试几种样式表 但似乎没有一个适用于画布 这是我第一次使用twinx 所以也许这就是问题所在 我尝试过的代码如下 import pickle import numpy as np import matplotlib pyplot a
  • 如何让主线程等待ThreadPoolExecutor中其他线程完成

    我正在使用 ThreadPoolExecutor 在我的 Java 应用程序中实现线程 我有一个 XML 我需要解析它并将其每个节点添加到线程中以执行完成 我的实现是这样的 parse ip 是创建的线程池对象 ParseQuotes XM
  • 黑屏 - Angular JIT 编译失败:“@angular/compiler”未加载

    我目前无法让我的 Ionic 5 和 Angular 9 项目正常工作 ionic cordova run android效果很好 但我一跑ionic cordova run android prod我得到的唯一结果是一个空白屏幕 Chro
  • 引起原因:java.lang.IllegalArgumentException:模式不能为 null 或为空

    我正在使用 Spring Boot v2 5 2 开发 Spring Boot 微服务项目 Erorr org springframework beans factory BeanCreationException Error creati