1 package io.swagger.v3.core.util;
2
3 import com.fasterxml.jackson.core.JsonParseException;
4 import com.fasterxml.jackson.core.JsonParser;
5 import com.fasterxml.jackson.core.JsonProcessingException;
6 import com.fasterxml.jackson.databind.DeserializationContext;
7 import com.fasterxml.jackson.databind.JsonDeserializer;
8 import com.fasterxml.jackson.databind.JsonNode;
9 import io.swagger.v3.oas.models.security.OAuthFlows;
10 import io.swagger.v3.oas.models.security.SecurityScheme;
11
12 import java.io.IOException;
13 import java.util.Arrays;
14
15 public class SecuritySchemeDeserializer extends JsonDeserializer<SecurityScheme> {
16     @Override
17     public SecurityScheme deserialize(JsonParser jp, DeserializationContext ctxt)
18             throws IOException, JsonProcessingException {
19         SecurityScheme result = null;
20
21         JsonNode node = jp.getCodec().readTree(jp);
22
23         JsonNode inNode = node.get("type");
24
25         if (inNode != null) {
26             String type = inNode.asText();
27             if (Arrays.stream(SecurityScheme.Type.values()).noneMatch(t -> t.toString().equals(type))) {
28                 // wrong type, throw exception
29                 throw new JsonParseException(jp, String.format("SecurityScheme type %s not allowed", type));
30             }
31             result = new SecurityScheme()
32                     .description(getFieldText("description", node));
33
34             if ("http".equals(type)) {
35                 result
36                         .type(SecurityScheme.Type.HTTP)
37                         .scheme(getFieldText("scheme", node))
38                         .bearerFormat(getFieldText("bearerFormat", node));
39             } else if ("apiKey".equals(type)) {
40                 result
41                         .type(SecurityScheme.Type.APIKEY)
42                         .name(getFieldText("name", node))
43                         .in(getIn(getFieldText("in", node)));
44             } else if ("openIdConnect".equals(type)) {
45                 result
46                         .type(SecurityScheme.Type.OPENIDCONNECT)
47                         .openIdConnectUrl(getFieldText("openIdConnectUrl", node));
48             } else if ("oauth2".equals(type)) {
49                 result
50                         .type(SecurityScheme.Type.OAUTH2)
51                         .flows(Json.mapper().convertValue(node.get("flows"), OAuthFlows.class));
52             }
53         }
54
55         return result;
56     }
57
58     private SecurityScheme.In getIn(String value) {
59         return Arrays.stream(SecurityScheme.In.values()).filter(i -> i.toString().equals(value)).findFirst().orElse(null);
60     }
61
62     private String getFieldText(String fieldName, JsonNode node) {
63         JsonNode inNode = node.get(fieldName);
64         if (inNode != null) {
65             return inNode.asText();
66         }
67         return null;
68     }
69 }
70