Java Code Examples for io.swagger.v3.oas.models.Operation#getSecurity()

The following examples show how to use io.swagger.v3.oas.models.Operation#getSecurity() . 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: 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 2
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 3
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 4
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 5
Source File: OASMergeUtil.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
public static Operation mergeOperations(Operation thisOperation, Operation thatOperation) {
  if (thatOperation == null) {
    return thisOperation;
  }

  if (thatOperation.getTags() != null) {
    thisOperation.setTags(
        mergeTags(thisOperation.getTags(), thatOperation.getTags())
    );
  }
  if (thatOperation.getExternalDocs() != null) {
    thisOperation.setExternalDocs(
      mergeExternalDocumentation(thisOperation.getExternalDocs(), thatOperation.getExternalDocs())
    );
  }
  if (thatOperation.getParameters() != null) {
    thisOperation.setParameters(
        mergeParameters(thisOperation.getParameters(), thatOperation.getParameters())
    );
  }
  if (thatOperation.getRequestBody() != null) {
    thisOperation.setRequestBody(thatOperation.getRequestBody());
  }
  if (thatOperation.getResponses() != null) {
    thisOperation.setResponses(thatOperation.getResponses());
  }
  if (thatOperation.getCallbacks() != null) {
    thisOperation.setCallbacks(thatOperation.getCallbacks());
  }
  if (thatOperation.getDeprecated() != null) {
    thisOperation.setDeprecated(thatOperation.getDeprecated());
  }
  if (thatOperation.getSecurity() != null) {
    thisOperation.setSecurity(thatOperation.getSecurity());
  }
  if (thatOperation.getServers() != null) {
    thisOperation.setServers(thatOperation.getServers());
  }
  if (thatOperation.getExtensions() != null) {
    thisOperation.setExtensions(thatOperation.getExtensions());
  }
  if (thatOperation.getOperationId() != null) {
    thisOperation.setOperationId(thatOperation.getOperationId());
  }
  if (thatOperation.getSummary() != null) {
    thisOperation.setSummary(thatOperation.getSummary());
  }
  if (thatOperation.getDescription() != null) {
    thisOperation.setDescription(thatOperation.getDescription());
  }
  if (thatOperation.getExtensions() != null) {
    thisOperation.setExtensions(thatOperation.getExtensions());
  }
  return thisOperation;
}
 
Example 6
Source File: OperationDiff.java    From openapi-diff with Apache License 2.0 4 votes vote down vote up
public Optional<ChangedOperation> diff(
    Operation oldOperation, Operation newOperation, DiffContext context) {
  ChangedOperation changedOperation =
      new ChangedOperation(context.getUrl(), context.getMethod(), oldOperation, newOperation);

  openApiDiff
      .getMetadataDiff()
      .diff(oldOperation.getSummary(), newOperation.getSummary(), context)
      .ifPresent(changedOperation::setSummary);
  openApiDiff
      .getMetadataDiff()
      .diff(oldOperation.getDescription(), newOperation.getDescription(), context)
      .ifPresent(changedOperation::setDescription);
  changedOperation.setDeprecated(
      !Boolean.TRUE.equals(oldOperation.getDeprecated())
          && Boolean.TRUE.equals(newOperation.getDeprecated()));

  if (oldOperation.getRequestBody() != null || newOperation.getRequestBody() != null) {
    openApiDiff
        .getRequestBodyDiff()
        .diff(
            oldOperation.getRequestBody(), newOperation.getRequestBody(), context.copyAsRequest())
        .ifPresent(changedOperation::setRequestBody);
  }

  openApiDiff
      .getParametersDiff()
      .diff(oldOperation.getParameters(), newOperation.getParameters(), context)
      .ifPresent(
          params -> {
            removePathParameters(context.getParameters(), params);
            changedOperation.setParameters(params);
          });

  if (oldOperation.getResponses() != null || newOperation.getResponses() != null) {
    openApiDiff
        .getApiResponseDiff()
        .diff(oldOperation.getResponses(), newOperation.getResponses(), context.copyAsResponse())
        .ifPresent(changedOperation::setApiResponses);
  }

  if (oldOperation.getSecurity() != null || newOperation.getSecurity() != null) {
    openApiDiff
        .getSecurityRequirementsDiff()
        .diff(oldOperation.getSecurity(), newOperation.getSecurity(), context)
        .ifPresent(changedOperation::setSecurityRequirements);
  }

  openApiDiff
      .getExtensionsDiff()
      .diff(oldOperation.getExtensions(), newOperation.getExtensions(), context)
      .ifPresent(extensions -> changedOperation.setExtensions(extensions));

  return isChanged(changedOperation);
}
 
Example 7
Source File: OpenAPIDeserializerTest.java    From swagger-parser with Apache License 2.0 4 votes vote down vote up
@Test
public void testPaths() {
    String json = "{\n" +
            "  \"openapi\": \"3.0.0\",\n" +
            "  \"paths\": {\n" +
            "    \"/pet\": {\n" +
            "      \"foo\": \"bar\",\n" +
            "      \"get\": {\n" +
            "        \"security\": [\n" +
            "          {\n" +
            "            \"petstore_auth\": [\n" +
            "              \"write:pets\",\n" +
            "              \"read:pets\"\n" +
            "            ]\n" +
            "          }\n" +
            "        ]\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";
    OpenAPIV3Parser parser = new OpenAPIV3Parser();

    SwaggerParseResult result = parser.readContents(json, null, null);
    List<String> messageList = result.getMessages();
    Set<String> messages = new HashSet<>(messageList);

    assertTrue(messages.contains("attribute paths.'/pet'.foo is unexpected"));
    OpenAPI openAPI = result.getOpenAPI();

    PathItem path = openAPI.getPaths().get("/pet");
    assertNotNull(path);
    Operation operation = path.getGet();
    assertNotNull(operation);
    List<SecurityRequirement> security = operation.getSecurity();

    assertTrue(security.size() == 1);
    Map<String, List<String>> requirement = security.get(0);

    assertTrue(requirement.containsKey("petstore_auth"));
    List<String> scopesList = requirement.get("petstore_auth");

    Set<String> scopes = new HashSet<>(scopesList);
    assertTrue(scopes.contains("read:pets"));
    assertTrue(scopes.contains("write:pets"));
}
 
Example 8
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Updates managed info of a provided operation such as auth type and throttling
 *
 * @param resource  API resource data
 * @param operation swagger operation
 */
private void updateOperationManagedInfo(SwaggerData.Resource resource, Operation operation) {
    String authType = resource.getAuthType();
    if (APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN.equals(authType)) {
        authType = "Application & Application User";
    }
    if (APIConstants.AUTH_APPLICATION_USER_LEVEL_TOKEN.equals(authType)) {
        authType = "Application User";
    }
    if (APIConstants.AUTH_APPLICATION_LEVEL_TOKEN.equals(authType)) {
        authType = "Application";
    }
    operation.addExtension(APIConstants.SWAGGER_X_AUTH_TYPE, authType);
    operation.addExtension(APIConstants.SWAGGER_X_THROTTLING_TIER, resource.getPolicy());
    // AWS Lambda: set arn & timeout to swagger
    if (resource.getAmznResourceName() != null) {
        operation.addExtension(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME, resource.getAmznResourceName());
    }
    if (resource.getAmznResourceTimeout() != 0) {
        operation.addExtension(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT, resource.getAmznResourceTimeout());
    }
    updateLegacyScopesFromOperation(resource, operation);
    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) {

            if (resource.getScopes().isEmpty()) {
                requirement.put(OPENAPI_SECURITY_SCHEMA_KEY, Collections.EMPTY_LIST);
            } else {
                requirement.put(OPENAPI_SECURITY_SCHEMA_KEY, resource.getScopes().stream().map(Scope::getKey)
                        .collect(Collectors.toList()));
            }
            return;
        }
    }
    // if oauth2SchemeKey not present, add a new
    SecurityRequirement defaultRequirement = new SecurityRequirement();
    if (resource.getScopes().isEmpty()) {
        defaultRequirement.put(OPENAPI_SECURITY_SCHEMA_KEY, Collections.EMPTY_LIST);
    } else {
        defaultRequirement.put(OPENAPI_SECURITY_SCHEMA_KEY, resource.getScopes().stream().map(Scope::getKey)
                .collect(Collectors.toList()));
    }
    security.add(defaultRequirement);
}
 
Example 9
Source File: OAS3Parser.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This method returns URI templates according to the given swagger file(Swagger version 3)
 *
 * @param openAPI OpenAPI
 * @return OpenAPI
 * @throws APIManagementException
 */
private OpenAPI injectOtherResourceScopesToDefaultScheme(OpenAPI openAPI) throws APIManagementException {
    List<String> schemes = getOtherSchemes();

    Paths paths = openAPI.getPaths();
    for (String pathKey : paths.keySet()) {
        PathItem pathItem = paths.get(pathKey);
        Map<PathItem.HttpMethod, Operation> operationsMap = pathItem.readOperationsMap();
        SecurityRequirement updatedDefaultSecurityRequirement = new SecurityRequirement();
        for (Map.Entry<PathItem.HttpMethod, Operation> entry : operationsMap.entrySet()) {
            PathItem.HttpMethod httpMethod = entry.getKey();
            Operation operation = entry.getValue();
            List<SecurityRequirement> securityRequirements = operation.getSecurity();
            if (securityRequirements == null) {
                securityRequirements = new ArrayList<>();
            }
            if (APIConstants.SUPPORTED_METHODS.contains(httpMethod.name().toLowerCase())) {
                List<String> opScopesDefault = new ArrayList<>();
                List<String> opScopesDefaultInstance = getScopeOfOperations(OPENAPI_SECURITY_SCHEMA_KEY, operation);
                if (opScopesDefaultInstance != null) {
                    opScopesDefault.addAll(opScopesDefaultInstance);
                }
                updatedDefaultSecurityRequirement.put(OPENAPI_SECURITY_SCHEMA_KEY, opScopesDefault);
                for (Map<String, List<String>> input : securityRequirements) {
                    for (String scheme : schemes) {
                        if (!OPENAPI_SECURITY_SCHEMA_KEY.equals(scheme)) {
                            List<String> opScopesOthers = getScopeOfOperations(scheme, operation);
                            if (opScopesOthers != null) {
                                for (String scope : opScopesOthers) {
                                    if (!opScopesDefault.contains(scope)) {
                                        opScopesDefault.add(scope);
                                    }
                                }
                            }
                        }
                        updatedDefaultSecurityRequirement.put(OPENAPI_SECURITY_SCHEMA_KEY, opScopesDefault);
                    }
                }
                securityRequirements.add(updatedDefaultSecurityRequirement);
            }
            operation.setSecurity(securityRequirements);
            entry.setValue(operation);
            operationsMap.put(httpMethod, operation);
        }
        paths.put(pathKey, pathItem);
    }
    openAPI.setPaths(paths);
    return openAPI;
}