Search in sources :

Example 6 with SecurityRequirement

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

the class OpenAPIDeserializerTest method testPaths.

@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"));
}
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) Collections.emptyList(java.util.Collections.emptyList) List(java.util.List) OpenAPI(io.swagger.v3.oas.models.OpenAPI) HashSet(java.util.HashSet) SecurityRequirement(io.swagger.v3.oas.models.security.SecurityRequirement) Test(org.testng.annotations.Test)

Example 7 with SecurityRequirement

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

the class OpenAPIDeserializerTest method readEmptySecurityRequirement.

@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);
}
Also used : YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) JsonNode(com.fasterxml.jackson.databind.JsonNode) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) OpenAPI(io.swagger.v3.oas.models.OpenAPI) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) SecurityRequirement(io.swagger.v3.oas.models.security.SecurityRequirement) Test(org.testng.annotations.Test)

Example 8 with SecurityRequirement

use of io.swagger.v3.oas.models.security.SecurityRequirement in project snow-owl by b2ihealthcare.

the class BaseApiConfig method docs.

/**
 * Expose this as @Bean annotated component in the implementation configuration class.
 * @return a configured docket for this API module
 */
protected final GroupedOpenApi docs(final String apiBaseUrl, final String apiGroup, final String apiVersion, final String apiTitle, final String apiTermsOfServiceUrl, final String apiContact, final String apiLicense, final String apiLicenseUrl, final String apiDescription) {
    return GroupedOpenApi.builder().group(apiGroup).pathsToMatch(apiBaseUrl.endsWith("/") ? apiBaseUrl + "**" : apiBaseUrl + "/**").packagesToScan(getApiBasePackages()).addOpenApiCustomiser(api -> {
        Info apiInfo = api.getInfo();
        apiInfo.setTitle(apiTitle);
        apiInfo.setDescription(apiDescription);
        apiInfo.setVersion(apiVersion);
        apiInfo.setTermsOfService(apiTermsOfServiceUrl);
        Contact contact = new Contact();
        contact.setName("B2i Healthcare");
        contact.setEmail(apiContact);
        contact.setUrl(apiLicenseUrl);
        apiInfo.setContact(contact);
        License license = new License();
        license.setName(apiLicense);
        license.setUrl(apiLicenseUrl);
        apiInfo.setLicense(license);
        // configure global security
        api.getComponents().addSecuritySchemes("basic", new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("basic")).addSecuritySchemes("bearer", new SecurityScheme().type(SecurityScheme.Type.APIKEY).scheme("bearer").in(In.HEADER).bearerFormat("JWT"));
        // disable servers prop
        api.setServers(List.of());
    }).addOperationCustomizer((operation, method) -> {
        return operation.addSecurityItem(new SecurityRequirement().addList("basic").addList("bearer"));
    }).build();
// .useDefaultResponseMessages(false)
// .alternateTypeRules(getAlternateTypeRules(resolver));
}
Also used : Configuration(org.springframework.context.annotation.Configuration) List(java.util.List) License(io.swagger.v3.oas.models.info.License) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) Contact(io.swagger.v3.oas.models.info.Contact) In(io.swagger.v3.oas.models.security.SecurityScheme.In) GroupedOpenApi(org.springdoc.core.GroupedOpenApi) AnnotationUtils(org.springframework.core.annotation.AnnotationUtils) Info(io.swagger.v3.oas.models.info.Info) SecurityRequirement(io.swagger.v3.oas.models.security.SecurityRequirement) Bean(org.springframework.context.annotation.Bean) ComponentScan(org.springframework.context.annotation.ComponentScan) License(io.swagger.v3.oas.models.info.License) Info(io.swagger.v3.oas.models.info.Info) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) Contact(io.swagger.v3.oas.models.info.Contact) SecurityRequirement(io.swagger.v3.oas.models.security.SecurityRequirement)

Example 9 with SecurityRequirement

use of io.swagger.v3.oas.models.security.SecurityRequirement in project swagger-core by swagger-api.

the class JsonDeserializationTest method testDeserializeSecurity.

@Test
public void testDeserializeSecurity() throws Exception {
    final OpenAPI swagger = TestUtils.deserializeJsonFileFromClasspath("specFiles/securityDefinitions.json", OpenAPI.class);
    final List<SecurityRequirement> security = swagger.getSecurity();
    assertNotNull(security);
    assertEquals(security.size(), 3);
    final Map<String, SecurityScheme> securitySchemes = swagger.getComponents().getSecuritySchemes();
    assertNotNull(securitySchemes);
    assertEquals(securitySchemes.size(), 4);
    {
        final SecurityScheme scheme = securitySchemes.get("petstore_auth");
        assertNotNull(scheme);
        assertEquals(scheme.getType().toString(), "oauth2");
        assertEquals(scheme.getFlows().getImplicit().getAuthorizationUrl(), "http://petstore.swagger.io/oauth/dialog");
        assertEquals(scheme.getFlows().getImplicit().getScopes().get("write:pets"), "modify pets in your account");
        assertEquals(scheme.getFlows().getImplicit().getScopes().get("read:pets"), "read your pets");
    }
    {
        final SecurityScheme scheme = securitySchemes.get("api_key");
        assertNotNull(scheme);
        assertEquals(scheme.getType().toString(), "apiKey");
        assertEquals(scheme.getIn().toString(), "header");
        assertEquals(scheme.getName(), "api_key");
    }
    {
        final SecurityScheme scheme = securitySchemes.get("http");
        assertNotNull(scheme);
        assertEquals(scheme.getType().toString(), "http");
        assertEquals(scheme.getScheme(), "basic");
    }
    {
        final SecurityScheme scheme = securitySchemes.get("open_id_connect");
        assertNotNull(scheme);
        assertEquals(scheme.getType().toString(), "openIdConnect");
        assertEquals(scheme.getOpenIdConnectUrl(), "http://petstore.swagger.io/openid");
    }
    {
        final SecurityRequirement securityRequirement = security.get(0);
        final List<String> scopes = securityRequirement.get("petstore_auth");
        assertNotNull(scopes);
        assertEquals(scopes.size(), 2);
        assertTrue(scopes.contains("write:pets"));
        assertTrue(scopes.contains("read:pets"));
    }
    {
        final SecurityRequirement securityRequirement = security.get(1);
        final List<String> scopes = securityRequirement.get("api_key");
        assertNotNull(scopes);
        assertTrue(scopes.isEmpty());
    }
    {
        final SecurityRequirement securityRequirement = security.get(2);
        final List<String> scopes = securityRequirement.get("http");
        assertNotNull(scopes);
        assertTrue(scopes.isEmpty());
    }
}
Also used : List(java.util.List) OpenAPI(io.swagger.v3.oas.models.OpenAPI) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) SecurityRequirement(io.swagger.v3.oas.models.security.SecurityRequirement) Test(org.testng.annotations.Test)

Example 10 with SecurityRequirement

use of io.swagger.v3.oas.models.security.SecurityRequirement in project swagger-core by swagger-api.

the class SecurityDefinitionTest method createModelWithSecurityRequirements.

@Test(description = "it should create a model with security requirements")
public void createModelWithSecurityRequirements() throws IOException {
    final Schema personModel = ModelConverters.getInstance().read(Person.class).get("Person");
    final Schema errorModel = ModelConverters.getInstance().read(Error.class).get("Error");
    final Info info = new Info().version("1.0.0").title("Swagger Petstore");
    final Contact contact = new Contact().name("Swagger API Team").email("foo@bar.baz").url("http://swagger.io");
    info.setContact(contact);
    final OpenAPI oas = new OpenAPI().info(info).addServersItem(new Server().url("http://petstore.swagger.io")).schema("Person", personModel).schema("Error", errorModel);
    oas.schemaRequirement("githubAccessCode", new SecurityScheme().flows(new OAuthFlows().authorizationCode(new OAuthFlow().scopes(new Scopes().addString("user:email", "Grants read access to a user’s email addresses.")))));
    final Operation get = new Operation().summary("finds pets in the system").description("a longer description").addTagsItem("Pet Operations").operationId("get pet by id");
    get.addParametersItem(new Parameter().in("query").name("tags").description("tags to filter by").required(false).schema(new StringSchema()));
    get.addParametersItem(new Parameter().in("path").name("petId").description("pet to fetch").schema(new IntegerSchema().format("int64")));
    final ApiResponse response = new ApiResponse().description("pets returned").content(new Content().addMediaType("*/*", new MediaType().schema(new Schema().$ref("Person"))));
    final ApiResponse errorResponse = new ApiResponse().description("error response").content(new Content().addMediaType("*/*", new MediaType().schema(new Schema().$ref("Error"))));
    get.responses(new ApiResponses().addApiResponse("200", response).addApiResponse("default", errorResponse)).addSecurityItem(new SecurityRequirement().addList("internal_oauth2", "user:email")).addSecurityItem(new SecurityRequirement().addList("api_key"));
    oas.path("/pets", new PathItem().get(get));
    final String json = ResourceUtils.loadClassResource(getClass(), "ModelWithSecurityRequirements.json");
    SerializationMatchers.assertEqualsToJson(oas, json);
}
Also used : Server(io.swagger.v3.oas.models.servers.Server) OAuthFlows(io.swagger.v3.oas.models.security.OAuthFlows) Schema(io.swagger.v3.oas.models.media.Schema) IntegerSchema(io.swagger.v3.oas.models.media.IntegerSchema) StringSchema(io.swagger.v3.oas.models.media.StringSchema) IntegerSchema(io.swagger.v3.oas.models.media.IntegerSchema) Operation(io.swagger.v3.oas.models.Operation) Info(io.swagger.v3.oas.models.info.Info) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) Contact(io.swagger.v3.oas.models.info.Contact) PathItem(io.swagger.v3.oas.models.PathItem) OAuthFlow(io.swagger.v3.oas.models.security.OAuthFlow) Scopes(io.swagger.v3.oas.models.security.Scopes) Content(io.swagger.v3.oas.models.media.Content) Parameter(io.swagger.v3.oas.models.parameters.Parameter) MediaType(io.swagger.v3.oas.models.media.MediaType) StringSchema(io.swagger.v3.oas.models.media.StringSchema) Person(io.swagger.v3.core.oas.models.Person) OpenAPI(io.swagger.v3.oas.models.OpenAPI) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) ApiResponses(io.swagger.v3.oas.models.responses.ApiResponses) SecurityRequirement(io.swagger.v3.oas.models.security.SecurityRequirement) Test(org.testng.annotations.Test)

Aggregations

SecurityRequirement (io.swagger.v3.oas.models.security.SecurityRequirement)23 OpenAPI (io.swagger.v3.oas.models.OpenAPI)14 Operation (io.swagger.v3.oas.models.Operation)11 ArrayList (java.util.ArrayList)10 PathItem (io.swagger.v3.oas.models.PathItem)8 SecurityScheme (io.swagger.v3.oas.models.security.SecurityScheme)8 HashMap (java.util.HashMap)8 LinkedHashMap (java.util.LinkedHashMap)8 List (java.util.List)8 Test (org.testng.annotations.Test)8 Components (io.swagger.v3.oas.models.Components)7 Map (java.util.Map)7 HashSet (java.util.HashSet)5 Paths (io.swagger.v3.oas.models.Paths)4 OAuthFlow (io.swagger.v3.oas.models.security.OAuthFlow)4 OAuthFlows (io.swagger.v3.oas.models.security.OAuthFlows)4 Scopes (io.swagger.v3.oas.models.security.Scopes)4 JsonNode (com.fasterxml.jackson.databind.JsonNode)3 HttpMethod (io.swagger.models.HttpMethod)3 Json (io.swagger.v3.core.util.Json)3