use of org.wso2.carbon.apimgt.impl.RESTAPICacheConfiguration in project carbon-apimgt by wso2.
the class OASYamlApi method oasYamlGet.
/**
* Retrieves swagger definition of Service Catalog REST API and returns
*
* @return swagger definition of Service Catalog REST API in yaml format
*/
@GET
@Consumes({ "text/yaml" })
@Produces({ "text/yaml" })
@io.swagger.annotations.ApiOperation(value = "Get OpenAPI Definition", notes = "Get OpenAPI Definition of Service Catalog REST API.", response = Void.class)
@io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nOpenAPI Definition is returned."), @io.swagger.annotations.ApiResponse(code = 304, message = "Not Modified.\nEmpty body because the client has already the latest version of the requested resource."), @io.swagger.annotations.ApiResponse(code = 406, message = "Not Acceptable.\nThe requested media type is not supported") })
public Response oasYamlGet() throws APIManagementException {
try {
if (openAPIDef == null) {
synchronized (LOCK_SERVICE_CATALOG_OPENAPI_DEF) {
if (openAPIDef == null) {
String definition = IOUtils.toString(this.getClass().getResourceAsStream("/service-catalog-api.yaml"), "UTF-8");
openAPIDef = new OAS3Parser().removeExamplesFromOpenAPI(definition);
}
}
}
RESTAPICacheConfiguration restapiCacheConfiguration = APIUtil.getRESTAPICacheConfig();
if (restapiCacheConfiguration.isCacheControlHeadersEnabled()) {
CacheControl cacheControl = new CacheControl();
cacheControl.setMaxAge(restapiCacheConfiguration.getCacheControlHeadersMaxAge());
cacheControl.setPrivate(true);
return Response.ok().entity(openAPIDef).cacheControl(cacheControl).build();
} else {
return Response.ok().entity(openAPIDef).build();
}
} catch (IOException e) {
String errorMessage = "Error while retrieving the OAS of the Service Catalog API";
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.impl.RESTAPICacheConfiguration in project carbon-apimgt by wso2.
the class OAuthOpaqueAuthenticatorImpl method authenticate.
/**
* @param message cxf message to be authenticated
* @return true if authentication was successful else false
* @throws APIManagementException when error in authentication process
*/
@Override
public boolean authenticate(Message message) throws APIManagementException {
boolean retrievedFromInvalidTokenCache = false;
boolean retrievedFromTokenCache = false;
String accessToken = RestApiUtil.extractOAuthAccessTokenFromMessage(message, RestApiConstants.REGEX_BEARER_PATTERN, RestApiConstants.AUTH_HEADER_NAME);
OAuthTokenInfo tokenInfo = null;
RESTAPICacheConfiguration cacheConfiguration = APIUtil.getRESTAPICacheConfig();
// validate the token from cache if it is enabled
if (cacheConfiguration.isTokenCacheEnabled()) {
tokenInfo = (OAuthTokenInfo) getRESTAPITokenCache().get(accessToken);
if (tokenInfo != null) {
if (isAccessTokenExpired(tokenInfo)) {
tokenInfo.setTokenValid(false);
// remove the token from token cache and put the token into invalid token cache
// when the access token is expired
getRESTAPIInvalidTokenCache().put(accessToken, tokenInfo);
getRESTAPITokenCache().remove(accessToken);
log.error(RestApiConstants.ERROR_TOKEN_EXPIRED);
return false;
} else {
retrievedFromTokenCache = true;
}
} else {
// if the token doesn't exist in the valid token cache, then check it in the invalid token cache
tokenInfo = (OAuthTokenInfo) getRESTAPIInvalidTokenCache().get(accessToken);
if (tokenInfo != null) {
retrievedFromInvalidTokenCache = true;
}
}
}
// if the tokenInfo is null, then only retrieve the token information from the database
try {
if (tokenInfo == null) {
tokenInfo = getTokenMetaData(accessToken);
}
} catch (APIManagementException e) {
log.error("Error while retrieving token information for token: " + accessToken, e);
}
// if we got valid access token we will proceed with next
if (tokenInfo != null && tokenInfo.isTokenValid()) {
if (cacheConfiguration.isTokenCacheEnabled() && !retrievedFromTokenCache) {
// put the token info into token cache
getRESTAPITokenCache().put(accessToken, tokenInfo);
}
// If access token is valid then we will perform scope check for given resource.
if (validateScopes(message, tokenInfo)) {
// Add the user scopes list extracted from token to the cxf message
message.getExchange().put(RestApiConstants.USER_REST_API_SCOPES, tokenInfo.getScopes());
// If scope validation successful then set tenant name and user name to current context
String tenantDomain = MultitenantUtils.getTenantDomain(tokenInfo.getEndUserName());
int tenantId;
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class, null);
try {
String username = tokenInfo.getEndUserName();
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
// when the username is an email in supertenant, it has at least 2 occurrences of '@'
long count = username.chars().filter(ch -> ch == '@').count();
// in the case of email, there will be more than one '@'
boolean isEmailUsernameEnabled = Boolean.parseBoolean(CarbonUtils.getServerConfiguration().getFirstProperty("EnableEmailUserName"));
if (isEmailUsernameEnabled || (username.endsWith(SUPER_TENANT_SUFFIX) && count <= 1)) {
username = MultitenantUtils.getTenantAwareUsername(username);
}
}
if (log.isDebugEnabled()) {
log.debug("username = " + username);
}
tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
carbonContext.setTenantDomain(tenantDomain);
carbonContext.setTenantId(tenantId);
carbonContext.setUsername(username);
message.put(RestApiConstants.SUB_ORGANIZATION, tenantDomain);
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
APIUtil.loadTenantConfigBlockingMode(tenantDomain);
}
return true;
} catch (UserStoreException e) {
log.error("Error while retrieving tenant id for tenant domain: " + tenantDomain, e);
}
} else {
log.error(RestApiConstants.ERROR_SCOPE_VALIDATION_FAILED);
}
} else {
log.error(RestApiConstants.ERROR_TOKEN_INVALID);
if (cacheConfiguration.isTokenCacheEnabled() && !retrievedFromInvalidTokenCache) {
getRESTAPIInvalidTokenCache().put(accessToken, tokenInfo);
}
}
return false;
}
use of org.wso2.carbon.apimgt.impl.RESTAPICacheConfiguration in project carbon-apimgt by wso2.
the class SwaggerYamlApi method swaggerYamlGet.
/**
* Retrieves swagger definition of Publisher REST API and returns
*
* @return swagger definition of Publisher REST API in yaml format
*/
@GET
@Consumes({ "text/yaml" })
@Produces({ "text/yaml" })
@io.swagger.annotations.ApiOperation(value = "Get Swagger Definition", notes = "Get Swagger Definition of Publisher REST API.", response = Void.class)
@io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nSwagger Definition is returned."), @io.swagger.annotations.ApiResponse(code = 304, message = "Not Modified.\nEmpty body because the client has already the latest version of the requested resource."), @io.swagger.annotations.ApiResponse(code = 406, message = "Not Acceptable.\nThe requested media type is not supported") })
public Response swaggerYamlGet() throws APIManagementException {
try {
if (openAPIDef == null) {
synchronized (LOCK_PUBLISHER_OPENAPI_DEF) {
if (openAPIDef == null) {
String definition = IOUtils.toString(this.getClass().getResourceAsStream("/publisher-api.yaml"), "UTF-8");
openAPIDef = new OAS3Parser().removeExamplesFromOpenAPI(definition);
}
}
}
RESTAPICacheConfiguration restapiCacheConfiguration = APIUtil.getRESTAPICacheConfig();
if (restapiCacheConfiguration.isCacheControlHeadersEnabled()) {
CacheControl cacheControl = new CacheControl();
cacheControl.setMaxAge(restapiCacheConfiguration.getCacheControlHeadersMaxAge());
cacheControl.setPrivate(true);
return Response.ok().entity(openAPIDef).cacheControl(cacheControl).build();
} else {
return Response.ok().entity(openAPIDef).build();
}
} catch (IOException e) {
String errorMessage = "Error while retrieving the OAS of the Publisher API";
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.impl.RESTAPICacheConfiguration in project carbon-apimgt by wso2.
the class SwaggerYamlApi method swaggerYamlGet.
/**
* Retrieves OAS of Developer Portal REST API and returns
*
* @return OAS of Developer Portal REST API in yaml format
*/
@GET
@Consumes({ "text/yaml" })
@Produces({ "text/yaml" })
@io.swagger.annotations.ApiOperation(value = "Get OAS Definition", notes = "Get OAS of Developer Portal REST API.", response = Void.class)
@io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nOAS Definition is returned."), @io.swagger.annotations.ApiResponse(code = 304, message = "Not Modified.\nEmpty body because the client has already the latest version of the requested resource."), @io.swagger.annotations.ApiResponse(code = 406, message = "Not Acceptable.\nThe requested media type is not supported") })
public Response swaggerYamlGet() throws APIManagementException {
try {
if (openAPIDef == null) {
synchronized (LOCK_STORE_OPENAPI_DEF) {
if (openAPIDef == null) {
String definition = IOUtils.toString(this.getClass().getResourceAsStream("/devportal-api.yaml"), "UTF-8");
openAPIDef = new OAS3Parser().removeExamplesFromOpenAPI(definition);
}
}
}
RESTAPICacheConfiguration restapiCacheConfiguration = APIUtil.getRESTAPICacheConfig();
if (restapiCacheConfiguration.isCacheControlHeadersEnabled()) {
CacheControl cacheControl = new CacheControl();
cacheControl.setMaxAge(restapiCacheConfiguration.getCacheControlHeadersMaxAge());
cacheControl.setPrivate(true);
return Response.ok().entity(openAPIDef).cacheControl(cacheControl).build();
} else {
return Response.ok().entity(openAPIDef).build();
}
} catch (IOException e) {
String errorMessage = "Error while retrieving the OAS of the Developer Portal API";
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.impl.RESTAPICacheConfiguration in project carbon-apimgt by wso2.
the class OAuthJwtAuthenticatorImpl method authenticate.
/**
* @param message cxf message to be authenticated
* @return true if authentication was successful else false
*/
@Override
public boolean authenticate(Message message) throws APIManagementException {
RESTAPICacheConfiguration cacheConfiguration = APIUtil.getRESTAPICacheConfig();
isRESTApiTokenCacheEnabled = cacheConfiguration.isTokenCacheEnabled();
String accessToken = RestApiUtil.extractOAuthAccessTokenFromMessage(message, RestApiConstants.REGEX_BEARER_PATTERN, RestApiConstants.AUTH_HEADER_NAME);
if (StringUtils.countMatches(accessToken, APIConstants.DOT) != 2) {
log.error("Invalid JWT token. The expected token format is <header.payload.signature>");
return false;
}
try {
SignedJWTInfo signedJWTInfo = getSignedJwt(accessToken);
String jwtTokenIdentifier = getJWTTokenIdentifier(signedJWTInfo);
String maskedToken = message.get(RestApiConstants.MASKED_TOKEN).toString();
URL basePath = new URL(message.get(APIConstants.BASE_PATH).toString());
// Validate token
log.debug("Starting JWT token validation " + maskedToken);
JWTValidationInfo jwtValidationInfo = validateJWTToken(signedJWTInfo, jwtTokenIdentifier, accessToken, maskedToken, basePath);
if (jwtValidationInfo != null) {
if (jwtValidationInfo.isValid()) {
if (isRESTApiTokenCacheEnabled) {
getRESTAPITokenCache().put(jwtTokenIdentifier, jwtValidationInfo);
}
// Validating scopes
return handleScopeValidation(message, signedJWTInfo, accessToken);
} else {
log.error("Invalid JWT token :" + maskedToken);
return false;
}
} else {
log.error("Invalid JWT token :" + maskedToken);
return false;
}
} catch (ParseException e) {
log.error("Not a JWT token. Failed to decode the token. Reason: " + e.getMessage());
} catch (MalformedURLException e) {
log.error("Malformed URL found in request path.Reason: " + e.getMessage());
}
return false;
}
Aggregations