Search in sources :

Example 6 with SecurityScheme

use of io.swagger.v3.oas.models.security.SecurityScheme in project carbon-apimgt by wso2.

the class OASParserUtil method setScopes.

private static void setScopes(final OpenAPI destOpenAPI, final Set<Scope> aggregatedScopes) {
    Map<String, SecurityScheme> securitySchemes;
    SecurityScheme securityScheme;
    OAuthFlow oAuthFlow;
    Scopes scopes = new Scopes();
    if (destOpenAPI.getComponents() != null && (securitySchemes = destOpenAPI.getComponents().getSecuritySchemes()) != null && (securityScheme = securitySchemes.get(OAS3Parser.OPENAPI_SECURITY_SCHEMA_KEY)) != null && (oAuthFlow = securityScheme.getFlows().getImplicit()) != null) {
        Map<String, String> scopeBindings = new HashMap<>();
        for (Scope scope : aggregatedScopes) {
            scopes.addString(scope.getKey(), scope.getDescription());
            scopeBindings.put(scope.getKey(), scope.getRoles());
        }
        oAuthFlow.setScopes(scopes);
        Map<String, Object> extensions = new HashMap<>();
        extensions.put(APIConstants.SWAGGER_X_SCOPES_BINDINGS, scopeBindings);
        oAuthFlow.setExtensions(extensions);
    }
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) OAuthFlow(io.swagger.v3.oas.models.security.OAuthFlow) HashMap(java.util.HashMap) Scopes(io.swagger.v3.oas.models.security.Scopes) JSONObject(org.json.JSONObject) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme)

Example 7 with SecurityScheme

use of io.swagger.v3.oas.models.security.SecurityScheme in project carbon-apimgt by wso2.

the class OAS3Parser method updateSwaggerSecurityDefinition.

/**
 * Include Scope details to the definition
 *
 * @param openAPI     openapi definition
 * @param swaggerData Swagger related API data
 */
private void updateSwaggerSecurityDefinition(OpenAPI openAPI, SwaggerData swaggerData, String authUrl) {
    if (openAPI.getComponents() == null) {
        openAPI.setComponents(new Components());
    }
    Map<String, SecurityScheme> securitySchemes = openAPI.getComponents().getSecuritySchemes();
    if (securitySchemes == null) {
        securitySchemes = new HashMap<>();
        openAPI.getComponents().setSecuritySchemes(securitySchemes);
    }
    SecurityScheme securityScheme = securitySchemes.get(OPENAPI_SECURITY_SCHEMA_KEY);
    if (securityScheme == null) {
        securityScheme = new SecurityScheme();
        securityScheme.setType(SecurityScheme.Type.OAUTH2);
        securitySchemes.put(OPENAPI_SECURITY_SCHEMA_KEY, securityScheme);
        List<SecurityRequirement> security = new ArrayList<SecurityRequirement>();
        SecurityRequirement secReq = new SecurityRequirement();
        secReq.addList(OPENAPI_SECURITY_SCHEMA_KEY, new ArrayList<String>());
        security.add(secReq);
        openAPI.setSecurity(security);
    }
    if (securityScheme.getFlows() == null) {
        securityScheme.setFlows(new OAuthFlows());
    }
    OAuthFlow oAuthFlow = securityScheme.getFlows().getImplicit();
    if (oAuthFlow == null) {
        oAuthFlow = new OAuthFlow();
        securityScheme.getFlows().setImplicit(oAuthFlow);
    }
    oAuthFlow.setAuthorizationUrl(authUrl);
    Scopes oas3Scopes = new Scopes();
    Set<Scope> scopes = swaggerData.getScopes();
    if (scopes != null && !scopes.isEmpty()) {
        Map<String, String> scopeBindings = new HashMap<>();
        for (Scope scope : scopes) {
            String description = scope.getDescription() != null ? scope.getDescription() : "";
            oas3Scopes.put(scope.getKey(), description);
            String roles = (StringUtils.isNotBlank(scope.getRoles()) && scope.getRoles().trim().split(",").length > 0) ? scope.getRoles() : StringUtils.EMPTY;
            scopeBindings.put(scope.getKey(), roles);
        }
        oAuthFlow.addExtension(APIConstants.SWAGGER_X_SCOPES_BINDINGS, scopeBindings);
    }
    oAuthFlow.setScopes(oas3Scopes);
}
Also used : OAuthFlows(io.swagger.v3.oas.models.security.OAuthFlows) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) Components(io.swagger.v3.oas.models.Components) Scope(org.wso2.carbon.apimgt.api.model.Scope) OAuthFlow(io.swagger.v3.oas.models.security.OAuthFlow) Scopes(io.swagger.v3.oas.models.security.Scopes) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) SecurityRequirement(io.swagger.v3.oas.models.security.SecurityRequirement)

Example 8 with SecurityScheme

use of io.swagger.v3.oas.models.security.SecurityScheme in project carbon-apimgt by wso2.

the class OAS3ParserTest method testUpdateAPIDefinitionWithExtensions.

@Test
public void testUpdateAPIDefinitionWithExtensions() throws Exception {
    String relativePath = "definitions" + File.separator + "oas3" + File.separator + "oas3Resources.json";
    String oas3Resources = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath), "UTF-8");
    OpenAPIV3Parser openAPIV3Parser = new OpenAPIV3Parser();
    // check remove vendor extensions
    String definition = testGenerateAPIDefinitionWithExtension(oas3Parser, oas3Resources);
    SwaggerParseResult parseAttemptForV3 = openAPIV3Parser.readContents(definition, null, null);
    OpenAPI openAPI = parseAttemptForV3.getOpenAPI();
    boolean isExtensionNotFound = openAPI.getExtensions() == null || !openAPI.getExtensions().containsKey(APIConstants.SWAGGER_X_WSO2_SECURITY);
    Assert.assertTrue(isExtensionNotFound);
    Assert.assertEquals(2, openAPI.getPaths().size());
    Iterator<Map.Entry<String, PathItem>> itr = openAPI.getPaths().entrySet().iterator();
    while (itr.hasNext()) {
        Map.Entry<String, PathItem> pathEntry = itr.next();
        PathItem path = pathEntry.getValue();
        for (Operation operation : path.readOperations()) {
            Assert.assertFalse(operation.getExtensions().containsKey(APIConstants.SWAGGER_X_SCOPE));
        }
    }
    // check updated scopes in security definition
    Operation itemGet = openAPI.getPaths().get("/items").getGet();
    Assert.assertTrue(itemGet.getSecurity().get(0).get("default").contains("newScope"));
    // check available scopes in security definition
    SecurityScheme securityScheme = openAPI.getComponents().getSecuritySchemes().get("default");
    OAuthFlow implicityOauth = securityScheme.getFlows().getImplicit();
    Assert.assertTrue(implicityOauth.getScopes().containsKey("newScope"));
    Assert.assertEquals("newScopeDescription", implicityOauth.getScopes().get("newScope"));
    Assert.assertTrue(implicityOauth.getExtensions().containsKey(APIConstants.SWAGGER_X_SCOPES_BINDINGS));
    Map<String, String> scopeBinding = (Map<String, String>) implicityOauth.getExtensions().get(APIConstants.SWAGGER_X_SCOPES_BINDINGS);
    Assert.assertTrue(scopeBinding.containsKey("newScope"));
    Assert.assertEquals("admin", scopeBinding.get("newScope"));
}
Also used : SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) Operation(io.swagger.v3.oas.models.Operation) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) PathItem(io.swagger.v3.oas.models.PathItem) OAuthFlow(io.swagger.v3.oas.models.security.OAuthFlow) OpenAPI(io.swagger.v3.oas.models.OpenAPI) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) Test(org.junit.Test)

Example 9 with SecurityScheme

use of io.swagger.v3.oas.models.security.SecurityScheme in project swagger-parser by swagger-api.

the class OpenAPIDeserializer method getSecurityScheme.

public SecurityScheme getSecurityScheme(ObjectNode node, String location, ParseResult result) {
    if (node == null) {
        return null;
    }
    SecurityScheme securityScheme = new SecurityScheme();
    JsonNode ref = node.get("$ref");
    if (ref != null) {
        if (ref.getNodeType().equals(JsonNodeType.STRING)) {
            String mungedRef = mungedRef(ref.textValue());
            if (mungedRef != null) {
                securityScheme.set$ref(mungedRef);
            } else {
                securityScheme.set$ref(ref.textValue());
            }
            return securityScheme;
        } else {
            result.invalidType(location, "$ref", "string", node);
            return null;
        }
    }
    boolean descriptionRequired, bearerFormatRequired, nameRequired, inRequired, schemeRequired, flowsRequired, openIdConnectRequired;
    descriptionRequired = bearerFormatRequired = nameRequired = inRequired = schemeRequired = flowsRequired = openIdConnectRequired = false;
    String value = getString("type", node, true, location, result);
    if ((result.isAllowEmptyStrings() && value != null) || (!result.isAllowEmptyStrings() && !StringUtils.isBlank(value))) {
        if (SecurityScheme.Type.APIKEY.toString().equals(value)) {
            securityScheme.setType(SecurityScheme.Type.APIKEY);
            nameRequired = inRequired = true;
        } else if (SecurityScheme.Type.HTTP.toString().equals(value)) {
            securityScheme.setType(SecurityScheme.Type.HTTP);
            schemeRequired = true;
        } else if (SecurityScheme.Type.OAUTH2.toString().equals(value)) {
            securityScheme.setType(SecurityScheme.Type.OAUTH2);
            flowsRequired = true;
        } else if (SecurityScheme.Type.OPENIDCONNECT.toString().equals(value)) {
            securityScheme.setType(SecurityScheme.Type.OPENIDCONNECT);
            openIdConnectRequired = true;
        } else {
            result.invalidType(location + ".type", "type", "http|apiKey|oauth2|openIdConnect ", node);
        }
    }
    value = getString("description", node, descriptionRequired, location, result);
    if ((result.isAllowEmptyStrings() && value != null) || (!result.isAllowEmptyStrings() && !StringUtils.isBlank(value))) {
        securityScheme.setDescription(value);
    }
    value = getString("name", node, nameRequired, location, result);
    if ((result.isAllowEmptyStrings() && value != null) || (!result.isAllowEmptyStrings() && !StringUtils.isBlank(value))) {
        securityScheme.setName(value);
    }
    final String securitySchemeIn = getString("in", node, inRequired, location, result);
    final Optional<SecurityScheme.In> matchingIn = Arrays.stream(SecurityScheme.In.values()).filter(in -> in.toString().equals(securitySchemeIn)).findFirst();
    securityScheme.setIn(matchingIn.orElse(null));
    value = getString("scheme", node, schemeRequired, location, result);
    if ((result.isAllowEmptyStrings() && value != null) || (!result.isAllowEmptyStrings() && !StringUtils.isBlank(value))) {
        securityScheme.setScheme(value);
    }
    value = getString("bearerFormat", node, bearerFormatRequired, location, result);
    if ((result.isAllowEmptyStrings() && value != null) || (!result.isAllowEmptyStrings() && !StringUtils.isBlank(value))) {
        securityScheme.setBearerFormat(value);
    }
    ObjectNode flowsObject = getObject("flows", node, flowsRequired, location, result);
    if (flowsObject != null) {
        securityScheme.setFlows(getOAuthFlows(flowsObject, location, result));
    }
    value = getString("openIdConnectUrl", node, openIdConnectRequired, location, result);
    if ((result.isAllowEmptyStrings() && value != null) || (!result.isAllowEmptyStrings() && !StringUtils.isBlank(value))) {
        securityScheme.setOpenIdConnectUrl(value);
    }
    Map<String, Object> extensions = getExtensions(node);
    if (extensions != null && extensions.size() > 0) {
        securityScheme.setExtensions(extensions);
    }
    Set<String> securitySchemeKeys = getKeys(node);
    for (String key : securitySchemeKeys) {
        if (!SECURITY_SCHEME_KEYS.contains(key) && !key.startsWith("x-")) {
            result.extra(location, key, node.get(key));
        }
    }
    return securityScheme;
}
Also used : DateSchema(io.swagger.v3.oas.models.media.DateSchema) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) Parameter(io.swagger.v3.oas.models.parameters.Parameter) SecurityRequirement(io.swagger.v3.oas.models.security.SecurityRequirement) Operation(io.swagger.v3.oas.models.Operation) Header(io.swagger.v3.oas.models.headers.Header) StringUtils(org.apache.commons.lang3.StringUtils) ComposedSchema(io.swagger.v3.oas.models.media.ComposedSchema) BigDecimal(java.math.BigDecimal) NullNode(com.fasterxml.jackson.databind.node.NullNode) License(io.swagger.v3.oas.models.info.License) Matcher(java.util.regex.Matcher) Scopes(io.swagger.v3.oas.models.security.Scopes) DateTimeSchema(io.swagger.v3.oas.models.media.DateTimeSchema) JsonNode(com.fasterxml.jackson.databind.JsonNode) Tag(io.swagger.v3.oas.models.tags.Tag) URI(java.net.URI) ByteArraySchema(io.swagger.v3.oas.models.media.ByteArraySchema) ParseException(java.text.ParseException) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) Content(io.swagger.v3.oas.models.media.Content) MediaType(io.swagger.v3.oas.models.media.MediaType) Example(io.swagger.v3.oas.models.examples.Example) RequestBody(io.swagger.v3.oas.models.parameters.RequestBody) Paths(io.swagger.v3.oas.models.Paths) StyleEnum(io.swagger.v3.oas.models.parameters.Parameter.StyleEnum) Collectors(java.util.stream.Collectors) TextNode(com.fasterxml.jackson.databind.node.TextNode) ExternalDocumentation(io.swagger.v3.oas.models.ExternalDocumentation) XML(io.swagger.v3.oas.models.media.XML) CookieParameter(io.swagger.v3.oas.models.parameters.CookieParameter) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) Server(io.swagger.v3.oas.models.servers.Server) OffsetDateTime(java.time.OffsetDateTime) Stream(java.util.stream.Stream) Contact(io.swagger.v3.oas.models.info.Contact) QueryParameter(io.swagger.v3.oas.models.parameters.QueryParameter) ObjectSchema(io.swagger.v3.oas.models.media.ObjectSchema) Pattern(java.util.regex.Pattern) Link(io.swagger.v3.oas.models.links.Link) RefUtils.extractSimpleName(io.swagger.v3.core.util.RefUtils.extractSimpleName) java.util(java.util) Json(io.swagger.v3.core.util.Json) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) OAuthFlows(io.swagger.v3.oas.models.security.OAuthFlows) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Schema(io.swagger.v3.oas.models.media.Schema) ServerVariables(io.swagger.v3.oas.models.servers.ServerVariables) JsonNodeType(com.fasterxml.jackson.databind.node.JsonNodeType) ApiResponses(io.swagger.v3.oas.models.responses.ApiResponses) Discriminator(io.swagger.v3.oas.models.media.Discriminator) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) PathItem(io.swagger.v3.oas.models.PathItem) Info(io.swagger.v3.oas.models.info.Info) MapSchema(io.swagger.v3.oas.models.media.MapSchema) Callback(io.swagger.v3.oas.models.callbacks.Callback) ParseOptions(io.swagger.v3.parser.core.models.ParseOptions) OAuthFlow(io.swagger.v3.oas.models.security.OAuthFlow) HeaderParameter(io.swagger.v3.oas.models.parameters.HeaderParameter) ServerVariable(io.swagger.v3.oas.models.servers.ServerVariable) Components(io.swagger.v3.oas.models.Components) PathParameter(io.swagger.v3.oas.models.parameters.PathParameter) Encoding(io.swagger.v3.oas.models.media.Encoding) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) JsonNode(com.fasterxml.jackson.databind.JsonNode) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme)

Example 10 with SecurityScheme

use of io.swagger.v3.oas.models.security.SecurityScheme in project swagger-parser by swagger-api.

the class OpenAPIDeserializerTest method testSecurityDefinition.

@Test
public void testSecurityDefinition() {
    String yaml = "openapi: 3.0.0\n" + "servers: []\n" + "paths:\n" + "  /pet:\n" + "    get:\n" + "      security:\n" + "        - basic_auth: []\n" + "          api_key: []\n" + "      responses:\n" + "        default:\n" + "          description: Default response\n" + "info:\n" + "  version: ''\n" + "  title: ''\n" + "components:\n" + "  securitySchemes:\n" + "    basic_auth:\n" + "      type: http\n" + "      x-foo: basicBar\n" + "      scheme: basic\n" + "    api_key:\n" + "      type: apiKey\n" + "      name: api_key\n" + "      in: header\n" + "      description: api key description\n" + "      x-foo: apiKeyBar";
    OpenAPIV3Parser parser = new OpenAPIV3Parser();
    SwaggerParseResult result = parser.readContents(yaml, null, null);
    OpenAPI openAPI = result.getOpenAPI();
    assertNotNull(openAPI.getComponents().getSecuritySchemes());
    assertTrue(openAPI.getComponents().getSecuritySchemes().keySet().size() == 2);
    // Basic Authentication
    SecurityScheme definitionBasic = openAPI.getComponents().getSecuritySchemes().get("basic_auth");
    assertNotNull(definitionBasic);
    assertEquals(definitionBasic.getType(), SecurityScheme.Type.HTTP);
    assertEquals(definitionBasic.getExtensions().get("x-foo"), "basicBar");
    // API Key Authentication
    SecurityScheme definition = openAPI.getComponents().getSecuritySchemes().get("api_key");
    assertNotNull(definition);
    assertEquals(definition.getType(), SecurityScheme.Type.APIKEY);
    SecurityScheme apiKey = definition;
    assertEquals(apiKey.getName(), "api_key");
    assertEquals(apiKey.getIn(), SecurityScheme.In.HEADER);
    assertEquals(apiKey.getDescription(), "api key description");
    assertEquals(apiKey.getExtensions().get("x-foo"), "apiKeyBar");
}
Also used : SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) OpenAPI(io.swagger.v3.oas.models.OpenAPI) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) Test(org.testng.annotations.Test)

Aggregations

SecurityScheme (io.swagger.v3.oas.models.security.SecurityScheme)35 OpenAPI (io.swagger.v3.oas.models.OpenAPI)20 Components (io.swagger.v3.oas.models.Components)15 OAuthFlow (io.swagger.v3.oas.models.security.OAuthFlow)13 Scopes (io.swagger.v3.oas.models.security.Scopes)12 OAuthFlows (io.swagger.v3.oas.models.security.OAuthFlows)11 Test (org.testng.annotations.Test)11 SecurityRequirement (io.swagger.v3.oas.models.security.SecurityRequirement)8 Operation (io.swagger.v3.oas.models.Operation)7 PathItem (io.swagger.v3.oas.models.PathItem)7 Info (io.swagger.v3.oas.models.info.Info)7 HashMap (java.util.HashMap)6 LinkedHashMap (java.util.LinkedHashMap)6 JsonNode (com.fasterxml.jackson.databind.JsonNode)5 MediaType (io.swagger.v3.oas.models.media.MediaType)5 Schema (io.swagger.v3.oas.models.media.Schema)5 Parameter (io.swagger.v3.oas.models.parameters.Parameter)5 ApiResponse (io.swagger.v3.oas.models.responses.ApiResponse)5 SwaggerParseResult (io.swagger.v3.parser.core.models.SwaggerParseResult)5 ArrayList (java.util.ArrayList)5