Spring Boot 安全性允许来自给定 IP 地址的请求

Posted

技术标签:

【中文标题】Spring Boot 安全性允许来自给定 IP 地址的请求【英文标题】:Spring Boot security allow requests from given IP address 【发布时间】:2020-05-09 13:33:48 【问题描述】:

我们有以下安全配置代码,

@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception 
        httpSecurity.cors().and().csrf().disable().authorizeRequests().antMatchers("/api/**").anyRequest()
                .authenticated().and().exceptionHandling().accessDeniedPage("/").and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    

     GET /api/users
        POST /api/users
        GET /api/users/userId

我们需要在 Spring Boot 应用程序中限制以下请求(并非针对所有请求),并仅在属性中的给定 ipaddress (multiple ipaddress) 上允许这些请求。

【问题讨论】:

【参考方案1】:

尝试以下配置:

@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception 
        httpSecurity.cors().and().csrf().disable().authorizeRequests()
                .antMatchers("/api/users/**").hasIpAddress("127.0.0.1")
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated().and().exceptionHandling().accessDeniedPage("/").and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    

【讨论】:

感谢您的发帖,这里需要配置多个ip地址 我只是尝试如下,似乎这工作。 @Override protected void configure(HttpSecurity httpSecurity) 抛出异常 httpSecurity.cors().and().csrf().disable().authorizeRequests() .antMatchers("/api/users/**").access(" hasIpAddress('10.00.07.9') 或 hasIpAddress('10.00.00.60')") .and() .authorizeRequests() .anyRequest() .authenticated().and().exceptionHandling().accessDeniedPage("/") .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

以上是关于Spring Boot 安全性允许来自给定 IP 地址的请求的主要内容,如果未能解决你的问题,请参考以下文章