【问题标题】:Set Swagger API Key in Spring Boot Camel在 Spring Boot Camel 中设置 Swagger API 密钥
【发布时间】:2021-09-09 13:53:54
【问题描述】:

我正在关注Camel Swagger Java docs 在 Camel 中设置 securityDefinitions。

rest("/user").tag("dude").description("User rest service")
    // setup security definitions
    .securityDefinitions()
        .apiKey("api_key").withHeader("myHeader").end()
    .end()
    .consumes("application/json").produces("application/json")
.get("/{id}/{date}").description("Find user by id and date").outType(User.class)
    .security("api_key")

因此,授权元素出现在 Swagger UI 上,但没有任何功能。

问题是,如何在 Spring Boot 中设置 API Key 并使授权元素能够正常工作?

【问题讨论】:

    标签: spring-boot apache-camel swagger


    【解决方案1】:

    可能不是最好的,但我想出了一个简单的解决方案,使用 if else 语句作为看门人,只需将提供的标头 API KEY 值与原始值进行比较。

    一旦我在 Camel 中设置了 securityDefinitions,就像我的问题所示,我在 Swagger UI 上获得了可以输入 API KEY 的授权元素。

    然后我将带有 API KEY 标头的请求发送到如下所示的 Service 类:

    public class Service{
    
        public void Result(Exchange exchange) {
    
            Message camelMessage = exchange.getIn();
    
            String api_key = String.valueOf(camelMessage.getHeader("myHeader"));
            System.out.println("API KEY: " + api_key);
    
            if(api_key.equals("original_api_key_value")){
                exchange.getOut().setBody("OK API KEY!");
                exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "application/json");
                exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, 200);
            }else{
                exchange.getOut().setBody("WRONG API KEY!");
                exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "application/json");
                exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, 401);
            }
       
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      • 2023-03-13
      • 2018-07-04
      • 2022-11-10
      • 2017-07-22
      • 2021-07-14
      • 2019-11-29
      相关资源
      最近更新 更多