Search in sources :

Example 66 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class AbstractKeyManagerTestCase method testCanHandleTokenWithConfigurationJWTAndOpaue.

@Test
public void testCanHandleTokenWithConfigurationJWTAndOpaue() throws APIManagementException {
    KeyManagerConfiguration keyManagerConfiguration = new KeyManagerConfiguration();
    keyManagerConfiguration.addParameter(APIConstants.KeyManager.TOKEN_FORMAT_STRING, "[{\"enable\": true,\"type\": \"JWT\",\"value\": {\"body\": {\"iss\": \"https://localhost:9443\"}}}," + "{\"enable\": true,\"type\": \"REFERENCE\",\"value\": \"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0" + "-9a-fA-F]{3}-[89ab][0-9a-fA-F]{3}-[0-9a-fA-F]{12}\"}]");
    KeyManager keyManager = new ModelKeyManagerForTest();
    keyManager.loadConfiguration(keyManagerConfiguration);
    assertTrue(keyManager.canHandleToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" + ".eyJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo5NDQzIiwiaWF0IjoxNTkwMTM0NzIyLCJleHAiOjE2MjE2NzA3MjAsImF1ZC" + "I6Ind3dy5leGFtcGxlLmNvbSIsInN1YiI6Impyb2NrZXRAZXhhbXBsZS5jb20iLCJFbWFpbCI6ImJlZUBleGFtcGxlLmNvb" + "SJ9.HIxL7_WqeLPkxYdROAwRyL0YEY1YNJRfLghsaHEc7C4"));
    assertTrue(keyManager.canHandleToken(UUID.randomUUID().toString()));
}
Also used : ModelKeyManagerForTest(org.wso2.carbon.apimgt.impl.factory.ModelKeyManagerForTest) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager) KeyManagerConfiguration(org.wso2.carbon.apimgt.api.model.KeyManagerConfiguration) Test(org.junit.Test) ModelKeyManagerForTest(org.wso2.carbon.apimgt.impl.factory.ModelKeyManagerForTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 67 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class AbstractKeyManagerTestCase method buildAccessTokenRequestFromJSONTest.

@Test
public void buildAccessTokenRequestFromJSONTest() throws APIManagementException {
    String jsonPayload = "{ \"callbackUrl\": \"www.google.lk\", \"clientName\": \"rest_api_publisher\", " + "\"tokenScope\": \"Production\", \"owner\": \"admin\", \"grantType\": \"password refresh_token\", " + "\"saasApp\": true }";
    AbstractKeyManager keyManager = new AMDefaultKeyManagerImpl();
    // test AccessTokenRequest null scenario
    AccessTokenRequest accessTokenRequest1 = keyManager.buildAccessTokenRequestFromJSON(jsonPayload, null);
    Assert.notNull(accessTokenRequest1);
    // test json payload without required parameters
    AccessTokenRequest accessTokenRequest2 = keyManager.buildAccessTokenRequestFromJSON(jsonPayload, accessTokenRequest1);
    Assert.notNull(accessTokenRequest2);
    assertNull(accessTokenRequest2.getClientId());
    // test json payload null
    assertNull(keyManager.buildAccessTokenRequestFromJSON(null, null));
    String jsonPayload2 = "{ \"callbackUrl\": \"www.google.lk\", \"client_id\": \"XBPcXSfGK47WiEX7enchoP2Dcvga\"," + "\"client_secret\": \"4UD8VX8NaQMtrHCwqzI1tHJLPoca\", \"owner\": \"admin\", \"grantType\": \"password" + " refresh_token\", " + "\"validityPeriod\": \"3600\" }";
    AccessTokenRequest accessTokenRequest3 = keyManager.buildAccessTokenRequestFromJSON(jsonPayload2, new AccessTokenRequest());
    assertEquals("XBPcXSfGK47WiEX7enchoP2Dcvga", accessTokenRequest3.getClientId());
    assertEquals("4UD8VX8NaQMtrHCwqzI1tHJLPoca", accessTokenRequest3.getClientSecret());
    assertEquals(3600, accessTokenRequest3.getValidityPeriod());
    // Error path with invalid json
    try {
        keyManager.buildAccessTokenRequestFromJSON("{dd}", null);
        assertTrue(false);
    } catch (APIManagementException e) {
        assertEquals("Error occurred while parsing JSON String", e.getMessage());
    }
    // Error path with empty JSON
    assertNull(keyManager.buildAccessTokenRequestFromJSON("{}", null));
    keyManager.buildAccessTokenRequestFromJSON(null, new AccessTokenRequest());
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) AccessTokenRequest(org.wso2.carbon.apimgt.api.model.AccessTokenRequest) Test(org.junit.Test) ModelKeyManagerForTest(org.wso2.carbon.apimgt.impl.factory.ModelKeyManagerForTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 68 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class InboundWebsocketProcessorUtil method isAuthenticated.

/**
 * Authenticate inbound websocket request handshake.
 *
 * @param inboundMessageContext InboundMessageContext
 * @return whether authenticated or not
 * @throws APIManagementException if an internal error occurs
 * @throws APISecurityException   if authentication fails
 */
public static boolean isAuthenticated(InboundMessageContext inboundMessageContext) throws APISecurityException, APIManagementException {
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(inboundMessageContext.getTenantDomain(), true);
        APIKeyValidationInfoDTO info;
        String authorizationHeader = inboundMessageContext.getRequestHeaders().get(HttpHeaders.AUTHORIZATION);
        inboundMessageContext.getRequestHeaders().put(HttpHeaders.AUTHORIZATION, authorizationHeader);
        String[] auth = authorizationHeader.split(StringUtils.SPACE);
        List<String> keyManagerList = DataHolder.getInstance().getKeyManagersFromUUID(inboundMessageContext.getElectedAPI().getUuid());
        if (APIConstants.CONSUMER_KEY_SEGMENT.equals(auth[0])) {
            String cacheKey;
            boolean isJwtToken = false;
            String apiKey = auth[1];
            if (WebsocketUtil.isRemoveOAuthHeadersFromOutMessage()) {
                inboundMessageContext.getRequestHeaders().remove(HttpHeaders.AUTHORIZATION);
            }
            // Initial guess of a JWT token using the presence of a DOT.
            if (StringUtils.isNotEmpty(apiKey) && apiKey.contains(APIConstants.DOT)) {
                try {
                    // Check if the header part is decoded
                    if (StringUtils.countMatches(apiKey, APIConstants.DOT) != 2) {
                        log.debug("Invalid JWT token. The expected token format is <header.payload.signature>");
                        throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, "Invalid JWT token");
                    }
                    inboundMessageContext.setSignedJWTInfo(getSignedJwtInfo(apiKey));
                    String keyManager = ServiceReferenceHolder.getInstance().getJwtValidationService().getKeyManagerNameIfJwtValidatorExist(inboundMessageContext.getSignedJWTInfo());
                    if (StringUtils.isNotEmpty(keyManager)) {
                        if (log.isDebugEnabled()) {
                            log.debug("KeyManager " + keyManager + "found for authenticate token " + GatewayUtils.getMaskedToken(apiKey));
                        }
                        if (keyManagerList.contains(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS) || keyManagerList.contains(keyManager)) {
                            if (log.isDebugEnabled()) {
                                log.debug("Elected KeyManager " + keyManager + "found in API level list " + String.join(",", keyManagerList));
                            }
                            isJwtToken = true;
                        } else {
                            if (log.isDebugEnabled()) {
                                log.debug("Elected KeyManager " + keyManager + " not found in API level list " + String.join(",", keyManagerList));
                            }
                            throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, "Invalid JWT token");
                        }
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("KeyManager not found for accessToken " + GatewayUtils.getMaskedToken(apiKey));
                        }
                    }
                } catch (ParseException e) {
                    log.debug("Not a JWT token. Failed to decode the token header.", e);
                } catch (APIManagementException e) {
                    log.error("Error while checking validation of JWT", e);
                    throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
                }
            }
            // Find the authentication scheme based on the token type
            if (isJwtToken) {
                log.debug("The token was identified as a JWT token");
                if (APIConstants.GRAPHQL_API.equals(inboundMessageContext.getElectedAPI().getApiType())) {
                    return InboundWebsocketProcessorUtil.authenticateGraphQLJWTToken(inboundMessageContext);
                } else {
                    return InboundWebsocketProcessorUtil.authenticateWSJWTToken(inboundMessageContext);
                }
            } else {
                log.debug("The token was identified as an OAuth token");
                // If the key have already been validated
                if (WebsocketUtil.isGatewayTokenCacheEnabled()) {
                    cacheKey = WebsocketUtil.getAccessTokenCacheKey(apiKey, inboundMessageContext.getApiContext(), inboundMessageContext.getMatchingResource());
                    info = WebsocketUtil.validateCache(apiKey, cacheKey);
                    if (info != null) {
                        inboundMessageContext.setKeyType(info.getType());
                        inboundMessageContext.setInfoDTO(info);
                        return info.isAuthorized();
                    }
                }
                info = getApiKeyDataForWSClient(apiKey, inboundMessageContext.getTenantDomain(), inboundMessageContext.getApiContext(), inboundMessageContext.getVersion(), keyManagerList);
                if (info == null || !info.isAuthorized()) {
                    return false;
                }
                if (WebsocketUtil.isGatewayTokenCacheEnabled()) {
                    cacheKey = WebsocketUtil.getAccessTokenCacheKey(apiKey, inboundMessageContext.getApiContext(), inboundMessageContext.getMatchingResource());
                    WebsocketUtil.putCache(info, apiKey, cacheKey);
                }
                inboundMessageContext.setKeyType(info.getType());
                inboundMessageContext.setToken(info.getEndUserToken());
                inboundMessageContext.setInfoDTO(info);
                return true;
            }
        } else {
            return false;
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ParseException(java.text.ParseException) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)

Example 69 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class JWTValidator method getUserClaimsFromKeyManager.

private Map<String, String> getUserClaimsFromKeyManager(JWTInfoDto jwtInfoDto) {
    if (jwtConfigurationDto.isEnableUserClaimRetrievalFromUserStore()) {
        String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        JWTValidationInfo jwtValidationInfo = jwtInfoDto.getJwtValidationInfo();
        if (jwtValidationInfo != null) {
            KeyManager keyManagerInstance = KeyManagerHolder.getKeyManagerInstance(tenantDomain, jwtValidationInfo.getKeyManager());
            if (keyManagerInstance != null) {
                Map<String, Object> properties = new HashMap<>();
                if (jwtValidationInfo.getRawPayload() != null) {
                    properties.put(APIConstants.KeyManager.ACCESS_TOKEN, jwtValidationInfo.getRawPayload());
                }
                if (!StringUtils.isEmpty(jwtConfigurationDto.getConsumerDialectUri())) {
                    properties.put(APIConstants.KeyManager.CLAIM_DIALECT, jwtConfigurationDto.getConsumerDialectUri());
                }
                properties.put(APIConstants.KeyManager.BINDING_FEDERATED_USER_CLAIMS, jwtConfigurationDto.isBindFederatedUserClaims());
                try {
                    return keyManagerInstance.getUserClaims(jwtInfoDto.getEndUser(), properties);
                } catch (APIManagementException e) {
                    log.error("Error while retrieving User claims from Key Manager ", e);
                }
            }
        }
    }
    return new HashMap<>();
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HashMap(java.util.HashMap) JSONObject(org.json.JSONObject) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager) JWTValidationInfo(org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo)

Example 70 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class KeyManagerHolder method addKeyManagerConfiguration.

public static void addKeyManagerConfiguration(String organization, String name, String type, KeyManagerConfiguration keyManagerConfiguration) throws APIManagementException {
    String issuer = (String) keyManagerConfiguration.getParameter(APIConstants.KeyManager.ISSUER);
    OrganizationKeyManagerDto organizationKeyManagerDto = organizationWiseMap.get(organization);
    if (organizationKeyManagerDto == null) {
        organizationKeyManagerDto = new OrganizationKeyManagerDto();
    }
    if (organizationKeyManagerDto.getKeyManagerByName(name) != null) {
        log.warn("Key Manager " + name + " already initialized in tenant " + organization);
    }
    if (keyManagerConfiguration.isEnabled() && !KeyManagerConfiguration.TokenType.EXCHANGED.equals(keyManagerConfiguration.getTokenType())) {
        KeyManager keyManager = null;
        JWTValidator jwtValidator = null;
        APIManagerConfiguration apiManagerConfiguration = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
        String defaultKeyManagerType = apiManagerConfiguration.getFirstProperty(APIConstants.DEFAULT_KEY_MANAGER_TYPE);
        KeyManagerConnectorConfiguration keyManagerConnectorConfiguration = ServiceReferenceHolder.getInstance().getKeyManagerConnectorConfiguration(type);
        if (keyManagerConnectorConfiguration != null) {
            if (StringUtils.isNotEmpty(keyManagerConnectorConfiguration.getImplementation())) {
                try {
                    keyManager = (KeyManager) Class.forName(keyManagerConnectorConfiguration.getImplementation()).newInstance();
                    keyManager.setTenantDomain(organization);
                    if (StringUtils.isNotEmpty(defaultKeyManagerType) && defaultKeyManagerType.equals(type)) {
                        keyManagerConfiguration.addParameter(APIConstants.KEY_MANAGER_USERNAME, apiManagerConfiguration.getFirstProperty(APIConstants.API_KEY_VALIDATOR_USERNAME));
                        keyManagerConfiguration.addParameter(APIConstants.KEY_MANAGER_PASSWORD, apiManagerConfiguration.getFirstProperty(APIConstants.API_KEY_VALIDATOR_PASSWORD));
                    }
                    keyManager.loadConfiguration(keyManagerConfiguration);
                } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                    throw new APIManagementException("Error while loading keyManager configuration", e);
                }
            }
            jwtValidator = getJWTValidator(keyManagerConfiguration, keyManagerConnectorConfiguration.getJWTValidator());
        } else {
            if (APIConstants.KeyManager.DEFAULT_KEY_MANAGER_TYPE.equals(type)) {
                keyManager = new AMDefaultKeyManagerImpl();
                keyManager.setTenantDomain(organization);
                keyManager.loadConfiguration(keyManagerConfiguration);
                jwtValidator = getJWTValidator(keyManagerConfiguration, null);
            }
        }
        KeyManagerDto keyManagerDto = new KeyManagerDto();
        keyManagerDto.setName(name);
        keyManagerDto.setIssuer(issuer);
        keyManagerDto.setJwtValidator(jwtValidator);
        keyManagerDto.setKeyManager(keyManager);
        organizationKeyManagerDto.putKeyManagerDto(keyManagerDto);
        organizationWiseMap.put(organization, organizationKeyManagerDto);
    }
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) OrganizationKeyManagerDto(org.wso2.carbon.apimgt.impl.dto.OrganizationKeyManagerDto) KeyManagerDto(org.wso2.carbon.apimgt.impl.dto.KeyManagerDto) AMDefaultKeyManagerImpl(org.wso2.carbon.apimgt.impl.AMDefaultKeyManagerImpl) KeyManagerConnectorConfiguration(org.wso2.carbon.apimgt.api.model.KeyManagerConnectorConfiguration) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OrganizationKeyManagerDto(org.wso2.carbon.apimgt.impl.dto.OrganizationKeyManagerDto) JWTValidator(org.wso2.carbon.apimgt.impl.jwt.JWTValidator) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)39 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)38 Test (org.junit.Test)29 KeyManager (org.wso2.carbon.apimgt.core.api.KeyManager)25 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)22 HashMap (java.util.HashMap)21 Test (org.testng.annotations.Test)18 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)18 FileInputStream (java.io.FileInputStream)16 KeyManagerConfigurationDTO (org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO)16 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)16 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)16 IdentityProvider (org.wso2.carbon.apimgt.core.api.IdentityProvider)16 Map (java.util.Map)14 API (org.wso2.carbon.apimgt.core.models.API)14 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)13 Scope (org.wso2.carbon.apimgt.core.models.Scope)13 KeyManagerDto (org.wso2.carbon.apimgt.impl.dto.KeyManagerDto)13 TreeMap (java.util.TreeMap)11 AccessTokenRequest (org.wso2.carbon.apimgt.api.model.AccessTokenRequest)11