use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project product-apim by wso2.
the class ApiClient method setCredentials.
/**
* Helper method to configure the username/password for basic auth or password OAuth
*
* @param username Username
* @param password Password
*/
public void setCredentials(String username, String password) {
for (RequestInterceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof HttpBasicAuth) {
HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization;
basicAuth.setCredentials(username, password);
return;
}
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.getTokenRequestBuilder().setUsername(username).setPassword(password);
return;
}
}
throw new RuntimeException("No Basic authentication or OAuth configured!");
}
use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.
the class OAuthTokenGenerator method generateToken.
/**
* Method to check for and refresh expired/generate new access tokens
*
* @param oAuthEndpoint OAuthEndpoint object for token endpoint properties
* @param latch CountDownLatch for blocking call when OAuth API is invoked
* @return TokenResponse object
* @throws APISecurityException In the event of errors when generating new token
*/
public static TokenResponse generateToken(OAuthEndpoint oAuthEndpoint, CountDownLatch latch) throws APISecurityException {
try {
TokenResponse tokenResponse = null;
if (ServiceReferenceHolder.getInstance().isRedisEnabled()) {
Object previousResponseObject = new RedisCacheUtils(ServiceReferenceHolder.getInstance().getRedisPool()).getObject(oAuthEndpoint.getId(), TokenResponse.class);
if (previousResponseObject != null) {
tokenResponse = (TokenResponse) previousResponseObject;
}
} else {
tokenResponse = TokenCache.getInstance().getTokenMap().get(oAuthEndpoint.getId());
}
if (tokenResponse != null) {
long validTill = tokenResponse.getValidTill();
long currentTimeInSeconds = System.currentTimeMillis() / 1000;
long timeDifference = validTill - currentTimeInSeconds;
if (timeDifference <= 1) {
if (tokenResponse.getRefreshToken() != null) {
tokenResponse = addTokenToCache(oAuthEndpoint, tokenResponse.getRefreshToken());
} else {
tokenResponse = addTokenToCache(oAuthEndpoint, null);
}
}
} else {
tokenResponse = addTokenToCache(oAuthEndpoint, null);
}
return tokenResponse;
} catch (IOException e) {
log.error("Error while generating OAuth Token" + getEndpointId(oAuthEndpoint));
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE, e);
} catch (APIManagementException e) {
log.error("Could not retrieve OAuth Token" + getEndpointId(oAuthEndpoint));
throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, "Error while retrieving OAuth token", e);
} catch (ParseException e) {
log.error("Could not retrieve OAuth Token" + getEndpointId(oAuthEndpoint));
throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, "Error while parsing OAuth Token endpoint response", e);
} finally {
if (latch != null) {
latch.countDown();
}
}
}
use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.
the class APIConsumerImplTest method testTokenTypeChangeWhenUpdatingApplications.
@Test
public void testTokenTypeChangeWhenUpdatingApplications() throws APIManagementException {
Application oldApplication = new Application("app1", new Subscriber("sub1"));
oldApplication.setTier("tier1");
oldApplication.setOrganization("testorg");
Application newApplication = new Application("app1", new Subscriber("sub1"));
newApplication.setOrganization("testorg");
newApplication.setTier("tier2");
Mockito.when(apiMgtDAO.getApplicationById(Mockito.anyInt())).thenReturn(oldApplication);
Mockito.when(apiMgtDAO.getApplicationByUUID(Mockito.anyString())).thenReturn(oldApplication);
APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(apiMgtDAO);
Map<String, Tier> tierMap = new HashMap<>();
tierMap.put("tier1", new Tier("tier1"));
tierMap.put("tier2", new Tier("tier2"));
PowerMockito.when(APIUtil.getTiers(APIConstants.TIER_APPLICATION_TYPE, "testorg")).thenReturn(tierMap);
PowerMockito.when(APIUtil.findTier(tierMap.values(), "tier2")).thenReturn(new Tier("tier2"));
// When token type of existing application is 'JWT' and request body contains 'OAUTH' as the token type.
oldApplication.setTokenType(APIConstants.TOKEN_TYPE_JWT);
newApplication.setTokenType(APIConstants.TOKEN_TYPE_OAUTH);
try {
// An exception will be thrown during this operation.
apiConsumer.updateApplication(newApplication);
Assert.fail("API management exception not thrown for error scenario");
} catch (APIManagementException e) {
Assert.assertTrue(e.getMessage().contains("Cannot change application token type from " + APIConstants.TOKEN_TYPE_JWT + " to " + newApplication.getTokenType()));
}
// When token type of existing application is 'JWT' and request body contains 'JWT' as the token type.
oldApplication.setTokenType(APIConstants.TOKEN_TYPE_JWT);
newApplication.setTokenType(APIConstants.TOKEN_TYPE_JWT);
try {
// Token type of newApplication will not change during this operation.
apiConsumer.updateApplication(newApplication);
Assert.assertEquals(APIConstants.TOKEN_TYPE_JWT, newApplication.getTokenType());
} catch (APIManagementException e) {
Assert.fail("API management exception is thrown due to an error");
}
// When token type of existing application is 'OAUTH' and request body contains 'OAUTH' as the token type.
oldApplication.setTokenType(APIConstants.TOKEN_TYPE_OAUTH);
newApplication.setTokenType(APIConstants.TOKEN_TYPE_OAUTH);
try {
// Token type of newApplication will not change during this operation.
apiConsumer.updateApplication(newApplication);
Assert.assertEquals(APIConstants.TOKEN_TYPE_OAUTH, newApplication.getTokenType());
} catch (APIManagementException e) {
Assert.fail("API management exception is thrown due to an error");
}
// When token type of existing application is 'OAUTH' and request body contains 'JWT' as the token type.
oldApplication.setTokenType(APIConstants.TOKEN_TYPE_OAUTH);
newApplication.setTokenType(APIConstants.TOKEN_TYPE_JWT);
try {
// Token type of newApplication will not change during this operation.
apiConsumer.updateApplication(newApplication);
Assert.assertEquals(APIConstants.TOKEN_TYPE_JWT, newApplication.getTokenType());
} catch (APIManagementException e) {
Assert.fail("API management exception is thrown due to an error");
}
// When token type of existing application is 'DEFAULT' and request body contains 'OAUTH' as the token type.
oldApplication.setTokenType(APIConstants.DEFAULT_TOKEN_TYPE);
newApplication.setTokenType(APIConstants.TOKEN_TYPE_OAUTH);
try {
// Token type of newApplication will change to 'DEFAULT' during this operation.
apiConsumer.updateApplication(newApplication);
Assert.assertEquals(APIConstants.DEFAULT_TOKEN_TYPE, newApplication.getTokenType());
} catch (APIManagementException e) {
Assert.fail("API management exception is thrown due to an error");
}
// When token type of existing application is 'DEFAULT' and request body contains 'JWT' as the token type.
oldApplication.setTokenType(APIConstants.DEFAULT_TOKEN_TYPE);
newApplication.setTokenType(APIConstants.TOKEN_TYPE_JWT);
try {
// Token type of newApplication will not change during this operation.
apiConsumer.updateApplication(newApplication);
Assert.assertEquals(APIConstants.TOKEN_TYPE_JWT, newApplication.getTokenType());
} catch (APIManagementException e) {
Assert.fail("API management exception is thrown due to an error");
}
}
use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.
the class PublisherCommonUtils method addAPIWithGeneratedSwaggerDefinition.
/**
* Add API with the generated swagger from the DTO.
*
* @param apiDto API DTO of the API
* @param oasVersion Open API Definition version
* @param username Username
* @param organization Organization Identifier
* @return Created API object
* @throws APIManagementException Error while creating the API
* @throws CryptoException Error while encrypting
*/
public static API addAPIWithGeneratedSwaggerDefinition(APIDTO apiDto, String oasVersion, String username, String organization) throws APIManagementException, CryptoException {
if (APIUtil.isOnPremResolver()) {
String name = apiDto.getName();
// replace all white spaces in the API Name
apiDto.setName(name.replaceAll("\\s+", ""));
}
if (APIDTO.TypeEnum.ASYNC.equals(apiDto.getType())) {
throw new APIManagementException("ASYNC API type does not support API creation from scratch", ExceptionCodes.API_CREATION_NOT_SUPPORTED_FOR_ASYNC_TYPE_APIS);
}
boolean isWSAPI = APIDTO.TypeEnum.WS.equals(apiDto.getType());
boolean isAsyncAPI = isWSAPI || APIDTO.TypeEnum.WEBSUB.equals(apiDto.getType()) || APIDTO.TypeEnum.SSE.equals(apiDto.getType()) || APIDTO.TypeEnum.ASYNC.equals(apiDto.getType());
username = StringUtils.isEmpty(username) ? RestApiCommonUtil.getLoggedInUsername() : username;
APIProvider apiProvider = RestApiCommonUtil.getProvider(username);
// validate web socket api endpoint configurations
if (isWSAPI && !PublisherCommonUtils.isValidWSAPI(apiDto)) {
throw new APIManagementException("Endpoint URLs should be valid web socket URLs", ExceptionCodes.INVALID_ENDPOINT_URL);
}
// validate sandbox and production endpoints
if (!PublisherCommonUtils.validateEndpoints(apiDto)) {
throw new APIManagementException("Invalid/Malformed endpoint URL(s) detected", ExceptionCodes.INVALID_ENDPOINT_URL);
}
Map endpointConfig = (Map) apiDto.getEndpointConfig();
CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
// OAuth 2.0 backend protection: API Key and API Secret encryption
encryptEndpointSecurityOAuthCredentials(endpointConfig, cryptoUtil, StringUtils.EMPTY, StringUtils.EMPTY, apiDto);
// AWS Lambda: secret key encryption while creating the API
if (apiDto.getEndpointConfig() != null) {
if (endpointConfig.containsKey(APIConstants.AMZN_SECRET_KEY)) {
String secretKey = (String) endpointConfig.get(APIConstants.AMZN_SECRET_KEY);
if (!StringUtils.isEmpty(secretKey)) {
String encryptedSecretKey = cryptoUtil.encryptAndBase64Encode(secretKey.getBytes());
endpointConfig.put(APIConstants.AMZN_SECRET_KEY, encryptedSecretKey);
apiDto.setEndpointConfig(endpointConfig);
}
}
}
/* if (isWSAPI) {
ArrayList<String> websocketTransports = new ArrayList<>();
websocketTransports.add(APIConstants.WS_PROTOCOL);
websocketTransports.add(APIConstants.WSS_PROTOCOL);
apiDto.setTransport(websocketTransports);
}*/
API apiToAdd = prepareToCreateAPIByDTO(apiDto, apiProvider, username, organization);
validateScopes(apiToAdd);
// validate API categories
List<APICategory> apiCategories = apiToAdd.getApiCategories();
List<APICategory> apiCategoriesList = new ArrayList<>();
for (APICategory category : apiCategories) {
category.setOrganization(organization);
apiCategoriesList.add(category);
}
apiToAdd.setApiCategories(apiCategoriesList);
if (apiCategoriesList.size() > 0) {
if (!APIUtil.validateAPICategories(apiCategoriesList, organization)) {
throw new APIManagementException("Invalid API Category name(s) defined", ExceptionCodes.from(ExceptionCodes.API_CATEGORY_INVALID));
}
}
if (!isAsyncAPI) {
APIDefinition oasParser;
if (RestApiConstants.OAS_VERSION_2.equalsIgnoreCase(oasVersion)) {
oasParser = new OAS2Parser();
} else {
oasParser = new OAS3Parser();
}
SwaggerData swaggerData = new SwaggerData(apiToAdd);
String apiDefinition = oasParser.generateAPIDefinition(swaggerData);
apiToAdd.setSwaggerDefinition(apiDefinition);
} else {
AsyncApiParser asyncApiParser = new AsyncApiParser();
String asyncApiDefinition = asyncApiParser.generateAsyncAPIDefinition(apiToAdd);
apiToAdd.setAsyncApiDefinition(asyncApiDefinition);
}
apiToAdd.setOrganization(organization);
if (isAsyncAPI) {
AsyncApiParser asyncApiParser = new AsyncApiParser();
String apiDefinition = asyncApiParser.generateAsyncAPIDefinition(apiToAdd);
apiToAdd.setAsyncApiDefinition(apiDefinition);
}
// adding the api
apiProvider.addAPI(apiToAdd);
return apiToAdd;
}
use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.
the class SecurityConfigContextTest method testSecurityConfigContextOauth.
@Test
public void testSecurityConfigContextOauth() throws Exception {
String json = "{\"endpoint_security\":{\n" + " \"production\":{\n" + " \"enabled\":true,\n" + " \"type\":\"oauth\",\n" + " \"clientId\":\"123-456\",\n" + " \"clientSecret\":\"admin\",\n" + " \"grantType\":\"client_credentials\"\n" + " },\n" + " \"sandbox\":{\n" + " \"enabled\":true,\n" + " \"type\":\"oauth\",\n" + " \"clientId\":\"123-4567\",\n" + " \"clientSecret\":\"admin\",\n" + " \"grantType\":\"client_credentials\"\n" + " }\n" + " }\n" + "}";
API api = new API(new APIIdentifier("admin", "TestAPI", "1.0.0"));
api.setUuid(UUID.randomUUID().toString());
api.setStatus(APIConstants.CREATED);
api.setContextTemplate("/");
api.setTransports(Constants.TRANSPORT_HTTP);
api.setEndpointConfig(json);
ConfigContext configcontext = new APIConfigContext(api);
Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.API_SECUREVAULT_ENABLE)).thenReturn("true");
SecurityConfigContext securityConfigContext = new SecurityConfigContextWrapper(configcontext, api, apiManagerConfiguration);
securityConfigContext.validate();
VelocityContext velocityContext = securityConfigContext.getContext();
Assert.assertNotNull(velocityContext.get("endpoint_security"));
Map<String, EndpointSecurityModel> endpointSecurityModelMap = (Map<String, EndpointSecurityModel>) velocityContext.get("endpoint_security");
EndpointSecurityModel production = endpointSecurityModelMap.get("production");
Assert.assertTrue("Property enabled cannot be false.", production.isEnabled());
Assert.assertTrue("Property type cannot be other.", production.getType().equalsIgnoreCase("oauth"));
Assert.assertTrue("Property clientid does not match.", "123-456".equals(production.getClientId()));
Assert.assertEquals(production.getClientSecretAlias(), "TestAPI--v1.0.0--oauth--clientSecret--production");
EndpointSecurityModel sandbox = endpointSecurityModelMap.get("sandbox");
Assert.assertTrue("Property enabled cannot be false.", sandbox.isEnabled());
Assert.assertTrue("Property type cannot be other.", sandbox.getType().equalsIgnoreCase("oauth"));
Assert.assertTrue("Property username does not match.", "123-4567".equals(sandbox.getClientId()));
Assert.assertEquals(sandbox.getClientSecretAlias(), "TestAPI--v1.0.0--oauth--clientSecret--sandbox");
Assert.assertTrue("Property isSecureVaultEnabled cannot be false. ", velocityContext.get("isSecureVaultEnabled").equals(true));
}
Aggregations