use of org.wso2.carbon.apimgt.core.api.APIDefinition in project carbon-apimgt by wso2.
the class OAuth2Authenticator method validateScopes.
/*
* This method validates the given scope against scopes defined in the api resource
* @param Request
* @param ServiceMethodInfo
* @param scopesToValidate scopes extracted from the access token
* @return true if scope validation successful
* */
@SuppressFBWarnings({ "DLS_DEAD_LOCAL_STORE" })
private boolean validateScopes(Request request, ServiceMethodInfo serviceMethodInfo, String scopesToValidate, String restAPIResource) throws APIMgtSecurityException {
final boolean[] authorized = { false };
String path = (String) request.getProperty(APIConstants.REQUEST_URL);
String verb = (String) request.getProperty(APIConstants.HTTP_METHOD);
if (log.isDebugEnabled()) {
log.debug("Invoking rest api resource path " + verb + " " + path + " ");
log.debug("LoggedIn user scopes " + scopesToValidate);
}
String[] scopesArr = new String[0];
if (scopesToValidate != null) {
scopesArr = scopesToValidate.split(" ");
}
if (scopesToValidate != null && scopesArr.length > 0) {
final List<String> scopes = Arrays.asList(scopesArr);
if (restAPIResource != null) {
APIDefinition apiDefinition = new APIDefinitionFromSwagger20();
try {
String apiResourceDefinitionScopes = apiDefinition.getScopeOfResourcePath(restAPIResource, request, serviceMethodInfo);
if (StringUtils.isEmpty(apiResourceDefinitionScopes)) {
if (log.isDebugEnabled()) {
log.debug("Scope not defined in swagger for matching resource " + path + " and verb " + verb + " . Hence consider as anonymous permission and let request to continue.");
}
// scope validation gets through if no scopes found in the api definition
authorized[0] = true;
} else {
Arrays.stream(apiResourceDefinitionScopes.split(" ")).forEach(scopeKey -> {
Optional<String> key = scopes.stream().filter(scp -> {
return scp.equalsIgnoreCase(scopeKey);
}).findAny();
if (key.isPresent()) {
// scope validation success if one of the
authorized[0] = true;
// apiResourceDefinitionScopes found.
}
});
}
} catch (APIManagementException e) {
String message = "Error while validating scopes";
log.error(message, e);
throw new APIMgtSecurityException(message, ExceptionCodes.INVALID_SCOPE);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Rest API resource could not be found for request path '" + path + "'");
}
}
} else {
// scope validation gets through if access token does not contain scopes to validate
authorized[0] = true;
}
if (!authorized[0]) {
String message = "Scope validation fails for the scopes " + scopesToValidate;
throw new APIMgtSecurityException(message, ExceptionCodes.INVALID_SCOPE);
}
return authorized[0];
}
use of org.wso2.carbon.apimgt.core.api.APIDefinition in project carbon-apimgt by wso2.
the class CompositeApisApiServiceImpl method compositeApisApiIdSwaggerPut.
/**
* Updates the swagger defnition of an API
*
* @param apiId UUID of API
* @param apiDefinition updated swagger defintion
* @param ifMatch If-Match header value
* @param ifUnmodifiedSince If-Unmodified-Since header value
* @param request msf4j request object
* @return Updated swagger definition
* @throws NotFoundException When the particular resource does not exist in the system
*/
@Override
public Response compositeApisApiIdSwaggerPut(String apiId, String apiDefinition, String ifMatch, String ifUnmodifiedSince, Request request) throws NotFoundException {
String username = RestApiUtil.getLoggedInUsername(request);
try {
APIStore apiStore = RestApiUtil.getConsumer(username);
String existingFingerprint = compositeApisApiIdSwaggerGetFingerprint(apiId, null, null, request);
if (!StringUtils.isEmpty(ifMatch) && !StringUtils.isEmpty(existingFingerprint) && !ifMatch.contains(existingFingerprint)) {
return Response.status(Response.Status.PRECONDITION_FAILED).build();
}
apiStore.updateCompositeApiDefinition(apiId, apiDefinition);
String apiSwagger = apiStore.getCompositeApiDefinition(apiId);
String newFingerprint = compositeApisApiIdSwaggerGetFingerprint(apiId, null, null, request);
return Response.ok().header(HttpHeaders.ETAG, "\"" + newFingerprint + "\"").entity(apiSwagger).build();
} catch (APIManagementException e) {
HashMap<String, String> paramList = new HashMap<String, String>();
paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
}
}
use of org.wso2.carbon.apimgt.core.api.APIDefinition in project carbon-apimgt by wso2.
the class SampleTestObjectCreator method createDefaultAPI.
public static API.APIBuilder createDefaultAPI() {
Set<String> transport = new HashSet<>();
transport.add(HTTP);
transport.add(HTTPS);
Set<String> tags = new HashSet<>();
tags.add(TAG_CLIMATE);
Set<Policy> policies = new HashSet<>();
policies.add(goldSubscriptionPolicy);
policies.add(silverSubscriptionPolicy);
policies.add(bronzeSubscriptionPolicy);
BusinessInformation businessInformation = new BusinessInformation();
businessInformation.setBusinessOwner(NAME_BUSINESS_OWNER_1);
businessInformation.setBusinessOwnerEmail(EMAIL_BUSINESS_OWNER_1);
businessInformation.setTechnicalOwner(NAME_TECHNICAL_OWNER_1);
businessInformation.setTechnicalOwnerEmail(EMAIL_TECHNICAL_OWNER_1);
String permissionJson = "[{\"groupId\" : \"developer\", \"permission\" : " + "[\"READ\",\"UPDATE\"]},{\"groupId\" : \"admin\", \"permission\" : [\"READ\",\"UPDATE\"," + "\"DELETE\", \"MANAGE_SUBSCRIPTION\"]}]";
Set<String> visibleRoles = new HashSet<>();
visibleRoles.add("testRple");
List<String> labels = new ArrayList<>();
labels.add("testLabel");
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setEnabled(true);
corsConfiguration.setAllowMethods(Arrays.asList(APIMgtConstants.FunctionsConstants.GET, APIMgtConstants.FunctionsConstants.POST, APIMgtConstants.FunctionsConstants.DELETE));
corsConfiguration.setAllowHeaders(Arrays.asList(ALLOWED_HEADER_AUTHORIZATION, ALLOWED_HEADER_CUSTOM));
corsConfiguration.setAllowCredentials(true);
corsConfiguration.setAllowOrigins(Arrays.asList("*"));
Map<String, Endpoint> endpointMap = new HashMap<>();
endpointMap.put("TestEndpoint", createMockEndpoint());
API.APIBuilder apiBuilder = new API.APIBuilder(ADMIN, "WeatherAPI", API_VERSION).id(UUID.randomUUID().toString()).context("weather").description("Get Weather Info").lifeCycleStatus(APIStatus.CREATED.getStatus()).lifecycleInstanceId(UUID.randomUUID().toString()).endpoint(Collections.emptyMap()).wsdlUri("http://localhost:9443/echo?wsdl").isResponseCachingEnabled(false).cacheTimeout(60).isDefaultVersion(false).apiPolicy(unlimitedApiPolicy).transport(transport).tags(tags).policies(policies).visibility(API.Visibility.PUBLIC).visibleRoles(visibleRoles).businessInformation(businessInformation).corsConfiguration(corsConfiguration).createdTime(LocalDateTime.now()).createdBy(ADMIN).updatedBy(ADMIN).lastUpdatedTime(LocalDateTime.now()).apiPermission(permissionJson).uriTemplates(getMockUriTemplates()).apiDefinition(apiDefinition).workflowStatus(WORKFLOW_STATUS).labels(labels).endpoint(endpointMap);
Map map = new HashMap();
map.put(DEVELOPER_ROLE_ID, 6);
map.put(ADMIN_ROLE_ID, 15);
apiBuilder.permissionMap(map);
return apiBuilder;
}
use of org.wso2.carbon.apimgt.core.api.APIDefinition in project carbon-apimgt by wso2.
the class APIDefinitionFromSwagger20 method generateApiFromSwaggerResource.
/**
* return API Object
*
* @param provider Provider of the API.
* @param apiDefinition API definition as string
* @return API object.
* @throws APIManagementException If failed to generate API from swagger.
*/
@Override
public API.APIBuilder generateApiFromSwaggerResource(String provider, String apiDefinition) throws APIManagementException {
SwaggerParser swaggerParser = new SwaggerParser();
Swagger swagger = swaggerParser.parse(apiDefinition);
if (swagger == null) {
throw new APIManagementException("Swagger could not be generated from provided API definition");
}
Info apiInfo = swagger.getInfo();
if (apiInfo == null) {
throw new APIManagementException("Swagger doesn't contains the info");
} else {
String apiName = apiInfo.getTitle();
String apiVersion = apiInfo.getVersion();
String apiDescription = apiInfo.getDescription();
Contact contact = apiInfo.getContact();
BusinessInformation businessInformation = new BusinessInformation();
if (contact != null) {
businessInformation.setBusinessOwner(contact.getName());
businessInformation.setBusinessOwnerEmail(contact.getEmail());
}
API.APIBuilder apiBuilder = new API.APIBuilder(provider, apiName, apiVersion);
apiBuilder.businessInformation(businessInformation);
apiBuilder.description(apiDescription);
apiBuilder.context(swagger.getBasePath());
List<APIResource> apiResourceList = parseSwaggerAPIResources(new StringBuilder(apiDefinition));
Map<String, UriTemplate> uriTemplateMap = new HashMap();
for (APIResource apiResource : apiResourceList) {
uriTemplateMap.put(apiResource.getUriTemplate().getTemplateId(), apiResource.getUriTemplate());
}
apiBuilder.uriTemplates(uriTemplateMap);
apiBuilder.id(UUID.randomUUID().toString());
return apiBuilder;
}
}
use of org.wso2.carbon.apimgt.core.api.APIDefinition in project carbon-apimgt by wso2.
the class SampleTestObjectCreator method createDefaultAPI.
public static API.APIBuilder createDefaultAPI() {
Set<String> transport = new HashSet<>();
transport.add(HTTP);
transport.add(HTTPS);
Set<String> tags = new HashSet<>();
tags.add(TAG_CLIMATE);
Set<Policy> policies = new HashSet<>();
policies.add(goldSubscriptionPolicy);
policies.add(silverSubscriptionPolicy);
policies.add(bronzeSubscriptionPolicy);
BusinessInformation businessInformation = new BusinessInformation();
CorsConfiguration corsConfiguration = new CorsConfiguration();
String permissionJson = "[{\"groupId\" : \"developer\", \"permission\" : " + "[\"READ\",\"UPDATE\"]},{\"groupId\" : \"admin\", \"permission\" : [\"READ\",\"UPDATE\"," + "\"DELETE\", \"MANAGE_SUBSCRIPTION\"]}]";
List<String> defaultLabels = getDefaultLabels();
API.APIBuilder apiBuilder = new API.APIBuilder(ADMIN, "WeatherAPI", API_VERSION).id(UUID.randomUUID().toString()).context("weather").description("Get Weather Info").lifeCycleStatus(APIStatus.CREATED.getStatus()).lifecycleInstanceId(UUID.randomUUID().toString()).endpoint(Collections.emptyMap()).isResponseCachingEnabled(false).cacheTimeout(60).isDefaultVersion(false).apiPolicy(unlimitedApiPolicy).transport(transport).tags(tags).labels(defaultLabels).policies(policies).visibility(API.Visibility.PUBLIC).visibleRoles(new HashSet<>()).businessInformation(businessInformation).corsConfiguration(corsConfiguration).createdTime(LocalDateTime.now()).createdBy(ADMIN).updatedBy(ADMIN).lastUpdatedTime(LocalDateTime.now()).apiPermission(permissionJson).uriTemplates(getMockUriTemplates()).apiDefinition(apiDefinition).securityScheme(3).threatProtectionPolicies(threatProtectionPolicies);
Map map = new HashMap();
map.put(DEVELOPER_ROLE_ID, 6);
map.put(ADMIN_ROLE_ID, 15);
apiBuilder.permissionMap(map);
return apiBuilder;
}
Aggregations