Search in sources :

Example 61 with IdentityProvider

use of org.wso2.carbon.apimgt.core.api.IdentityProvider in project carbon-apimgt by wso2.

the class AuthenticatorServiceTestCase method testGetTokens.

@Test
public void testGetTokens() throws Exception {
    // Happy Path - 200 - Authorization code grant type
    APIMConfigurationService apimConfigurationService = Mockito.mock(APIMConfigurationService.class);
    EnvironmentConfigurations environmentConfigurations = new EnvironmentConfigurations();
    Mockito.when(apimConfigurationService.getEnvironmentConfigurations()).thenReturn(environmentConfigurations);
    APIMAppConfigurationService apimAppConfigurationService = Mockito.mock(APIMAppConfigurationService.class);
    APIMAppConfigurations apimAppConfigurations = new APIMAppConfigurations();
    Mockito.when(apimAppConfigurationService.getApimAppConfigurations()).thenReturn(apimAppConfigurations);
    // // Mocked response from DCR endpoint
    OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
    oAuthApplicationInfo.setClientId("xxx-client-id-xxx");
    oAuthApplicationInfo.setClientSecret("xxx-client-secret-xxx");
    // // Expected response object from KeyManager
    AccessTokenInfo tokenInfo = new AccessTokenInfo();
    tokenInfo.setAccessToken("xxx-access-token-xxx");
    tokenInfo.setScopes("apim:subscribe openid");
    tokenInfo.setRefreshToken("xxx-refresh-token-xxx");
    tokenInfo.setIdToken("xxx-id-token-xxx");
    tokenInfo.setValidityPeriod(-2L);
    KeyManager keyManager = Mockito.mock(KeyManager.class);
    SystemApplicationDao systemApplicationDao = Mockito.mock(SystemApplicationDao.class);
    Mockito.when(systemApplicationDao.isConsumerKeyExistForApplication("store")).thenReturn(false);
    MultiEnvironmentOverview multiEnvironmentOverview = new MultiEnvironmentOverview();
    environmentConfigurations.setMultiEnvironmentOverview(multiEnvironmentOverview);
    AuthenticatorService authenticatorService = new AuthenticatorService(keyManager, systemApplicationDao, apimConfigurationService, apimAppConfigurationService);
    Mockito.when(keyManager.createApplication(Mockito.any())).thenReturn(oAuthApplicationInfo);
    // // Actual response - When authorization code is not null
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
    AccessTokenInfo tokenInfoResponseForValidAuthCode = authenticatorService.getTokens("store", "authorization_code", null, null, null, 0, "xxx-auth-code-xxx", null, null);
    Assert.assertEquals(tokenInfoResponseForValidAuthCode, tokenInfo);
    // Error Path - 500 - Authorization code grant type
    // // When an error occurred - Eg: Access denied
    AccessTokenInfo emptyTokenInfo = new AccessTokenInfo();
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(emptyTokenInfo);
    AccessTokenInfo tokenInfoResponseForInvalidAuthCode = new AccessTokenInfo();
    try {
        tokenInfoResponseForInvalidAuthCode = authenticatorService.getTokens("store", "authorization_code", null, null, null, 0, null, null, null);
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "No Authorization Code available.");
        Assert.assertEquals(tokenInfoResponseForInvalidAuthCode, emptyTokenInfo);
    }
    // Happy Path - 200 - Password grant type
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
    AccessTokenInfo tokenInfoResponseForPasswordGrant = authenticatorService.getTokens("store", "password", "admin", "admin", null, 0, null, null, null);
    Assert.assertEquals(tokenInfoResponseForPasswordGrant, tokenInfo);
    // Error Path - When token generation fails and throws APIManagementException
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenThrow(KeyManagementException.class).thenReturn(tokenInfo);
    try {
        authenticatorService.getTokens("store", "password", "admin", "admin", null, 0, null, null, null);
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error while receiving tokens for OAuth application : store");
    }
    // Happy Path - 200 - Refresh grant type
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
    AccessTokenInfo tokenInfoResponseForRefreshGrant = authenticatorService.getTokens("store", "refresh_token", null, null, null, 0, null, null, null);
    Assert.assertEquals(tokenInfoResponseForPasswordGrant, tokenInfo);
    // Happy Path - 200 - JWT grant type
    // Multi-Environment Overview configuration
    multiEnvironmentOverview.setEnabled(true);
    IdentityProvider identityProvider = Mockito.mock(IdentityProvider.class);
    String userFromIdentityProvider = "admin-user";
    Mockito.when(identityProvider.getIdOfUser(Mockito.anyString())).thenThrow(IdentityProviderException.class);
    Mockito.doReturn("xxx-admin-user-id-xxx").when(identityProvider).getIdOfUser(userFromIdentityProvider);
    // A valid jwt with user "admin-user"
    String idTokenWith_adminUser = "xxx+header+xxx.eyJzdWIiOiJhZG1pbi11c2VyIn0.xxx+signature+xxx";
    tokenInfo.setIdToken(idTokenWith_adminUser);
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
    AccessTokenInfo tokenInfoResponseForValidJWTGrant = authenticatorService.getTokens("store", "urn:ietf:params:oauth:grant-type:jwt-bearer", null, null, null, 0, null, "xxx-assertion-xxx", identityProvider);
    Assert.assertEquals(tokenInfoResponseForValidJWTGrant, tokenInfo);
    // Error Path - When invalid user in JWT Token
    // A valid jwt with user "John"
    String idTokenWith_johnUser = "xxx+header+xxx.eyJzdWIiOiJKb2huIn0.xxx+signature+xxx";
    tokenInfo.setIdToken(idTokenWith_johnUser);
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
    try {
        AccessTokenInfo tokenInfoResponseForInvalidJWTGrant = authenticatorService.getTokens("store", "urn:ietf:params:oauth:grant-type:jwt-bearer", null, null, null, 0, null, "xxx-assertion-xxx", identityProvider);
        Assert.assertEquals(tokenInfoResponseForInvalidJWTGrant, tokenInfo);
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "User John does not exists in this environment.");
    }
}
Also used : IdentityProvider(org.wso2.carbon.apimgt.core.api.IdentityProvider) APIMAppConfigurationService(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.APIMAppConfigurationService) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) EnvironmentConfigurations(org.wso2.carbon.apimgt.core.configuration.models.EnvironmentConfigurations) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) APIMAppConfigurations(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations) SystemApplicationDao(org.wso2.carbon.apimgt.core.dao.SystemApplicationDao) MultiEnvironmentOverview(org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview) KeyManager(org.wso2.carbon.apimgt.core.api.KeyManager) APIMConfigurationService(org.wso2.carbon.apimgt.core.configuration.APIMConfigurationService) Test(org.junit.Test)

Example 62 with IdentityProvider

use of org.wso2.carbon.apimgt.core.api.IdentityProvider in project siddhi by wso2.

the class WindowDefinitionTestCase method testEventWindow8.

@Test(expectedExceptions = DuplicateDefinitionException.class)
public void testEventWindow8() throws InterruptedException {
    log.info("WindowDefinitionTestCase Test8");
    SiddhiManager siddhiManager = new SiddhiManager();
    String query = "define stream InStream (meta_tenantId int, contextId string, eventId string, eventType " + "string, authenticationSuccess bool, username string, localUsername string, userStoreDomain string, " + "tenantDomain string, remoteIp string, region string, inboundAuthType string, serviceProvider string," + " rememberMeEnabled bool, forceAuthEnabled bool, passiveAuthEnabled bool, rolesCommaSeparated string," + " authenticationStep string, identityProvider string, authStepSuccess bool, stepAuthenticator string," + " isFirstLogin bool, identityProviderType string, _timestamp long);\n" + "define window countWindow (meta_tenantId int, batchEndTime long, timestamp long) externalTimeBatch" + "(batchEndTime, 1 sec, 0, 10 sec, true);\n" + "from InStream\n" + "select meta_tenantId, eventId\n" + "insert into countStream;\n" + "from countStream\n" + "select meta_tenantId, eventId\n" + "insert into countWindow;";
    SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(query);
    siddhiAppRuntime.shutdown();
}
Also used : SiddhiAppRuntime(org.wso2.siddhi.core.SiddhiAppRuntime) SiddhiManager(org.wso2.siddhi.core.SiddhiManager) Test(org.testng.annotations.Test)

Example 63 with IdentityProvider

use of org.wso2.carbon.apimgt.core.api.IdentityProvider in project carbon-apimgt by wso2.

the class SystemScopesIssuer method getResidentIDPForIssuer.

private IdentityProvider getResidentIDPForIssuer(String tenantDomain, String jwtIssuer) throws IdentityOAuth2Exception {
    String issuer = "";
    IdentityProvider residentIdentityProvider;
    try {
        residentIdentityProvider = IdentityProviderManager.getInstance().getResidentIdP(tenantDomain);
    } catch (IdentityProviderManagementException var7) {
        String errorMsg = String.format("Error while getting Resident Identity Provider of '%s' tenant.", tenantDomain);
        throw new IdentityOAuth2Exception(errorMsg, var7);
    }
    FederatedAuthenticatorConfig[] fedAuthnConfigs = residentIdentityProvider.getFederatedAuthenticatorConfigs();
    FederatedAuthenticatorConfig oauthAuthenticatorConfig = IdentityApplicationManagementUtil.getFederatedAuthenticator(fedAuthnConfigs, "openidconnect");
    if (oauthAuthenticatorConfig != null) {
        issuer = IdentityApplicationManagementUtil.getProperty(oauthAuthenticatorConfig.getProperties(), "IdPEntityId").getValue();
    }
    return jwtIssuer.equals(issuer) ? residentIdentityProvider : null;
}
Also used : IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException)

Example 64 with IdentityProvider

use of org.wso2.carbon.apimgt.core.api.IdentityProvider in project carbon-apimgt by wso2.

the class APIAdminImpl method addKeyManagerConfiguration.

@Override
public KeyManagerConfigurationDTO addKeyManagerConfiguration(KeyManagerConfigurationDTO keyManagerConfigurationDTO) throws APIManagementException {
    if (apiMgtDAO.isKeyManagerConfigurationExistByName(keyManagerConfigurationDTO.getName(), keyManagerConfigurationDTO.getOrganization())) {
        throw new APIManagementException("Key manager Already Exist by Name " + keyManagerConfigurationDTO.getName() + " in tenant " + keyManagerConfigurationDTO.getOrganization(), ExceptionCodes.KEY_MANAGER_ALREADY_EXIST);
    }
    if (!KeyManagerConfiguration.TokenType.valueOf(keyManagerConfigurationDTO.getTokenType().toUpperCase()).equals(KeyManagerConfiguration.TokenType.EXCHANGED)) {
        validateKeyManagerConfiguration(keyManagerConfigurationDTO);
        validateKeyManagerEndpointConfiguration(keyManagerConfigurationDTO);
    }
    if (StringUtils.equals(KeyManagerConfiguration.TokenType.EXCHANGED.toString(), keyManagerConfigurationDTO.getTokenType()) || StringUtils.equals(KeyManagerConfiguration.TokenType.BOTH.toString(), keyManagerConfigurationDTO.getTokenType())) {
        keyManagerConfigurationDTO.setUuid(UUID.randomUUID().toString());
        try {
            IdentityProvider identityProvider = IdentityProviderManager.getInstance().addIdPWithResourceId(createIdp(keyManagerConfigurationDTO), APIUtil.getInternalOrganizationDomain(keyManagerConfigurationDTO.getOrganization()));
            keyManagerConfigurationDTO.setExternalReferenceId(identityProvider.getResourceId());
        } catch (IdentityProviderManagementException e) {
            throw new APIManagementException("IdP adding failed. " + e.getMessage(), e, ExceptionCodes.IDP_ADDING_FAILED);
        }
    }
    if (StringUtils.isBlank(keyManagerConfigurationDTO.getUuid())) {
        keyManagerConfigurationDTO.setUuid(UUID.randomUUID().toString());
    }
    KeyManagerConfigurationDTO keyManagerConfigurationToStore = new KeyManagerConfigurationDTO(keyManagerConfigurationDTO);
    encryptKeyManagerConfigurationValues(null, keyManagerConfigurationToStore);
    apiMgtDAO.addKeyManagerConfiguration(keyManagerConfigurationToStore);
    new KeyMgtNotificationSender().notify(keyManagerConfigurationDTO, APIConstants.KeyManager.KeyManagerEvent.ACTION_ADD);
    return keyManagerConfigurationDTO;
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) IdentityProvider(org.wso2.carbon.identity.application.common.model.IdentityProvider) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException) KeyMgtNotificationSender(org.wso2.carbon.apimgt.impl.keymgt.KeyMgtNotificationSender)

Example 65 with IdentityProvider

use of org.wso2.carbon.apimgt.core.api.IdentityProvider in project carbon-apimgt by wso2.

the class APIAdminImpl method createIdp.

private IdentityProvider createIdp(KeyManagerConfigurationDTO keyManagerConfigurationDTO) {
    IdentityProvider identityProvider = new IdentityProvider();
    String idpName = sanitizeName(getSubstringOfTen(keyManagerConfigurationDTO.getName()) + "_" + keyManagerConfigurationDTO.getOrganization() + "_" + keyManagerConfigurationDTO.getUuid());
    identityProvider.setIdentityProviderName(idpName);
    identityProvider.setDisplayName(keyManagerConfigurationDTO.getDisplayName());
    identityProvider.setPrimary(Boolean.FALSE);
    identityProvider.setIdentityProviderDescription(keyManagerConfigurationDTO.getDescription());
    identityProvider.setAlias(keyManagerConfigurationDTO.getAlias());
    String certificate = null;
    if (keyManagerConfigurationDTO.getAdditionalProperties().containsKey(APIConstants.KeyManager.CERTIFICATE_VALUE)) {
        certificate = (String) keyManagerConfigurationDTO.getAdditionalProperties().get(APIConstants.KeyManager.CERTIFICATE_VALUE);
    }
    String certificateType = null;
    if (keyManagerConfigurationDTO.getAdditionalProperties().containsKey(APIConstants.KeyManager.CERTIFICATE_TYPE)) {
        certificateType = (String) keyManagerConfigurationDTO.getAdditionalProperties().get(APIConstants.KeyManager.CERTIFICATE_TYPE);
    }
    List<IdentityProviderProperty> idpProperties = new ArrayList<>();
    if (StringUtils.isNotEmpty(certificate) && StringUtils.isNotEmpty(certificateType)) {
        if (APIConstants.KeyManager.CERTIFICATE_TYPE_JWKS_ENDPOINT.equals(certificateType)) {
            if (StringUtils.isNotBlank(certificate)) {
                IdentityProviderProperty jwksProperty = new IdentityProviderProperty();
                jwksProperty.setName(APIConstants.JWKS_URI);
                jwksProperty.setValue(certificate);
                idpProperties.add(jwksProperty);
            }
        } else if (APIConstants.KeyManager.CERTIFICATE_TYPE_PEM_FILE.equals(certificateType)) {
            identityProvider.setCertificate(String.join(certificate, ""));
        }
    }
    if (keyManagerConfigurationDTO.getProperty(APIConstants.KeyManager.ISSUER) != null) {
        IdentityProviderProperty identityProviderProperty = new IdentityProviderProperty();
        identityProviderProperty.setName(IdentityApplicationConstants.IDP_ISSUER_NAME);
        identityProviderProperty.setValue((String) keyManagerConfigurationDTO.getProperty(APIConstants.KeyManager.ISSUER));
        idpProperties.add(identityProviderProperty);
    }
    if (idpProperties.size() > 0) {
        identityProvider.setIdpProperties(idpProperties.toArray(new IdentityProviderProperty[0]));
    }
    identityProvider.setEnable(keyManagerConfigurationDTO.isEnabled());
    Object claims = keyManagerConfigurationDTO.getProperty(APIConstants.KeyManager.CLAIM_MAPPING);
    updateClaims(identityProvider, claims);
    return identityProvider;
}
Also used : IdentityProviderProperty(org.wso2.carbon.identity.application.common.model.IdentityProviderProperty) ArrayList(java.util.ArrayList) IdentityProvider(org.wso2.carbon.identity.application.common.model.IdentityProvider) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject)

Aggregations

IdentityProvider (org.wso2.carbon.apimgt.core.api.IdentityProvider)54 Test (org.testng.annotations.Test)50 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)47 API (org.wso2.carbon.apimgt.core.models.API)43 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)35 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)34 APILifecycleManager (org.wso2.carbon.apimgt.core.api.APILifecycleManager)20 APIBuilder (org.wso2.carbon.apimgt.core.models.API.APIBuilder)19 KeyManager (org.wso2.carbon.apimgt.core.api.KeyManager)16 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)15 FileInputStream (java.io.FileInputStream)11 LabelDAO (org.wso2.carbon.apimgt.core.dao.LabelDAO)11 Scope (org.wso2.carbon.apimgt.core.models.Scope)11 APISubscriptionDAO (org.wso2.carbon.apimgt.core.dao.APISubscriptionDAO)8 PolicyDAO (org.wso2.carbon.apimgt.core.dao.PolicyDAO)8 DedicatedGateway (org.wso2.carbon.apimgt.core.models.DedicatedGateway)8 APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)8 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)8 ArrayList (java.util.ArrayList)7 IdentityProvider (org.wso2.carbon.identity.application.common.model.IdentityProvider)7