Search in sources :

Example 1 with RESTAPICacheConfiguration

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;
}
Also used : OAS3Parser(org.wso2.carbon.apimgt.impl.definitions.OAS3Parser) RESTAPICacheConfiguration(org.wso2.carbon.apimgt.impl.RESTAPICacheConfiguration) CacheControl(javax.ws.rs.core.CacheControl) IOException(java.io.IOException) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 2 with RESTAPICacheConfiguration

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;
}
Also used : RESTAPICacheConfiguration(org.wso2.carbon.apimgt.impl.RESTAPICacheConfiguration) MultitenantConstants(org.wso2.carbon.utils.multitenancy.MultitenantConstants) Message(org.apache.cxf.message.Message) APIUtil(org.wso2.carbon.apimgt.impl.utils.APIUtil) UserStoreException(org.wso2.carbon.user.api.UserStoreException) OAuth2TokenValidationRequestDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO) AbstractOAuthAuthenticator(org.wso2.carbon.apimgt.rest.api.util.authenticators.AbstractOAuthAuthenticator) MethodStats(org.wso2.carbon.apimgt.rest.api.util.MethodStats) RestApiUtil(org.wso2.carbon.apimgt.rest.api.util.utils.RestApiUtil) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) RealmService(org.wso2.carbon.user.core.service.RealmService) APIConstants(org.wso2.carbon.apimgt.impl.APIConstants) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) OAuth2TokenValidationService(org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService) OAuth2ClientApplicationDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2ClientApplicationDTO) CarbonUtils(org.wso2.carbon.utils.CarbonUtils) MultitenantUtils(org.wso2.carbon.utils.multitenancy.MultitenantUtils) RestApiConstants(org.wso2.carbon.apimgt.rest.api.common.RestApiConstants) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthTokenInfo(org.wso2.carbon.apimgt.api.OAuthTokenInfo) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) OAuth2TokenValidationResponseDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreException(org.wso2.carbon.user.api.UserStoreException) OAuthTokenInfo(org.wso2.carbon.apimgt.api.OAuthTokenInfo) RESTAPICacheConfiguration(org.wso2.carbon.apimgt.impl.RESTAPICacheConfiguration) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext)

Example 3 with RESTAPICacheConfiguration

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;
}
Also used : OAS3Parser(org.wso2.carbon.apimgt.impl.definitions.OAS3Parser) RESTAPICacheConfiguration(org.wso2.carbon.apimgt.impl.RESTAPICacheConfiguration) CacheControl(javax.ws.rs.core.CacheControl) IOException(java.io.IOException) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 4 with RESTAPICacheConfiguration

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;
}
Also used : OAS3Parser(org.wso2.carbon.apimgt.impl.definitions.OAS3Parser) RESTAPICacheConfiguration(org.wso2.carbon.apimgt.impl.RESTAPICacheConfiguration) CacheControl(javax.ws.rs.core.CacheControl) IOException(java.io.IOException) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 5 with RESTAPICacheConfiguration

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;
}
Also used : MalformedURLException(java.net.MalformedURLException) RESTAPICacheConfiguration(org.wso2.carbon.apimgt.impl.RESTAPICacheConfiguration) ParseException(java.text.ParseException) SignedJWTInfo(org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo) URL(java.net.URL) JWTValidationInfo(org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo)

Aggregations

RESTAPICacheConfiguration (org.wso2.carbon.apimgt.impl.RESTAPICacheConfiguration)5 IOException (java.io.IOException)3 Consumes (javax.ws.rs.Consumes)3 GET (javax.ws.rs.GET)3 Produces (javax.ws.rs.Produces)3 CacheControl (javax.ws.rs.core.CacheControl)3 OAS3Parser (org.wso2.carbon.apimgt.impl.definitions.OAS3Parser)3 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 ParseException (java.text.ParseException)1 Log (org.apache.commons.logging.Log)1 LogFactory (org.apache.commons.logging.LogFactory)1 Message (org.apache.cxf.message.Message)1 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)1 OAuthTokenInfo (org.wso2.carbon.apimgt.api.OAuthTokenInfo)1 JWTValidationInfo (org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo)1 APIConstants (org.wso2.carbon.apimgt.impl.APIConstants)1 APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)1 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)1 SignedJWTInfo (org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo)1