首页 > 解决方案 > Spring Boot 安全性允许来自给定 IP 地址的请求

问题描述

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

@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)在属性中给定。

标签: spring-bootspring-security-rest

解决方案


尝试以下配置:

@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);
    }

推荐阅读