Search in sources :

Example 46 with APIKeyValidationInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO in project carbon-apimgt by wso2.

the class JWTValidator method authenticateForWebSocket.

/**
 * Authenticates the given WebSocket handshake request with a JWT token to see if an API consumer is allowed to
 * access a particular API or not.
 *
 * @param signedJWTInfo    The JWT token sent with the API request
 * @param apiContext       The context of the invoked API
 * @param apiVersion       The version of the invoked API
 * @param matchingResource template of matching api resource
 * @return an AuthenticationContext object which contains the authentication information
 * @throws APISecurityException in case of authentication failure
 */
@MethodStats
public AuthenticationContext authenticateForWebSocket(SignedJWTInfo signedJWTInfo, String apiContext, String apiVersion, String matchingResource) throws APISecurityException {
    String tokenSignature = signedJWTInfo.getSignedJWT().getSignature().toString();
    JWTClaimsSet jwtClaimsSet = signedJWTInfo.getJwtClaimsSet();
    String jti = getJWTTokenIdentifier(signedJWTInfo);
    JWTValidationInfo jwtValidationInfo = validateTokenForWS(signedJWTInfo, tokenSignature, jti);
    if (jwtValidationInfo != null && jwtValidationInfo.isValid()) {
        APIKeyValidationInfoDTO apiKeyValidationInfoDTO = validateSubscriptionsForWS(jwtValidationInfo, apiContext, apiVersion);
        if (apiKeyValidationInfoDTO.isAuthorized()) {
            validateScopes(apiContext, apiVersion, matchingResource, WebSocketApiConstants.WEBSOCKET_DUMMY_HTTP_METHOD_NAME, jwtValidationInfo, signedJWTInfo);
            log.debug("JWT authentication successful. user: " + apiKeyValidationInfoDTO.getEndUserName());
            String endUserToken = generateBackendJWTForWS(jwtValidationInfo, apiKeyValidationInfoDTO, apiContext, apiVersion, tokenSignature);
            return generateAuthenticationContextForWS(jti, jwtValidationInfo, apiKeyValidationInfoDTO, endUserToken, apiVersion);
        } else {
            String message = "User is NOT authorized to access the Resource. API Subscription validation failed.";
            log.debug(message);
            throw new APISecurityException(apiKeyValidationInfoDTO.getValidationStatus(), message);
        }
    } else if (!jwtValidationInfo.isValid()) {
        throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, "Invalid JWT token");
    }
    throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) JWTValidationInfo(org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo) MethodStats(org.wso2.carbon.apimgt.gateway.MethodStats)

Example 47 with APIKeyValidationInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO in project carbon-apimgt by wso2.

the class JWTValidator method validateSubscriptionsForWS.

/**
 * This method is used to validate subscriptions for WS API requests.
 *
 * @param jwtValidationInfo JWTValidationInfo
 * @param apiContext        API Context
 * @param apiVersion        API Version
 * @return APIKeyValidationInfoDTO
 * @throws APISecurityException if an error occurs.
 */
private APIKeyValidationInfoDTO validateSubscriptionsForWS(JWTValidationInfo jwtValidationInfo, String apiContext, String apiVersion) throws APISecurityException {
    log.debug("Begin subscription validation via Key Manager: " + jwtValidationInfo.getKeyManager());
    APIKeyValidationInfoDTO apiKeyValidationInfoDTO = validateSubscriptionUsingKeyManager(apiContext, apiVersion, jwtValidationInfo);
    if (log.isDebugEnabled()) {
        log.debug("Subscription validation via Key Manager: " + jwtValidationInfo.getKeyManager() + ". Status: " + apiKeyValidationInfoDTO.isAuthorized());
    }
    return apiKeyValidationInfoDTO;
}
Also used : APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)

Example 48 with APIKeyValidationInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO in project carbon-apimgt by wso2.

the class JWTValidator method generateBackendJWTForWS.

/**
 * Generate backend JWT for WS API requests.
 *
 * @param jwtValidationInfo       JWTValidationInfo
 * @param apiKeyValidationInfoDTO APIKeyValidationInfoDTO
 * @param apiContext              API Context
 * @param apiVersion              API Version
 * @param tokenSignature          Token signature
 * @return Backend JWT String
 * @throws APISecurityException if an error ocurrs
 */
private String generateBackendJWTForWS(JWTValidationInfo jwtValidationInfo, APIKeyValidationInfoDTO apiKeyValidationInfoDTO, String apiContext, String apiVersion, String tokenSignature) throws APISecurityException {
    String endUserToken = null;
    JWTInfoDto jwtInfoDto;
    if (jwtGenerationEnabled) {
        jwtInfoDto = GatewayUtils.generateJWTInfoDto(jwtValidationInfo, apiKeyValidationInfoDTO, apiContext, apiVersion);
        endUserToken = generateAndRetrieveJWTToken(tokenSignature, jwtInfoDto);
    }
    return endUserToken;
}
Also used : JWTInfoDto(org.wso2.carbon.apimgt.common.gateway.dto.JWTInfoDto)

Example 49 with APIKeyValidationInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO in project carbon-apimgt by wso2.

the class APIKeyValidatorTestCase method testCheckForValidTokenForTenant.

// Test for first time invocation for valid token for Tenant
// Expectation : token need to put into token cache at super tenant,tenant and put @APIKeyValidationInfoDTO to cache
@Test
public void testCheckForValidTokenForTenant() throws APISecurityException {
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain("abc.com");
        String tenantDomain = "abc.com";
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(1);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername("admin");
        APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
        apiKeyValidationInfoDTO.setAuthorized(true);
        AxisConfiguration axisConfiguration = Mockito.mock(AxisConfiguration.class);
        Cache tokenCache = Mockito.mock(Cache.class);
        Cache keyCache = Mockito.mock(Cache.class);
        Cache resourceCache = Mockito.mock(Cache.class);
        Cache invalidTokenCache = Mockito.mock(Cache.class);
        APIKeyDataStore apiKeyDataStore = Mockito.mock(APIKeyDataStore.class);
        APIKeyValidator apiKeyValidator = getAPIKeyValidator(axisConfiguration, invalidTokenCache, tokenCache, keyCache, resourceCache, apiKeyDataStore, "abc.com");
        Mockito.when(tokenCache.get(Mockito.anyString())).thenReturn(null);
        Mockito.when(invalidTokenCache.get(Mockito.anyString())).thenReturn(null);
        Mockito.when(apiKeyDataStore.getAPIKeyData(context, apiVersion, apiKey, authenticationScheme, matchingResource, httpVerb, tenantDomain, new ArrayList<>())).thenReturn(apiKeyValidationInfoDTO);
        apiKeyValidator.getKeyValidationInfo(context, apiKey, apiVersion, authenticationScheme, matchingResource, httpVerb, defaultVersionInvoked, new ArrayList<>());
        Mockito.verify(tokenCache, Mockito.times(1)).get(Mockito.anyString());
        Mockito.verify(invalidTokenCache, Mockito.times(1)).get(Mockito.anyString());
        Mockito.verify(keyCache, Mockito.times(0)).get(Mockito.anyString());
        Mockito.verify(tokenCache, Mockito.times(2)).put(Mockito.anyString(), Mockito.anyString());
        Mockito.verify(keyCache, Mockito.times(1)).put(Mockito.any(APIKeyValidationInfoDTO.class), Mockito.anyString());
        Mockito.verify(invalidTokenCache, Mockito.times(0)).put(Mockito.anyString(), Mockito.anyString());
        Mockito.verify(tokenCache, Mockito.times(0)).remove(Mockito.anyString());
        Mockito.verify(invalidTokenCache, Mockito.times(0)).remove(Mockito.anyString());
        Mockito.verify(keyCache, Mockito.times(0)).remove(Mockito.anyString());
        Mockito.verify(apiKeyDataStore, Mockito.times(1)).getAPIKeyData(context, apiVersion, apiKey, authenticationScheme, matchingResource, httpVerb, tenantDomain, new ArrayList<>());
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : AxisConfiguration(org.apache.axis2.engine.AxisConfiguration) WSAPIKeyDataStore(org.wso2.carbon.apimgt.gateway.handlers.security.keys.WSAPIKeyDataStore) APIKeyDataStore(org.wso2.carbon.apimgt.gateway.handlers.security.keys.APIKeyDataStore) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Cache(javax.cache.Cache) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 50 with APIKeyValidationInfoDTO

use of org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO in project carbon-apimgt by wso2.

the class WebsocketUtilTestCase method testPutCache.

@Test
public void testPutCache() {
    APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
    apiKeyValidationInfoDTO.setApiName(apiName);
    Cache gwKeyCache = Mockito.mock(Cache.class);
    Cache gwTokenCache = Mockito.mock(Cache.class);
    WebsocketUtil.putCache(apiKeyValidationInfoDTO, apiKey, cacheKey);
    Assert.assertEquals(apiName, apiKeyValidationInfoDTO.getApiName());
}
Also used : APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Cache(javax.cache.Cache) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

APIKeyValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO)54 Test (org.junit.Test)29 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)28 Cache (javax.cache.Cache)19 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)14 HashMap (java.util.HashMap)13 JWTValidationInfo (org.wso2.carbon.apimgt.common.gateway.dto.JWTValidationInfo)12 TokenValidationContext (org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext)12 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)11 APIKeyValidator (org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator)11 AuthenticationContext (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)11 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)11 SignedJWTInfo (org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo)10 AxisConfiguration (org.apache.axis2.engine.AxisConfiguration)9 MessageContext (org.apache.synapse.MessageContext)9 ExtendedJWTConfigurationDto (org.wso2.carbon.apimgt.impl.dto.ExtendedJWTConfigurationDto)9 JWTValidationService (org.wso2.carbon.apimgt.impl.jwt.JWTValidationService)9 SignedJWT (com.nimbusds.jwt.SignedJWT)8 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)7 APIKeyDataStore (org.wso2.carbon.apimgt.gateway.handlers.security.keys.APIKeyDataStore)7