当使用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')")