io.swagger.v3.oas.models.security.SecurityRequirement Java Examples

The following examples show how to use io.swagger.v3.oas.models.security.SecurityRequirement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SerializerUtilsTest.java    From openapi-generator with Apache License 2.0 7 votes vote down vote up
private OpenAPI createCompleteExample() {
    OpenAPI openAPI = new OpenAPI();
    openAPI.setInfo(new Info().title("Some title").description("Some description"));
    openAPI.setExternalDocs(new ExternalDocumentation().url("http://abcdef.com").description("a-description"));
    openAPI.setServers(Arrays.asList(
            new Server().url("http://www.server1.com").description("first server"),
            new Server().url("http://www.server2.com").description("second server")
        ));
    openAPI.setSecurity(Arrays.asList(
            new SecurityRequirement().addList("some_auth", Arrays.asList("write", "read"))
        ));
    openAPI.setTags(Arrays.asList(
            new Tag().name("tag1").description("some 1 description"),
            new Tag().name("tag2").description("some 2 description"),
            new Tag().name("tag3").description("some 3 description")
        ));
    openAPI.path("/ping/pong", new PathItem().get(new Operation()
            .description("Some description")
            .operationId("pingOp")
            .responses(new ApiResponses().addApiResponse("200", new ApiResponse().description("Ok")))));
    openAPI.components(new Components().addSchemas("SomeObject", new ObjectSchema().description("An Obj").addProperties("id", new StringSchema())));
    openAPI.setExtensions(new LinkedHashMap<>()); // required because swagger-core is using HashMap instead of LinkedHashMap internally.
    openAPI.addExtension("x-custom", "value1");
    openAPI.addExtension("x-other", "value2");
    return openAPI;
}
 
Example #2
Source File: BearerOpenAPIFilter.java    From RestDoc with Apache License 2.0 6 votes vote down vote up
@Override
public OpenAPI handle(OpenAPI openApi) {
    var components = openApi.getComponents();
    // security 添加 token
    var scheme = new SecurityScheme();
    scheme.setType(SecurityScheme.Type.HTTP);
    scheme.setScheme("bearer");
    scheme.setBearerFormat("JWT");
    components.addSecuritySchemes("bearerAuth", scheme);
    // path 添加 token
    var paths = openApi.getPaths();
    var securityRequirement = new SecurityRequirement().addList("bearerAuth");
    paths.forEach((s, pathItem) -> {
        handelPathItem(pathItem.getGet(), securityRequirement);
        handelPathItem(pathItem.getPost(), securityRequirement);
        handelPathItem(pathItem.getPut(), securityRequirement);
        handelPathItem(pathItem.getDelete(), securityRequirement);
        handelPathItem(pathItem.getPatch(), securityRequirement);
        handelPathItem(pathItem.getHead(), securityRequirement);
        handelPathItem(pathItem.getOptions(), securityRequirement);
        handelPathItem(pathItem.getTrace(), securityRequirement);
    });
    return openApi;
}
 
Example #3
Source File: SecurityRequirementsDiff.java    From openapi-diff with Apache License 2.0 6 votes vote down vote up
private List<Pair<SecurityScheme.Type, SecurityScheme.In>> getListOfSecuritySchemes(
    Components components, SecurityRequirement securityRequirement) {
  return securityRequirement
      .keySet()
      .stream()
      .map(
          x -> {
            SecurityScheme result = components.getSecuritySchemes().get(x);
            if (result == null) {
              throw new IllegalArgumentException("Impossible to find security scheme: " + x);
            }
            return result;
          })
      .map(this::getPair)
      .distinct()
      .collect(Collectors.toList());
}
 
Example #4
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void testSecurityDeserialization() throws Exception {
    String yaml = "openapi: 3.0.0\n" +
            "security:\n" +
            "  - api_key1: []\n" +
            "    api_key2: []\n" +
            "  - api_key3: []\n";

    OpenAPIV3Parser parser = new OpenAPIV3Parser();

    SwaggerParseResult result = parser.readContents(yaml, null, null);
    OpenAPI openAPI = result.getOpenAPI();
    assertNotNull(openAPI);

    List<SecurityRequirement> security = openAPI.getSecurity();
    assertTrue(security.size() == 2);

}
 
Example #5
Source File: OpenAPICodegenUtils.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
/**
 * Provide api keys for a given security requirement list.
 *
 * @param securityRequirementList {@link List<SecurityRequirement>} object
 * @return list of API Keys
 */
public static List<APIKey> generateAPIKeysFromSecurity(List<SecurityRequirement> securityRequirementList,
                                                       boolean isAPIKeyEnabled) {
    List<APIKey> apiKeys = new ArrayList<>();
    if (securityRequirementList != null) {
        securityRequirementList.forEach(value -> value.forEach((k, v) -> {
            //check if the key is in apikey list
            if (apiKeySecuritySchemaMap.containsKey(k)) {
                apiKeys.add((APIKey) apiKeySecuritySchemaMap.get(k));
            }
        }));
    }
    if (isAPIKeyEnabled && apiKeys.isEmpty()) {
        apiKeys.add(new APIKey(SecurityScheme.In.HEADER, OpenAPIConstants.DEFAULT_API_KEY_HEADER_QUERY));
        apiKeys.add(new APIKey(SecurityScheme.In.QUERY, OpenAPIConstants.DEFAULT_API_KEY_HEADER_QUERY));
    }
    return apiKeys;
}
 
Example #6
Source File: ProtoOpenAPI.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
/**
 * Add APIKey security requirement to the operation/API.
 * If {@link Operation} object is null, security requirement is added to the API.
 *
 * @param operation {@link Operation} object
 */
private void addAPIKeySecurityRequirement(Operation operation) {
    if (!isAPIKeyEnabled) {
        return;
    }
    if (openAPI.getComponents().getSecuritySchemes().get(APIKEY_SCHEME) != null) {
        SecurityRequirement apikeyReq = new SecurityRequirement();
        apikeyReq.addList(APIKEY_SCHEME);

        if (operation == null) {
            openAPI.addSecurityItem(apikeyReq);
        } else {
            operation.addSecurityItem(apikeyReq);
        }
    }
}
 
Example #7
Source File: ProtoOpenAPI.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
/**
 * Add Basic Auth security requirement to the operation/API.
 * If {@link Operation} object is null, security requirement is added to the API.
 *
 * @param operation {@link Operation} object
 */
private void addBasicAuthSecurityRequirement(Operation operation) {
    if (!isBasicAuthEnabled) {
        return;
    }
    if (openAPI.getComponents().getSecuritySchemes().get(BASIC_SCHEME) != null) {
        SecurityRequirement basicAuthReq = new SecurityRequirement();
        basicAuthReq.addList(BASIC_SCHEME);

        if (operation == null) {
            openAPI.addSecurityItem(basicAuthReq);
        } else {
            operation.addSecurityItem(basicAuthReq);
        }
    }
}
 
Example #8
Source File: ProtoOpenAPI.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
/**
 * Add Oauth2 security requirement to the operation/API.
 * If {@link Operation} object is null, security requirement is added to the API.
 *
 * @param operation {@link Operation} object
 * @param scopes    array of scopes
 */
private void addOauth2SecurityRequirement(Operation operation, String[] scopes) {
    //if Oauth2 is not available as a security scheme, adding scopes would be meaningless.
    if (!isOauth2Enabled) {
        if (scopes != null && scopes.length > 0 && !scopes[0].isEmpty()) {
            throw new CLIRuntimeException("Scopes cannot be added if \"oauth2\" is not provided as security type.");
        }
    }
    SecurityRequirement oauth2Req = new SecurityRequirement();
    //Since the scopes are not known at the start, the security scheme should be updated with newly identified
    //scopes as proceed
    if (scopes != null) {
        for (String scope : scopes) {
            addScopeToSchema(scope);
        }
        oauth2Req.addList(OAUTH2_SCHEME, Arrays.asList(scopes));
    } else {
        oauth2Req.addList(OAUTH2_SCHEME);
    }
    if (operation == null) {
        openAPI.addSecurityItem(oauth2Req);
    } else {
        operation.addSecurityItem(oauth2Req);
    }
}
 
Example #9
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 6 votes vote down vote up
@Test
public void readEmptySecurityRequirement() throws Exception {
    final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    final JsonNode rootNode = mapper.readTree(Files.readAllBytes(java.nio.file.Paths.get(getClass().getResource("/oas.yaml").toURI())));

    final OpenAPIDeserializer deserializer = new OpenAPIDeserializer();
    final SwaggerParseResult result = deserializer.deserialize(rootNode);

    Assert.assertNotNull(result);

    final OpenAPI openAPI = result.getOpenAPI();
    Assert.assertNotNull(openAPI);

    SecurityRequirement securityRequirement = openAPI.getSecurity().get(0);

    assertTrue(securityRequirement.isEmpty());
    assertEquals(openAPI.getSecurity().size(), 4);
}
 
Example #10
Source File: SecurityParser.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Gets security requirements.
 *
 * @param securityRequirementsApi the security requirements api
 * @return the security requirements
 */
public Optional<List<SecurityRequirement>> getSecurityRequirements(
		io.swagger.v3.oas.annotations.security.SecurityRequirement[] securityRequirementsApi) {
	if (securityRequirementsApi == null || securityRequirementsApi.length == 0)
		return Optional.empty();
	List<SecurityRequirement> securityRequirements = new ArrayList<>();
	for (io.swagger.v3.oas.annotations.security.SecurityRequirement securityRequirementApi : securityRequirementsApi) {
		if (StringUtils.isBlank(securityRequirementApi.name()))
			continue;
		SecurityRequirement securityRequirement = new SecurityRequirement();
		if (securityRequirementApi.scopes().length > 0)
			securityRequirement.addList(securityRequirementApi.name(), Arrays.asList(securityRequirementApi.scopes()));
		else
			securityRequirement.addList(securityRequirementApi.name());
		securityRequirements.add(securityRequirement);
	}
	if (securityRequirements.isEmpty())
		return Optional.empty();
	return Optional.of(securityRequirements);
}
 
Example #11
Source File: JaxRsActivatorNew.java    From pnc with Apache License 2.0 5 votes vote down vote up
private void configureSwagger() {
    OpenAPI oas = new OpenAPI();
    Info info = new Info().title("PNC")
            .description("PNC build system")
            .termsOfService("http://swagger.io/terms/")
            .license(new License().name("Apache 2.0").url("http://www.apache.org/licenses/LICENSE-2.0.html"));
    oas.info(info);
    oas.addServersItem(new Server().url("/pnc-rest-new"));

    final SecurityScheme authScheme = getAuthScheme();
    if (authScheme == null) {
        logger.warn("Not adding auth scheme to openapi definition as auth scheme could not been generated.");
    } else {
        oas.schemaRequirement(KEYCLOAK_AUTH, authScheme);
        oas.addSecurityItem(new SecurityRequirement().addList(KEYCLOAK_AUTH));
    }

    SwaggerConfiguration oasConfig = new SwaggerConfiguration().openAPI(oas);

    try {
        new JaxrsOpenApiContextBuilder().servletConfig(servletConfig)
                .application(this)
                .openApiConfiguration(oasConfig)
                .buildContext(true);
    } catch (OpenApiConfigurationException ex) {
        throw new IllegalArgumentException("Failed to setup OpenAPI configuration", ex);
    }
}
 
Example #12
Source File: OpenAPIUtils.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Extract the scopes of "default" security definition
 *
 * @param requirements security requirements of the operation
 * @return extracted scopes of "default" security definition
 */
private static List<String> getDefaultSecurityScopes(List<SecurityRequirement> requirements) {
    if (requirements != null) {
        for (SecurityRequirement requirement: requirements) {
            if (requirement.get(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY) != null) {
                return requirement.get(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY);
            }
        }
    }
    return new ArrayList<>();
}
 
Example #13
Source File: OASParserUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private static void readPathsAndScopes(PathItem srcPathItem, URITemplate uriTemplate,
                                       final Set<Scope> allScopes, SwaggerUpdateContext context) {
    Map<PathItem.HttpMethod, Operation> srcOperations = srcPathItem.readOperationsMap();

    PathItem.HttpMethod httpMethod = PathItem.HttpMethod.valueOf(uriTemplate.getHTTPVerb().toUpperCase());
    Operation srcOperation = srcOperations.get(httpMethod);

    Paths paths = context.getPaths();
    Set<Scope> aggregatedScopes = context.getAggregatedScopes();

    if (!paths.containsKey(uriTemplate.getUriTemplate())) {
        paths.put(uriTemplate.getUriTemplate(), new PathItem());
    }

    PathItem pathItem = paths.get(uriTemplate.getUriTemplate());
    pathItem.operation(httpMethod, srcOperation);

    readReferenceObjects(srcOperation, context);

    List<SecurityRequirement> srcOperationSecurity = srcOperation.getSecurity();
    if (srcOperationSecurity != null) {
        for (SecurityRequirement requirement : srcOperationSecurity) {
            List<String> scopes = requirement.get(OAS3Parser.OPENAPI_SECURITY_SCHEMA_KEY);
            if (scopes != null) {
                for (String scopeKey : scopes) {
                    for (Scope scope : allScopes) {
                        if (scope.getKey().equals(scopeKey)) {
                            aggregatedScopes.add(scope);
                        }
                    }
                }
            }
        }
    }
}
 
Example #14
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a list of scopes using the security requirements
 *
 * @param oauth2SchemeKey OAuth2 security element key
 * @param operation       Swagger path operation
 * @return list of scopes using the security requirements
 */
private List<String> getScopeOfOperations(String oauth2SchemeKey, Operation operation) {
    List<SecurityRequirement> security = operation.getSecurity();
    if (security != null) {
        for (Map<String, List<String>> requirement : security) {
            if (requirement.get(oauth2SchemeKey) != null) {
                return requirement.get(oauth2SchemeKey);
            }
        }
    }
    return getScopeOfOperationsFromExtensions(operation);
}
 
Example #15
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Update OAS operations for Store
 *
 * @param openAPI OpenAPI to be updated
 */
private void updateOperations(OpenAPI openAPI) {
    for (String pathKey : openAPI.getPaths().keySet()) {
        PathItem pathItem = openAPI.getPaths().get(pathKey);
        for (Map.Entry<PathItem.HttpMethod, Operation> entry : pathItem.readOperationsMap().entrySet()) {
            Operation operation = entry.getValue();
            Map<String, Object> extensions = operation.getExtensions();
            if (extensions != null) {
                // remove mediation extension
                if (extensions.containsKey(APIConstants.SWAGGER_X_MEDIATION_SCRIPT)) {
                    extensions.remove(APIConstants.SWAGGER_X_MEDIATION_SCRIPT);
                }
                // set x-scope value to security definition if it not there.
                if (extensions.containsKey(APIConstants.SWAGGER_X_WSO2_SCOPES)) {
                    String scope = (String) extensions.get(APIConstants.SWAGGER_X_WSO2_SCOPES);
                    List<SecurityRequirement> security = operation.getSecurity();
                    if (security == null) {
                        security = new ArrayList<>();
                        operation.setSecurity(security);
                    }
                    for (Map<String, List<String>> requirement : security) {
                        if (requirement.get(OPENAPI_SECURITY_SCHEMA_KEY) == null || !requirement
                                .get(OPENAPI_SECURITY_SCHEMA_KEY).contains(scope)) {
                            requirement.put(OPENAPI_SECURITY_SCHEMA_KEY, Collections.singletonList(scope));
                        }
                    }
                }
            }
        }
    }
}
 
Example #16
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testSecurity() {
    String json = "{\n" +
            "  \"openapi\": \"3.0.0\",\n" +
            "  \"security\": [\n" +
            "    {\n" +
            "      \"petstore_auth\": [\n" +
            "        \"write:pets\",\n" +
            "        \"read:pets\"\n" +
            "      ]\n" +
            "    }\n" +
            "  ]\n" +
            "}";
    OpenAPIV3Parser parser = new OpenAPIV3Parser();

    SwaggerParseResult result = parser.readContents(json, null, null);


    OpenAPI openAPI = result.getOpenAPI();

    assertNotNull(openAPI.getSecurity());
    List<SecurityRequirement> security = openAPI.getSecurity();
    Assert.assertTrue(security.size() == 1);
    Assert.assertTrue(security.get(0).size() == 1);

    List<String> requirement = security.get(0).get("petstore_auth");
    Assert.assertTrue(requirement.size() == 2);

    Set<String> requirements = new HashSet(requirement);
    Assert.assertTrue(requirements.contains("read:pets"));
    Assert.assertTrue(requirements.contains("write:pets"));
}
 
Example #17
Source File: SecurityHandlersStore.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
protected List<Handler<RoutingContext>> solveSecurityHandlers(List<SecurityRequirement> nonTranslatedKeys, boolean failOnNotFound) {
  List<SecurityRequirementKey> keys = this.translateRequirements(nonTranslatedKeys);
  if (keys != null) {
    if (failOnNotFound)
      return keys.stream().map(this::mapWithFail).flatMap(Collection::stream).collect(Collectors.toList());
    else
      return keys.stream().map(this::mapWithoutFail).filter(Objects::nonNull).flatMap(Collection::stream).collect(Collectors.toList());
  } else
    return new ArrayList<>();
}
 
Example #18
Source File: OpenAPIDeserializer.java    From swagger-parser with Apache License 2.0 5 votes vote down vote up
public List<SecurityRequirement> getSecurityRequirementsList(ArrayNode nodes, String location, ParseResult result) {
    if (nodes == null)
        return null;

    List<SecurityRequirement> securityRequirements = new ArrayList<>();

    for (JsonNode node : nodes) {
        if (node.getNodeType().equals(JsonNodeType.OBJECT)) {
            SecurityRequirement securityRequirement = new SecurityRequirement();
            Set<String> keys = getKeys((ObjectNode) node);
            if (keys.size() == 0){
                securityRequirements.add(securityRequirement);
            }else {
                for (String key : keys) {
                    if (key != null) {
                        JsonNode value = node.get(key);
                        if (key != null && JsonNodeType.ARRAY.equals(value.getNodeType())) {
                            ArrayNode arrayNode = (ArrayNode) value;
                            List<String> scopes = Stream
                                    .generate(arrayNode.elements()::next)
                                    .map((n) -> n.asText())
                                    .limit(arrayNode.size())
                                    .collect(Collectors.toList());
                            securityRequirement.addList(key, scopes);
                        }
                    }
                }
                if (securityRequirement.size() > 0) {
                    securityRequirements.add(securityRequirement);
                }
            }
        }
    }

    return securityRequirements;

}
 
Example #19
Source File: OpenApiObjectGenerator.java    From flow with Apache License 2.0 5 votes vote down vote up
private Operation createPostOperation(MethodDeclaration methodDeclaration) {
    Operation post = new Operation();
    SecurityRequirement securityItem = new SecurityRequirement();
    securityItem.addList(VAADIN_CONNECT_OAUTH2_SECURITY_SCHEME);
    post.addSecurityItem(securityItem);

    methodDeclaration.getJavadoc().ifPresent(javadoc -> post
            .setDescription(javadoc.getDescription().toText()));
    return post;
}
 
Example #20
Source File: SecurityDocument.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
@Override
public Document apply(Document document, SecurityDocument.Parameters parameters) {
    List<SecurityRequirement> securityRequirements = parameters.schema.getSecurity();
    if (null == securityRequirements || securityRequirements.isEmpty()) return document;

    Section securityRequirementsSection = new SectionImpl(document);
    securityRequirementsSection.setTitle(labels.getLabel(SECTION_TITLE_SECURITY));
    securityRequirementTableComponent.apply(securityRequirementsSection, securityRequirements, false);
    document.append(securityRequirementsSection);

    return document;
}
 
Example #21
Source File: SecurityRequirementTableComponent.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
@Override
public StructuralNode apply(StructuralNode node, SecurityRequirementTableComponent.Parameters parameters) {
    List<SecurityRequirement> securityRequirements = parameters.securityRequirements;

    if (securityRequirements == null || securityRequirements.isEmpty()) return node;

    TableImpl securityRequirementsTable = new TableImpl(node, new HashMap<>(), new ArrayList<>());
    securityRequirementsTable.setOption("header");
    securityRequirementsTable.setAttribute("caption", "", true);
    securityRequirementsTable.setAttribute("cols", ".^3a,.^4a,.^13a", true);
    if (parameters.addTitle) {
        securityRequirementsTable.setTitle(labels.getLabel(TABLE_TITLE_SECURITY));
    }
    securityRequirementsTable.setHeaderRow(
            labels.getLabel(TABLE_HEADER_TYPE),
            labels.getLabel(TABLE_HEADER_NAME),
            labels.getLabel(TABLE_HEADER_SCOPES));

    securityRequirements.forEach(securityRequirement ->
            securityRequirement.forEach((name, scopes) ->
                    securityRequirementsTable.addRow(
                            generateInnerDoc(securityRequirementsTable, boldUnconstrained(scopes.isEmpty() ? "apiKey" : "oauth2")),
                            generateInnerDoc(securityRequirementsTable, name),
                            generateInnerDoc(securityRequirementsTable, String.join(", ", scopes))
                    )
            )
    );
    node.append(securityRequirementsTable);
    return node;
}
 
Example #22
Source File: SecurityDiffInfo.java    From openapi-diff with Apache License 2.0 5 votes vote down vote up
public static SecurityRequirement getSecurityRequirement(
    List<SecurityDiffInfo> securityDiffInfoList) {
  SecurityRequirement securityRequirement = new SecurityRequirement();
  for (SecurityDiffInfo securityDiffInfo : securityDiffInfoList) {
    securityRequirement.put(securityDiffInfo.getRef(), securityDiffInfo.getScopes());
  }

  return securityRequirement;
}
 
Example #23
Source File: SecurityHandlersStore.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private List<SecurityRequirementKey> translateRequirements(List<SecurityRequirement> keys) {
  if (keys != null)
    return keys.stream()
      .flatMap(m -> m.entrySet().stream().flatMap(e -> {
        if (e.getValue() == null || e.getValue().size() == 0)
          return Stream.of(new SecurityRequirementKey(e.getKey()));
        else
          return e.getValue().stream().map(s -> new SecurityRequirementKey(e.getKey(), s));
      }))
      .collect(Collectors.toList());
  else
    return new ArrayList<>();
}
 
Example #24
Source File: SecurityRequirementsDiff.java    From openapi-diff with Apache License 2.0 5 votes vote down vote up
public boolean same(SecurityRequirement left, SecurityRequirement right) {
  //        List<SecurityScheme.Type> leftTypes = left.keySet().stream()
  //                .map(x -> leftComponents.getSecuritySchemes().get(x).getType())
  //                .collect(Collectors.toList());
  //        List<SecurityScheme.Type> rightTypes = right.keySet().stream()
  //                .map(x -> rightComponents.getSecuritySchemes().get(x).getType())
  //                .collect(Collectors.toList());
  //
  List<Pair<SecurityScheme.Type, SecurityScheme.In>> leftTypes =
      getListOfSecuritySchemes(leftComponents, left);
  List<Pair<SecurityScheme.Type, SecurityScheme.In>> rightTypes =
      getListOfSecuritySchemes(rightComponents, right);

  return CollectionUtils.isEqualCollection(leftTypes, rightTypes);
}
 
Example #25
Source File: SecurityRequirementDiff.java    From openapi-diff with Apache License 2.0 5 votes vote down vote up
private LinkedHashMap<String, List<String>> contains(
    SecurityRequirement right, String schemeRef) {
  SecurityScheme leftSecurityScheme = leftComponents.getSecuritySchemes().get(schemeRef);
  LinkedHashMap<String, List<String>> found = new LinkedHashMap<>();

  for (Map.Entry<String, List<String>> entry : right.entrySet()) {
    SecurityScheme rightSecurityScheme = rightComponents.getSecuritySchemes().get(entry.getKey());
    if (leftSecurityScheme.getType() == rightSecurityScheme.getType()) {
      switch (leftSecurityScheme.getType()) {
        case APIKEY:
          if (leftSecurityScheme.getName().equals(rightSecurityScheme.getName())) {
            found.put(entry.getKey(), entry.getValue());
            return found;
          }
          break;

        case OAUTH2:
        case HTTP:
        case OPENIDCONNECT:
          found.put(entry.getKey(), entry.getValue());
          return found;
      }
    }
  }

  return found;
}
 
Example #26
Source File: SpringDocApp76Test.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
@Bean
public OpenAPI openAPI() {
	return new OpenAPI()
			.components(new Components().addSecuritySchemes("bearer-jwt",
					new SecurityScheme()
							.type(SecurityScheme.Type.HTTP)
							.scheme("bearer")
							.bearerFormat("JWT"))
			)
			.addSecurityItem(
					new SecurityRequirement().addList("bearer-jwt", Arrays.asList("read", "write")));
}
 
Example #27
Source File: SecurityParser.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Get security requirements io . swagger . v 3 . oas . annotations . security . security requirement [ ].
 *
 * @param method the method
 * @return the io . swagger . v 3 . oas . annotations . security . security requirement [ ]
 */
public io.swagger.v3.oas.annotations.security.SecurityRequirement[] getSecurityRequirements(
		HandlerMethod method) {
	// class SecurityRequirements
	io.swagger.v3.oas.annotations.security.SecurityRequirements classSecurity = AnnotatedElementUtils.findMergedAnnotation(method.getBeanType(), io.swagger.v3.oas.annotations.security.SecurityRequirements.class);
	// method SecurityRequirements
	io.swagger.v3.oas.annotations.security.SecurityRequirements methodSecurity = AnnotatedElementUtils.findMergedAnnotation(method.getMethod(), io.swagger.v3.oas.annotations.security.SecurityRequirements.class);

	Set<io.swagger.v3.oas.annotations.security.SecurityRequirement> allSecurityTags = null;

	if (classSecurity != null)
		allSecurityTags = new HashSet<>(Arrays.asList(classSecurity.value()));
	if (methodSecurity != null)
		allSecurityTags = addSecurityRequirements(allSecurityTags, new HashSet<>(Arrays.asList(methodSecurity.value())));

	if (CollectionUtils.isEmpty(allSecurityTags)) {
		// class SecurityRequirement
		Set<io.swagger.v3.oas.annotations.security.SecurityRequirement> securityRequirementsClassList = AnnotatedElementUtils.findMergedRepeatableAnnotations(
				method.getBeanType(),
				io.swagger.v3.oas.annotations.security.SecurityRequirement.class);
		// method SecurityRequirement
		Set<io.swagger.v3.oas.annotations.security.SecurityRequirement> securityRequirementsMethodList = AnnotatedElementUtils.findMergedRepeatableAnnotations(method.getMethod(),
				io.swagger.v3.oas.annotations.security.SecurityRequirement.class);
		if (!CollectionUtils.isEmpty(securityRequirementsClassList))
			allSecurityTags = addSecurityRequirements(allSecurityTags, securityRequirementsClassList);
		if (!CollectionUtils.isEmpty(securityRequirementsMethodList))
			allSecurityTags = addSecurityRequirements(allSecurityTags, securityRequirementsMethodList);
	}

	return (allSecurityTags != null) ? allSecurityTags.toArray(new io.swagger.v3.oas.annotations.security.SecurityRequirement[0]) : null;
}
 
Example #28
Source File: SecurityParser.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Build security requirement.
 *
 * @param securityRequirements the security requirements
 * @param operation the operation
 */
public void buildSecurityRequirement(
		io.swagger.v3.oas.annotations.security.SecurityRequirement[] securityRequirements, Operation operation) {
	Optional<List<SecurityRequirement>> requirementsObject = this.getSecurityRequirements(securityRequirements);
	requirementsObject.ifPresent(requirements -> requirements.stream()
			.filter(r -> operation.getSecurity() == null || !operation.getSecurity().contains(r))
			.forEach(operation::addSecurityItem));
}
 
Example #29
Source File: AbstractAdaCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Override
public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List<Server> servers) {
    CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers);

    if (operation.getResponses() != null && !operation.getResponses().isEmpty()) {
        ApiResponse methodResponse = findMethodResponse(operation.getResponses());
        if (methodResponse != null && ModelUtils.getSchemaFromResponse(methodResponse) != null) {
            CodegenProperty cm = fromProperty("response", ModelUtils.getSchemaFromResponse(methodResponse));
            op.vendorExtensions.put("x-codegen-response", cm);
            if ("HttpContent".equals(cm.dataType)) {
                op.vendorExtensions.put("x-codegen-response-ishttpcontent", true);
            }
        }
    }

    // Add a vendor extension attribute that provides a map of auth methods and the scopes
    // which are expected by the operation.  This map is then used by postProcessOperationsWithModels
    // to build another vendor extension that provides a subset of the auth methods with only
    // the scopes required by the operation.
    final List<SecurityRequirement> securities = operation.getSecurity();
    if (securities != null && securities.size() > 0) {
        final Map<String, SecurityScheme> securitySchemes = this.openAPI.getComponents() != null ? this.openAPI.getComponents().getSecuritySchemes() : null;
        final List<SecurityRequirement> globalSecurities = this.openAPI.getSecurity();

        Map<String, List<String>> scopes = getAuthScopes(securities, securitySchemes);
        if (scopes.isEmpty() && globalSecurities != null) {
            scopes = getAuthScopes(globalSecurities, securitySchemes);
        }
        op.vendorExtensions.put("x-scopes", scopes);
    }
    return op;
}
 
Example #30
Source File: AbstractAdaCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
private Map<String, List<String>> getAuthScopes(List<SecurityRequirement> securities, Map<String, SecurityScheme> securitySchemes) {
    final Map<String, List<String>> scopes = new HashMap<>();
    Optional.ofNullable(securitySchemes).ifPresent(_securitySchemes -> {
        for (SecurityRequirement requirement : securities) {
            for (String key : requirement.keySet()) {
                Optional.ofNullable(securitySchemes.get(key))
                        .ifPresent(securityScheme -> scopes.put(key, requirement.get(key)));
            }
        }
    });
    return scopes;
}