微服务:6.限制通过IP直接访问服务器

该博客介绍了如何在微服务架构中利用Zuul API网关和Eureka进行流量管理,并通过SpringSecurity配置仅允许特定IP(如192.168.2.81)访问微服务。通过在pom.xml中添加SpringBoot的SpringSecurity依赖,并自定义WebSecurity配置,可以实现对HTTP请求的IP授权,确保用户验证等操作的安全性。
摘要由CSDN通过智能技术生成

当使用Zuul API网关和Eureka时,如果要所有的HTTP请求都通过Zuul API网关进行请求然后转发到微服务,比如用户验证的时候,就需要这样的处理。

要阻止IP请求来自除了Zuul API网关之外的其他地址,在微服务应用中配置Spring Security。

增加 Spring Security

pom.xml中添加依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
授权访问IP

创建Java配置类,具体如下:

package com.xarhsoft.photoapp.api.users.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
          .antMatchers("/**").hasIpAddress("192.168.2.81");
    }
    
}

hasIpAddress的其他写法如:

http
    .authorizeRequests().access(
            "hasIpAddress('192.168.2.5/16') or hasIpAddress('127.0.0.1/32')")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丷丩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值