如何在Spring Boot应用程序中使用API​​网关拦截请求

Ana*_*ukh 6 java interceptor spring-boot

我正在尝试做的是:

  • 我正在通过8765端口上运行的API-GATEWAY调用每个微服务
  • 对于路由,我已经在API网关中添加了zuell路由(调用运行良好)
  • 我希望对通过API网关的每个调用进行API密钥检查。即,如果API密钥为空或不正确,它将不会调用其他微服务。

以下是我的代码:

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        LOG.info("#### Starting TokenValidateInterceptor.preHandle ####");

        LOG.info("apikeyAttribute-->" + request.getAttribute("apiKey"); //coming as a blank
        LOG.info("apikeyHeader-->" + request.getHeader("apiKey"));//coming as a blank

        if (StringUtils.isBlank(apiKey)) {

            if (!request.getRequestURI().endsWith("/")) {

                try {
                    response.sendError(401, ("Unauthorized: Access is denied due to invalid credentials."));
                } catch (IOException e) {
                    LOG.error("##### IOException occured at TokenValidateInterceptor.preHandle() #####", e);
                } catch (Exception e) {
                    LOG.error("##### Generic Exception occured at TokenValidateInterceptor.preHandle() #####,e");
                }
                //This block is getting executed but still its calling the other microservice
                return false;
            } else {

                return true;
            }
        }
Run Code Online (Sandbox Code Playgroud)

我在这里面临2个问题-

  • 尽管我使用提供的API密钥来作为null postman
  • 正如我提到的,我这样做是为了进行验证检查。API密钥仍为空白,仍然调用相应的微服务

请参阅附件图片, 我给网关打电话的方式