新建三个项目:
- demo-server 服务端做security验证
- demo-client 客户端使用feign调用server端接口
- demo-gateway 网关层访问server端接口
1、demo-server项目:
-
1.1、pom.xml引入如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
-
1.2、application.yml加入如下配置:
security:
basic:
enabled: true
user:
name: app01
password: passwd01
-
1.3、启动工程后访问接口会出现下图:
2、demo-client项目:
-
2.1、feignclient客户端加入BasicAuth授权信息:
@FeignClient(value = "demo-server", configuration = BasicAuthConfiguration.class)
public interface SimpleClient {
}
-
2.2、BasicAuthConfiguration类如下
import feign.auth.BasicAuthRequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class BasicAuthConfiguration {
@Bean
public BasicAuthRequestInterceptor basicAuthorizationInterceptor() {
return new BasicAuthRequestInterceptor("app01", "passwd01");
}
}
-
2.3、启动demo-client,调用demo-server接口能正常调通
3、demo-gateway网关项目:
-
3.1、新建AccessFilter extends ZuulFilter,在run方法里加入Authorization的授权信息:
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
//添加Basic Auth认证信息
ctx.addZuulRequestHeader("Authorization", "Basic " + getBase64Credentials("app01", "passwd01"));
return null;
}
private String getBase64Credentials(String username, String password) {
String plainCreds = username + ":" + password;
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
return new String(base64CredsBytes);
}
-
3.2、application.ym里面加入:
zuul:
routes:
api-demo1:
path: /demo-server/**
sensitiveHeaders: Cookie,Set-Cookie,Authorization
serviceId: demo-server
-
3.3、启动gateway工程,就可以访问server的接口了