SpringCloud——自定义断言工厂
目录
场景:用户的请求头中需要有指定的用户名和密码才能访问。
断言工厂
参考系统
AfterRoutePredicateFactory
写法。
package com.zjw.factory;
import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
/**
* @since 2023/11/28 12:09
*/
@Component
public class AuthRoutePredicateFactory extends AbstractRoutePredicateFactory<AuthRoutePredicateFactory.Config> {
/**
* DateTime key.
*/
public static final String USER_NAME_KEY = "username";
public static final String PASS_WORD_KEY = "password";
public AuthRoutePredicateFactory() {
super(AuthRoutePredicateFactory.Config.class);
}
/**
* 认证校验逻辑
*/
@Override
public Predicate<ServerWebExchange> apply(AuthRoutePredicateFactory.Config config) {
return serverWebExchange -> {
// 获取到请求中的所有header
HttpHeaders headers = serverWebExchange.getRequest().getHeaders();
// 校验header中是否包含用户名和密码,如果包含,返回true,否则返回false
List<String> pwdList = headers.get(config.getUsername());
return pwdList != null && pwdList.contains(config.getPassword());
};
}
@Getter
@Setter
public static class Config {
private String username;
private String password;
}
@Override
public List<String> shortcutFieldOrder() {
return Arrays.asList(USER_NAME_KEY, PASS_WORD_KEY);
}
}
application.yml
server:
port: 9001
spring:
application:
name: depart-consumer # 微服务名称
cloud:
gateway:
routes:
# 自定义断言工厂
- id: custom_auth_route
uri: http://localhost:8081
predicates:
- Auth=zhangsan, 123
请求头需要有zhangsan
,值为123
才能访问资源。
---------------
我每一次回头,都感觉自己不够努力,所以我不再回头。
---------------