use of io.swagger.v3.oas.models.security.SecurityRequirement in project carbon-apimgt by wso2.
the class OAS3Parser method copyVendorExtensions.
@Override
public String copyVendorExtensions(String existingOASContent, String updatedOASContent) {
OpenAPI existingOpenAPI = getOpenAPI(existingOASContent);
OpenAPI updatedOpenAPI = getOpenAPI(updatedOASContent);
Paths updatedPaths = updatedOpenAPI.getPaths();
Paths existingPaths = existingOpenAPI.getPaths();
// Merge Security Schemes
if (existingOpenAPI.getComponents().getSecuritySchemes() != null) {
if (updatedOpenAPI.getComponents() != null) {
updatedOpenAPI.getComponents().setSecuritySchemes(existingOpenAPI.getComponents().getSecuritySchemes());
} else {
Components components = new Components();
components.setSecuritySchemes(existingOpenAPI.getComponents().getSecuritySchemes());
updatedOpenAPI.setComponents(components);
}
}
// Merge Operation specific vendor extensions
for (String pathKey : updatedPaths.keySet()) {
Map<PathItem.HttpMethod, Operation> operationsMap = updatedPaths.get(pathKey).readOperationsMap();
for (Map.Entry<PathItem.HttpMethod, Operation> updatedEntry : operationsMap.entrySet()) {
if (existingPaths.keySet().contains(pathKey)) {
for (Map.Entry<PathItem.HttpMethod, Operation> existingEntry : existingPaths.get(pathKey).readOperationsMap().entrySet()) {
if (updatedEntry.getKey().equals(existingEntry.getKey())) {
Map<String, Object> vendorExtensions = updatedEntry.getValue().getExtensions();
Map<String, Object> existingExtensions = existingEntry.getValue().getExtensions();
boolean extensionsAreEmpty = false;
if (vendorExtensions == null) {
vendorExtensions = new HashMap<>();
extensionsAreEmpty = true;
}
OASParserUtil.copyOperationVendorExtensions(existingExtensions, vendorExtensions);
if (extensionsAreEmpty) {
updatedEntry.getValue().setExtensions(existingExtensions);
}
List<SecurityRequirement> securityRequirements = existingEntry.getValue().getSecurity();
List<SecurityRequirement> updatedRequirements = new ArrayList<>();
if (securityRequirements != null) {
for (SecurityRequirement requirement : securityRequirements) {
List<String> scopes = requirement.get(OAS3Parser.OPENAPI_SECURITY_SCHEMA_KEY);
if (scopes != null) {
updatedRequirements.add(requirement);
}
}
updatedEntry.getValue().setSecurity(updatedRequirements);
}
break;
}
}
}
}
}
return Json.pretty(updatedOpenAPI);
}
use of io.swagger.v3.oas.models.security.SecurityRequirement in project carbon-apimgt by wso2.
the class OAS3Parser method updateOperationManagedInfo.
/**
* 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);
if (resource.getPolicy() != null) {
operation.addExtension(APIConstants.SWAGGER_X_THROTTLING_TIER, resource.getPolicy());
} else {
operation.addExtension(APIConstants.SWAGGER_X_THROTTLING_TIER, APIConstants.DEFAULT_API_POLICY_UNLIMITED);
}
// 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);
}
use of io.swagger.v3.oas.models.security.SecurityRequirement in project openremote by openremote.
the class ManagerWebService method init.
@Override
public void init(Container container) throws Exception {
super.init(container);
String rootRedirectPath = getString(container.getConfig(), ROOT_REDIRECT_PATH, ROOT_REDIRECT_PATH_DEFAULT);
// Modify swagger object mapper to match ours
configureObjectMapper(Json.mapper());
Json.mapper().addMixIn(ServerVariable.class, ServerVariableMixin.class);
// Add swagger resource
OpenAPI oas = new OpenAPI().servers(Collections.singletonList(new Server().url("/api/{realm}/").variables(new ServerVariables().addServerVariable("realm", new ServerVariable()._default("master"))))).schemaRequirement("openid", new SecurityScheme().type(SecurityScheme.Type.OAUTH2).flows(new OAuthFlows().authorizationCode(new OAuthFlow().authorizationUrl("/auth/realms/master/protocol/openid-connect/auth").refreshUrl("/auth/realms/master/protocol/openid-connect/token").tokenUrl("/auth/realms/master/protocol/openid-connect/token")))).security(Collections.singletonList(new SecurityRequirement().addList("openid")));
Info info = new Info().title("OpenRemote Manager REST API").description("This is the documentation for the OpenRemote Manager HTTP REST API. Please see the [wiki](https://github.com/openremote/openremote/wiki) for more info.").contact(new Contact().email("info@openremote.io")).license(new License().name("AGPL 3.0").url("https://www.gnu.org/licenses/agpl-3.0.en.html"));
oas.info(info);
SwaggerConfiguration oasConfig = new SwaggerConfiguration().resourcePackages(Stream.of("org.openremote.model.*").collect(Collectors.toSet())).openAPI(oas);
OpenApiResource openApiResource = new OpenApiResource();
openApiResource.openApiConfiguration(oasConfig);
addApiSingleton(openApiResource);
initialised = true;
ResteasyDeployment resteasyDeployment = createResteasyDeployment(container, getApiClasses(), apiSingletons, true);
// Serve REST API
HttpHandler apiHandler = createApiHandler(container, resteasyDeployment);
if (apiHandler != null) {
// Authenticating requests requires a realm, either we receive this in a header or
// we extract it (e.g. from request path segment) and set it as a header before
// processing the request
HttpHandler baseApiHandler = apiHandler;
apiHandler = exchange -> {
String path = exchange.getRelativePath().substring(API_PATH.length());
Matcher realmSubMatcher = PATTERN_REALM_SUB.matcher(path);
if (!realmSubMatcher.matches()) {
exchange.setStatusCode(NOT_FOUND.getStatusCode());
throw new WebApplicationException(NOT_FOUND);
}
// Extract realm from path and push it into REQUEST_HEADER_REALM header
String realm = realmSubMatcher.group(1);
// Move the realm from path segment to header
exchange.getRequestHeaders().put(HttpString.tryFromString(REALM_PARAM_NAME), realm);
URI url = fromUri(exchange.getRequestURL()).replacePath(realmSubMatcher.group(2)).build();
exchange.setRequestURI(url.toString(), true);
exchange.setRequestPath(url.getPath());
exchange.setRelativePath(url.getPath());
baseApiHandler.handleRequest(exchange);
};
}
// Serve deployment files unsecured (explicitly map deployment folders to request paths)
builtInAppDocRoot = Paths.get(getString(container.getConfig(), APP_DOCROOT, APP_DOCROOT_DEFAULT));
customAppDocRoot = Paths.get(getString(container.getConfig(), CUSTOM_APP_DOCROOT, CUSTOM_APP_DOCROOT_DEFAULT));
HttpHandler defaultHandler = null;
if (Files.isDirectory(customAppDocRoot)) {
HttpHandler customBaseFileHandler = createFileHandler(container, customAppDocRoot, null);
defaultHandler = exchange -> {
if (exchange.getRelativePath().isEmpty() || "/".equals(exchange.getRelativePath())) {
exchange.setRelativePath("/index.html");
}
customBaseFileHandler.handleRequest(exchange);
};
}
PathHandler deploymentHandler = defaultHandler != null ? new PathHandler(defaultHandler) : new PathHandler();
// Serve deployment files
if (Files.isDirectory(builtInAppDocRoot)) {
HttpHandler appBaseFileHandler = createFileHandler(container, builtInAppDocRoot, null);
HttpHandler appFileHandler = exchange -> {
if (exchange.getRelativePath().isEmpty() || "/".equals(exchange.getRelativePath())) {
exchange.setRelativePath("/index.html");
}
// Reinstate the full path
exchange.setRelativePath(exchange.getRequestPath());
appBaseFileHandler.handleRequest(exchange);
};
deploymentHandler.addPrefixPath(MANAGER_APP_PATH, appFileHandler);
deploymentHandler.addPrefixPath(SWAGGER_APP_PATH, appFileHandler);
deploymentHandler.addPrefixPath(CONSOLE_LOADER_APP_PATH, appFileHandler);
deploymentHandler.addPrefixPath(SHARED_PATH, appFileHandler);
}
// Redirect / to default app
if (rootRedirectPath != null) {
getRequestHandlers().add(new RequestHandler("Default app redirect", exchange -> exchange.getRequestPath().equals("/"), exchange -> {
LOG.finer("Handling root request, redirecting client to default app");
new RedirectHandler(redirect(exchange, rootRedirectPath)).handleRequest(exchange);
}));
}
if (apiHandler != null) {
getRequestHandlers().add(pathStartsWithHandler("REST API Handler", API_PATH, apiHandler));
}
// This will try and handle any request that makes it to this handler
getRequestHandlers().add(new RequestHandler("Deployment files", exchange -> true, deploymentHandler));
}
use of io.swagger.v3.oas.models.security.SecurityRequirement in project swagger-parser by swagger-api.
the class OpenAPIDeserializerTest method testSecurity.
@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"));
}
use of io.swagger.v3.oas.models.security.SecurityRequirement in project swagger-parser by swagger-api.
the class OpenAPIDeserializerTest method readSecurityRequirementsObject.
@Test(dataProvider = "data")
public void readSecurityRequirementsObject(JsonNode rootNode) throws Exception {
final OpenAPIDeserializer deserializer = new OpenAPIDeserializer();
final SwaggerParseResult result = deserializer.deserialize(rootNode);
Assert.assertNotNull(result);
final OpenAPI openAPI = result.getOpenAPI();
Assert.assertNotNull(openAPI);
final List<SecurityRequirement> requirements = openAPI.getSecurity();
Assert.assertNotNull(requirements);
Assert.assertEquals(requirements.size(), 2);
SecurityRequirement requirement = requirements.get(0);
assertTrue(requirement.containsKey("api_key"));
requirement = requirements.get(1);
assertTrue(requirement.containsKey("tokenAuth"));
}
Aggregations