我正在开发API网关以将请求重定向到某些微服务。这是application.properties文件的一部分:
# _____ _____.__
# / _ \ ______ ______ ____ ____ _____/ ____\__| ____
# / /_\ \\____ \\____ \ _/ ___\/ _ \ / \ __\| |/ ___\
# / | \ |_> > |_> > \ \__( <_> ) | \ | | / /_/ >
# \____|__ / __/| __/ \___ >____/|___| /__| |__\___ /
# \/|__| |__| \/ \/ /_____/
server.port=8088
server.servlet.context-path=/PetApp
# __________ .__ _________ _____.__
# \____ /__ __ __ __| | \_ ___ \ ____ _____/ ____\__| ____
# / /| | \ | \ | / \ \/ / _ \ / \ __\| |/ ___\
# / /_| | / | / |__ \ \___( <_> ) | \ | | / /_/ >
# /_______ \____/|____/|____/ \______ /\____/|___| /__| |__\___ /
# \/ \/ \/ /_____/
#Routes for Auth
zuul.routes.tokenGenerator.path=/auth/login
zuul.routes.tokenGenerator.url=http://localhost:8086/PetApp_Auth/auth/generateToken
zuul.routes.tokenGenerator.stripPrefix=false
我正在尝试将请求从API网关(http://localhost:8080/PetApp/auth/login)重定向到(http://localhost:8086/PetApp_Auth/auth/generateToken)中运行的服务我已将邮递员的请求直接发送到微服务,它运行良好。
重要:我没有添加任何授权标头,因为该端点没有被证券化(并且运行良好),但是我的身份验证微服务中的其余API却被证券化了
但是当我尝试通过API网关发送请求时,得到以下信息:
可以看出,该请求被重定向到正确的微服务(Auth服务),但是没有重定向到正确的URL,因为其余的端点和所显示的URL都有例外。
我还尝试过将先前生成的授权令牌放入并发送到标头中,但未经授权我会得到同样的结果
我做错了什么?
也许您需要在zuul或auth微服务中禁用Spring安全性。只需删除spring安全依赖项,确保将令牌从zuul传递到auth ...
我已经通过添加过滤器解决了。Zuul像服务服务定义的URL + PATH一样构建完整的URL,因此我实现了一个删除路径的过滤器,现在其他微服务完美地接收了该请求。无论如何,我计划将端点定义更改为与微服务中定义的端点路径具有相同的端点路径,因为我认为使用可变路径无法解决该问题。我还将检查是否使用其他解决方案,例如@Maxim Sagaydachny建议的nginx或清漆]
@Component
public class PathConfigFilter extends ZuulFilter {
@Autowired
private ZuulProperties zuulProperties;
@Override
public String filterType() {
return FilterConstants.PRE_TYPE;
}
@Override
public int filterOrder() {
return FilterConstants.PRE_DECORATION_FILTER_ORDER + 1;
}
@Override
public boolean shouldFilter() {
return RequestContext.getCurrentContext().getFilterExecutionSummary().toString()
.contains( "PreDecorationFilter[SUCCESS]" );
}
@Override
public Object run() {
RequestContext context = RequestContext.getCurrentContext();
String originalRequestPath = (String) context.get(FilterConstants.REQUEST_URI_KEY);
//PathVariable change
URL routeHost = (URL) context.get( "routeHost");
String modifiedPathVariable = processPathVariableRoutes( routeHost.getPath(), originalRequestPath );
if(modifiedPathVariable != null){
try {
URL newUrl = new URL(routeHost,modifiedPathVariable);
context.put("routeHost", newUrl);
} catch (MalformedURLException e) {
throw new ApiGatewayException( ApiGatewayErrorCodes.PATH_VARIABLE_ERROR );
}
}
//Delete the path because the full path is defined in properties
context.put(FilterConstants.REQUEST_URI_KEY, "");
return null;
}
private String processPathVariableRoutes(String routeHost, String requestPath){
if(!routeHost.contains( "*" )){
return null;
}
ArrayList<String> splitedRoute = new ArrayList<>(Arrays.asList(routeHost.split( "/" )));
splitedRoute.remove( 0 );
String context = "/" + splitedRoute.get( 0 );
String realPath = context + requestPath;
return realPath;
}
}
非常感谢。