use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.
the class WebsocketHandlerTestCase method testGraphQLWriteResponse.
@Test
public void testGraphQLWriteResponse() throws Exception {
InboundMessageContext inboundMessageContext = new InboundMessageContext();
inboundMessageContext.setElectedAPI(graphQLAPI);
InboundMessageContextDataHolder.getInstance().addInboundMessageContextForConnection(channelIdString, inboundMessageContext);
msg = new TextWebSocketFrame("{\"id\":\"1\",\"type\":\"start\",\"payload\":{\"variables\":{}," + "\"extensions\":{},\"operationName\":null," + "\"query\":\"subscription {\\n liftStatusChange {\\n id\\n name\\n }\\n}\\n\"}}");
VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
verbInfoDTO.setHttpVerb(GraphQLConstants.SubscriptionConstants.HTTP_METHOD_NAME);
verbInfoDTO.setAuthType("OAUTH");
GraphQLOperationDTO graphQLOperationDTO = new GraphQLOperationDTO(verbInfoDTO, "liftStatusChange");
inboundMessageContext.addVerbInfoForGraphQLMsgId("1", graphQLOperationDTO);
InboundProcessorResponseDTO responseDTO = new InboundProcessorResponseDTO();
PowerMockito.when(InboundWebsocketProcessorUtil.validateScopes(Mockito.anyObject(), Mockito.anyObject(), Mockito.anyObject())).thenReturn(responseDTO);
PowerMockito.when(InboundWebsocketProcessorUtil.doThrottleForGraphQL(Mockito.anyInt(), Mockito.anyObject(), Mockito.anyObject(), Mockito.anyObject())).thenReturn(responseDTO);
PowerMockito.when(InboundWebsocketProcessorUtil.authenticateToken(inboundMessageContext)).thenReturn(responseDTO);
// happy path
websocketHandler.write(channelHandlerContext, msg, channelPromise);
Assert.assertTrue((InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().containsKey(// No error has occurred context exists in data-holder map.
channelIdString)));
// close connection error
responseDTO.setError(true);
responseDTO.setCloseConnection(true);
websocketHandler.write(channelHandlerContext, msg, channelPromise);
Assert.assertFalse(InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().containsKey(// Closing connection error has occurred
channelIdString));
// Websocket frame error has occurred
InboundMessageContextDataHolder.getInstance().addInboundMessageContextForConnection(channelIdString, inboundMessageContext);
responseDTO.setError(true);
responseDTO.setCloseConnection(false);
websocketHandler.write(channelHandlerContext, msg, channelPromise);
Assert.assertTrue((InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().containsKey(channelIdString)));
}
use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.
the class OAS2Parser method getScopes.
/**
* This method returns the oauth scopes according to the given swagger
*
* @param resourceConfigsJSON resource json
* @return scope set
* @throws APIManagementException
*/
@Override
public Set<Scope> getScopes(String resourceConfigsJSON) throws APIManagementException {
Swagger swagger = getSwagger(resourceConfigsJSON);
String oauth2SchemeKey = getOAuth2SecuritySchemeKey(swagger);
Map<String, SecuritySchemeDefinition> securityDefinitions = swagger.getSecurityDefinitions();
OAuth2Definition oAuth2Definition;
if (securityDefinitions != null && (oAuth2Definition = (OAuth2Definition) securityDefinitions.get(oauth2SchemeKey)) != null && oAuth2Definition.getScopes() != null) {
Set<Scope> scopeSet = new LinkedHashSet<>();
for (Map.Entry<String, String> entry : oAuth2Definition.getScopes().entrySet()) {
Scope scope = new Scope();
scope.setKey(entry.getKey());
scope.setName(entry.getKey());
scope.setDescription(entry.getValue());
Map<String, String> scopeBindings;
if (oAuth2Definition.getVendorExtensions() != null && (scopeBindings = (Map<String, String>) oAuth2Definition.getVendorExtensions().get(APIConstants.SWAGGER_X_SCOPES_BINDINGS)) != null) {
if (scopeBindings.get(scope.getKey()) != null) {
scope.setRoles(scopeBindings.get(scope.getKey()));
}
}
scopeSet.add(scope);
}
return OASParserUtil.sortScopes(scopeSet);
} else {
return OASParserUtil.sortScopes(getScopesFromExtensions(swagger));
}
}
use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.
the class AbstractKeyManagerTestCase method buildFromJSONTest.
@Test
public void buildFromJSONTest() throws APIManagementException {
AbstractKeyManager keyManager = new AMDefaultKeyManagerImpl();
KeyManagerConnectorConfiguration keyManagerConnectorConfiguration = Mockito.mock(DefaultKeyManagerConnectorConfiguration.class);
ServiceReferenceHolder serviceReferenceHolder = PowerMockito.mock(ServiceReferenceHolder.class);
PowerMockito.mockStatic(ServiceReferenceHolder.class);
PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
Mockito.when(serviceReferenceHolder.getKeyManagerConnectorConfiguration(APIConstants.KeyManager.DEFAULT_KEY_MANAGER_TYPE)).thenReturn(keyManagerConnectorConfiguration);
// test with empty json payload
assertNotNull(keyManager.buildFromJSON(new OAuthApplicationInfo(), "{}"));
// test with valid json
String jsonPayload2 = "{ \"callbackUrl\": \"www.google.lk\", \"client_id\": \"XBPcXSfGK47WiEX7enchoP2Dcvga\"," + "\"client_secret\": \"4UD8VX8NaQMtrHCwqzI1tHJLPoca\", \"owner\": \"admin\", \"grantType\": \"password" + " refresh_token\", " + "\"validityPeriod\": \"3600\" }";
OAuthApplicationInfo oAuthApplicationInfo1 = keyManager.buildFromJSON(new OAuthApplicationInfo(), jsonPayload2);
assertEquals("XBPcXSfGK47WiEX7enchoP2Dcvga", oAuthApplicationInfo1.getClientId());
// test with invalid json
try {
keyManager.buildFromJSON(new OAuthApplicationInfo(), "{invalid}");
assertTrue(false);
} catch (APIManagementException e) {
assertEquals("Error occurred while parsing JSON String", e.getMessage());
}
// test with invalid additionalProperties
OAuthApplicationInfo applicationInfo = new OAuthApplicationInfo();
applicationInfo.addParameter("additionalProperties", "{invalid}");
try {
keyManager.buildFromJSON(applicationInfo, "{}");
fail();
} catch (APIManagementException e) {
assertEquals("Error while parsing the addition properties of OAuth application", e.getMessage());
}
}
use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.
the class OAuthTokenGeneratorTest method testOauthBackendSecurityWithPasswordGrant.
/**
* Test OAuth backend security with password grant type
*/
@Test
public void testOauthBackendSecurityWithPasswordGrant() throws ParseException, IOException, APIManagementException, APISecurityException {
// Assign values for test specific properties of mock token response and oAuthEndpoint object.
mockTokenResponse.setExpiresIn("1800");
long validTill = System.currentTimeMillis() / 1000 + Long.parseLong(mockTokenResponse.getExpiresIn());
mockTokenResponse.setValidTill(validTill);
mockTokenResponse.setRefreshToken("testRefreshToken");
oAuthEndpoint.setId("testID4");
oAuthEndpoint.setUsername("username");
oAuthEndpoint.setPassword("password".toCharArray());
oAuthEndpoint.setGrantType("PASSWORD");
// First token generation operation. Token endpoint will be called and the token response will be cached.
TokenResponse tokenResponse = OAuthTokenGenerator.generateToken(oAuthEndpoint, latch);
Assert.assertNotNull(tokenResponse);
Assert.assertNotNull(tokenCache.getTokenMap().get(oAuthEndpoint.getId()));
// Second token generation operation. Since the token response was cached, the token endpoint will not be
// called during this operation.
tokenResponse = OAuthTokenGenerator.generateToken(oAuthEndpoint, latch);
Assert.assertNotNull(tokenResponse);
// Token endpoint will be called only one time (during the first token generation operation).
PowerMockito.verifyStatic(OAuthClient.class, Mockito.times(1));
OAuthClient.generateToken(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.anyString(), Mockito.any(), Mockito.anyString());
Assert.assertNotNull(tokenCache.getTokenMap().get(oAuthEndpoint.getId()));
}
use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.
the class OAuthTokenGeneratorTest method testOauthBackendSecurityWithClientCredentialsGrantWhenTokenExpired.
/**
* Test OAuth backend security with client credentials grant type and when token is expired
*/
@Test
public void testOauthBackendSecurityWithClientCredentialsGrantWhenTokenExpired() throws ParseException, IOException, APIManagementException, APISecurityException {
// Assign values for test specific properties of mock token response and oAuthEndpoint object.
// expires_in value is subtracted to replicate the token expiry behaviour.
mockTokenResponse.setExpiresIn("1800");
long validTill = System.currentTimeMillis() / 1000 - Long.parseLong(mockTokenResponse.getExpiresIn());
mockTokenResponse.setValidTill(validTill);
mockTokenResponse.setRefreshToken(null);
oAuthEndpoint.setId("testID2");
oAuthEndpoint.setGrantType("CLIENT_CREDENTIALS");
// First token generation operation. Token endpoint will be called and the token response will be cached.
TokenResponse tokenResponse = OAuthTokenGenerator.generateToken(oAuthEndpoint, latch);
Assert.assertNotNull(tokenResponse);
Assert.assertNotNull(tokenCache.getTokenMap().get(oAuthEndpoint.getId()));
// Second token generation operation. Since the token is expired, the token endpoint will be called during
// this operation.
tokenResponse = OAuthTokenGenerator.generateToken(oAuthEndpoint, latch);
Assert.assertNotNull(tokenResponse);
// Third token generation operation (replicating the behaviour when the mock token response contains a refresh
// token).
mockTokenResponse.setRefreshToken("testRefreshToken");
tokenResponse = OAuthTokenGenerator.generateToken(oAuthEndpoint, latch);
Assert.assertNotNull(tokenResponse);
// Token endpoint will be called three times (during the first, second and third token generation operations).
PowerMockito.verifyStatic(OAuthClient.class, Mockito.times(3));
OAuthClient.generateToken(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.anyString(), Mockito.any(), Mockito.anyString());
}
Aggregations