Search in sources :

Example 21 with OAuth

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)));
}
Also used : GraphQLOperationDTO(org.wso2.carbon.apimgt.gateway.dto.GraphQLOperationDTO) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) InboundProcessorResponseDTO(org.wso2.carbon.apimgt.gateway.inbound.websocket.InboundProcessorResponseDTO) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) InboundMessageContext(org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 22 with OAuth

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));
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Scope(org.wso2.carbon.apimgt.api.model.Scope) Swagger(io.swagger.models.Swagger) OAuth2Definition(io.swagger.models.auth.OAuth2Definition) SecuritySchemeDefinition(io.swagger.models.auth.SecuritySchemeDefinition) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 23 with OAuth

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());
    }
}
Also used : KeyManagerConnectorConfiguration(org.wso2.carbon.apimgt.api.model.KeyManagerConnectorConfiguration) ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) Test(org.junit.Test) ModelKeyManagerForTest(org.wso2.carbon.apimgt.impl.factory.ModelKeyManagerForTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 24 with OAuth

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()));
}
Also used : TokenResponse(org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 25 with OAuth

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());
}
Also used : TokenResponse(org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)26 HashMap (java.util.HashMap)18 ArrayList (java.util.ArrayList)14 Test (org.junit.Test)14 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)13 Map (java.util.Map)11 JSONObject (org.json.simple.JSONObject)9 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)9 OAuthApplicationInfo (org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo)9 JsonObject (com.google.gson.JsonObject)8 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)8 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)8 TokenResponse (org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse)8 LinkedHashMap (java.util.LinkedHashMap)6 Test (org.testng.annotations.Test)6 IOException (java.io.IOException)5 ParseException (org.json.simple.parser.ParseException)5 OAuthAppRequest (org.wso2.carbon.apimgt.api.model.OAuthAppRequest)5 MultiEnvironmentOverview (org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview)5 APIMAppConfigurations (org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations)5