Search in sources :

Example 16 with AuthenticationResponse

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse in project carbon-apimgt by wso2.

the class BasicAuthAuthenticator method authenticate.

/**
 * Authenticates the given request to see if an API consumer is allowed to access
 * a particular API or not.
 *
 * @param synCtx The message to be authenticated
 * @return an AuthenticationResponse object which contains the authentication status
 */
@MethodStats
public AuthenticationResponse authenticate(MessageContext synCtx) {
    if (log.isDebugEnabled()) {
        log.info("Basic Authentication initialized");
    }
    openAPI = (OpenAPI) synCtx.getProperty(APIMgtGatewayConstants.OPEN_API_OBJECT);
    if (openAPI == null && !APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
        log.error("OpenAPI definition is missing in the gateway. Basic authentication cannot be performed.");
        return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_MISSING_OPEN_API_DEF, "Basic authentication cannot be performed.");
    }
    // Extract basic authorization header while removing it from the authorization header
    String basicAuthHeader = extractBasicAuthHeader(synCtx);
    String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
    String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
    String httpMethod = (String) ((Axis2MessageContext) synCtx).getAxis2MessageContext().getProperty(Constants.Configuration.HTTP_METHOD);
    String matchingResource = (String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE);
    // Check for resource level authentication
    String authenticationScheme;
    List<VerbInfoDTO> verbInfoList;
    if (APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
        HashMap<String, Boolean> operationAuthSchemeMappingList = (HashMap<String, Boolean>) synCtx.getProperty(APIConstants.OPERATION_AUTH_SCHEME_MAPPING);
        HashMap<String, String> operationThrottlingMappingList = (HashMap<String, String>) synCtx.getProperty(APIConstants.OPERATION_THROTTLING_MAPPING);
        String[] operationList = matchingResource.split(",");
        verbInfoList = new ArrayList<>(1);
        authenticationScheme = APIConstants.AUTH_NO_AUTHENTICATION;
        for (String operation : operationList) {
            boolean operationAuthSchemeEnabled = operationAuthSchemeMappingList.get(operation);
            VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
            if (operationAuthSchemeEnabled) {
                verbInfoDTO.setAuthType(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN);
                authenticationScheme = APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN;
            } else {
                verbInfoDTO.setAuthType(APIConstants.AUTH_NO_AUTHENTICATION);
            }
            verbInfoDTO.setThrottling(operationThrottlingMappingList.get(operation));
            verbInfoDTO.setRequestKey(apiContext + "/" + apiVersion + operation + ":" + httpMethod);
            verbInfoList.add(verbInfoDTO);
        }
    } else {
        authenticationScheme = OpenAPIUtils.getResourceAuthenticationScheme(openAPI, synCtx);
        verbInfoList = new ArrayList<>(1);
        VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
        verbInfoDTO.setAuthType(authenticationScheme);
        verbInfoDTO.setThrottling(OpenAPIUtils.getResourceThrottlingTier(openAPI, synCtx));
        verbInfoDTO.setRequestKey(apiContext + "/" + apiVersion + matchingResource + ":" + httpMethod);
        verbInfoList.add(verbInfoDTO);
    }
    String[] credentials;
    try {
        credentials = extractBasicAuthCredentials(basicAuthHeader);
    } catch (APISecurityException ex) {
        return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
    }
    String username = getEndUserName(credentials[0]);
    String password = credentials[1];
    // If end user tenant domain does not match the API publisher's tenant domain, return error
    if (!MultitenantUtils.getTenantDomain(username).equals(synCtx.getProperty(PUBLISHER_TENANT_DOMAIN))) {
        log.error("Basic Authentication failure: tenant domain mismatch for user :" + username);
        return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_FORBIDDEN, APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE);
    }
    BasicAuthValidationInfoDTO basicAuthValidationInfoObj;
    try {
        if (basicAuthCredentialValidator == null) {
            basicAuthCredentialValidator = new BasicAuthCredentialValidator();
        }
        basicAuthValidationInfoObj = basicAuthCredentialValidator.validate(username, password);
    } catch (APISecurityException ex) {
        return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
    }
    if (!basicAuthValidationInfoObj.isAuthenticated()) {
        log.error("Basic Authentication failure: Username and Password mismatch");
        return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
    } else {
        // username password matches
        if (log.isDebugEnabled()) {
            log.debug("Basic Authentication: Username and Password authenticated");
        }
        // scope validation
        boolean scopesValid = false;
        try {
            scopesValid = basicAuthCredentialValidator.validateScopes(username, openAPI, synCtx, basicAuthValidationInfoObj);
        } catch (APISecurityException ex) {
            return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
        }
        String domainQualifiedUserName = basicAuthValidationInfoObj.getDomainQualifiedUsername();
        if (scopesValid) {
            if (APISecurityUtils.getAuthenticationContext(synCtx) == null) {
                // Create a dummy AuthenticationContext object with hard coded values for
                // Tier and KeyType. This is because we cannot determine the Tier nor Key
                // Type without subscription information..
                AuthenticationContext authContext = new AuthenticationContext();
                authContext.setAuthenticated(true);
                authContext.setTier(APIConstants.UNAUTHENTICATED_TIER);
                authContext.setStopOnQuotaReach(// Since we don't have details on unauthenticated tier we setting stop on quota reach true
                true);
                synCtx.setProperty(APIConstants.VERB_INFO_DTO, verbInfoList);
                // In basic authentication scenario, we will use the username for throttling.
                authContext.setApiKey(domainQualifiedUserName);
                authContext.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
                authContext.setUsername(domainQualifiedUserName);
                authContext.setCallerToken(null);
                authContext.setApplicationName(APIConstants.BASIC_AUTH_APPLICATION_NAME);
                // Set username as application ID in basic auth scenario
                authContext.setApplicationId(domainQualifiedUserName);
                // Set username as application ID in basic auth scenario
                authContext.setApplicationUUID(domainQualifiedUserName);
                // Set application owner in basic auth scenario
                authContext.setSubscriber(APIConstants.BASIC_AUTH_APPLICATION_OWNER);
                authContext.setConsumerKey(null);
                authContext.setApiTier(apiLevelPolicy);
                APISecurityUtils.setAuthenticationContext(synCtx, authContext, null);
            }
            log.debug("Basic Authentication: Scope validation passed");
            return new AuthenticationResponse(true, isMandatory, false, 0, null);
        }
        return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.INVALID_SCOPE, "Scope validation failed");
    }
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) HashMap(java.util.HashMap) AuthenticationResponse(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse) BasicAuthValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.BasicAuthValidationInfoDTO) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) MethodStats(org.wso2.carbon.apimgt.gateway.MethodStats)

Example 17 with AuthenticationResponse

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse in project carbon-apimgt by wso2.

the class InternalAPIKeyAuthenticatorTest method testAuthenticateNoOpenAPIDefinition.

@Test
public void testAuthenticateNoOpenAPIDefinition() {
    InternalAPIKeyAuthenticator internalAPIKeyAuthenticator = new InternalAPIKeyAuthenticator(APIMgtGatewayConstants.INTERNAL_KEY);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    API api = new API();
    PowerMockito.when(GatewayUtils.getAPI(messageContext)).thenReturn(api);
    TreeMap transportHeaders = new TreeMap();
    transportHeaders.put(APIMgtGatewayConstants.INTERNAL_KEY, internalKey);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(transportHeaders);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    AuthenticationResponse authenticate = internalAPIKeyAuthenticator.authenticate(messageContext);
    Assert.assertNotNull(authenticate);
    Assert.assertTrue(authenticate.isMandatoryAuthentication());
    Assert.assertFalse(authenticate.isAuthenticated());
    Assert.assertFalse(authenticate.isContinueToNextAuthenticator());
    Assert.assertEquals(authenticate.getErrorCode(), APISecurityConstants.API_AUTH_MISSING_OPEN_API_DEF);
    Assert.assertEquals(authenticate.getErrorMessage(), APISecurityConstants.API_AUTH_MISSING_OPEN_API_DEF_ERROR_MESSAGE);
}
Also used : OpenAPI(io.swagger.v3.oas.models.OpenAPI) API(org.wso2.carbon.apimgt.keymgt.model.entity.API) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) TreeMap(java.util.TreeMap) AuthenticationResponse(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 18 with AuthenticationResponse

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse in project carbon-apimgt by wso2.

the class InternalAPIKeyAuthenticatorTest method testAuthenticateNoCacheExpiredToken.

@Test
public void testAuthenticateNoCacheExpiredToken() throws Exception {
    PowerMockito.when(GatewayUtils.isInternalKey(Mockito.any(JWTClaimsSet.class))).thenReturn(true);
    InternalAPIKeyAuthenticator internalAPIKeyAuthenticator = new InternalAPIKeyAuthenticator(APIMgtGatewayConstants.INTERNAL_KEY);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1/1.0.0");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0.0");
    API api = new API();
    PowerMockito.when(GatewayUtils.getAPI(messageContext)).thenReturn(api);
    TreeMap transportHeaders = new TreeMap();
    transportHeaders.put(APIMgtGatewayConstants.INTERNAL_KEY, internalKey);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(transportHeaders);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET");
    Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/resource");
    OpenAPI openAPI = Mockito.mock(OpenAPI.class);
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.OPEN_API_OBJECT)).thenReturn(openAPI);
    PowerMockito.when(OpenAPIUtils.getResourceThrottlingTier(openAPI, messageContext)).thenReturn("GOLD");
    PowerMockito.when(GatewayUtils.getTenantDomain()).thenReturn("carbon.super");
    Cache internalKeyCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getGatewayInternalKeyCache()).thenReturn(internalKeyCache);
    Mockito.when(internalKeyCache.get("28f8d7b0-9e62-4341-bf17-094453d5ffa4")).thenReturn(null);
    Cache internalKeyDataCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getGatewayInternalKeyDataCache()).thenReturn(internalKeyDataCache);
    Cache invalidCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getInvalidGatewayInternalKeyCache()).thenReturn(invalidCache);
    Mockito.when(invalidCache.get("28f8d7b0-9e62-4341-bf17-094453d5ffa4")).thenReturn(null);
    String cacheKey = GatewayUtils.getAccessTokenCacheKey("28f8d7b0-9e62-4341-bf17-094453d5ffa4", "/api1/1.0.0", "1.0.0", "/resource", "GET");
    JSONObject subscribedAPI = Mockito.mock(JSONObject.class);
    PowerMockito.when(GatewayUtils.verifyTokenSignature(Mockito.any(SignedJWT.class), Mockito.anyString())).thenReturn(true);
    PowerMockito.when(GatewayUtils.isJwtTokenExpired(signedJWT.getJWTClaimsSet())).thenReturn(true);
    PowerMockito.when(GatewayUtils.validateAPISubscription("/api1/1.0.0", "1.0.0", signedJWT.getJWTClaimsSet(), internalKey.split("\\."), false)).thenReturn(subscribedAPI);
    AuthenticationContext authenticationContext = Mockito.mock(AuthenticationContext.class);
    PowerMockito.when(GatewayUtils.generateAuthenticationContext("28f8d7b0-9e62-4341-bf17-094453d5ffa4", signedJWT.getJWTClaimsSet(), subscribedAPI, api.getApiTier())).thenReturn(authenticationContext);
    PowerMockito.doNothing().when(APISecurityUtils.class, "setAuthenticationContext", messageContext, authenticationContext);
    AuthenticationResponse authenticate = internalAPIKeyAuthenticator.authenticate(messageContext);
    Assert.assertNotNull(authenticate);
    Assert.assertTrue(authenticate.isMandatoryAuthentication());
    Assert.assertFalse(authenticate.isAuthenticated());
    Assert.assertFalse(authenticate.isContinueToNextAuthenticator());
    Assert.assertEquals(authenticate.getErrorCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS);
    Assert.assertEquals(authenticate.getErrorMessage(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
    Mockito.verify(internalKeyCache, Mockito.times(1)).get("28f8d7b0-9e62-4341-bf17-094453d5ffa4");
    Mockito.verify(invalidCache, Mockito.times(1)).get("28f8d7b0-9e62-4341-bf17-094453d5ffa4");
    Mockito.verify(internalKeyCache, Mockito.times(0)).put("28f8d7b0-9e62-4341-bf17-094453d5ffa4", "carbon.super");
    Mockito.verify(invalidCache, Mockito.times(1)).put("28f8d7b0-9e62-4341-bf17-094453d5ffa4", "carbon.super");
    Mockito.verify(internalKeyDataCache, Mockito.times(0)).put(Mockito.anyString(), Mockito.any(AuthenticationContext.class));
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) SignedJWT(com.nimbusds.jwt.SignedJWT) TreeMap(java.util.TreeMap) AuthenticationResponse(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse) JSONObject(net.minidev.json.JSONObject) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) OpenAPI(io.swagger.v3.oas.models.OpenAPI) API(org.wso2.carbon.apimgt.keymgt.model.entity.API) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Cache(javax.cache.Cache) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 19 with AuthenticationResponse

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse in project carbon-apimgt by wso2.

the class InternalAPIKeyAuthenticatorTest method testAuthenticateNoCacheInvalidSignatureToken.

@Test
public void testAuthenticateNoCacheInvalidSignatureToken() throws Exception {
    PowerMockito.when(GatewayUtils.isInternalKey(Mockito.any(JWTClaimsSet.class))).thenReturn(true);
    InternalAPIKeyAuthenticator internalAPIKeyAuthenticator = new InternalAPIKeyAuthenticator(APIMgtGatewayConstants.INTERNAL_KEY);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1/1.0.0");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0.0");
    API api = new API();
    PowerMockito.when(GatewayUtils.getAPI(messageContext)).thenReturn(api);
    TreeMap transportHeaders = new TreeMap();
    transportHeaders.put(APIMgtGatewayConstants.INTERNAL_KEY, internalKey);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(transportHeaders);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET");
    Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/resource");
    OpenAPI openAPI = Mockito.mock(OpenAPI.class);
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.OPEN_API_OBJECT)).thenReturn(openAPI);
    PowerMockito.when(OpenAPIUtils.getResourceThrottlingTier(openAPI, messageContext)).thenReturn("GOLD");
    PowerMockito.when(GatewayUtils.getTenantDomain()).thenReturn("carbon.super");
    Cache internalKeyCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getGatewayInternalKeyCache()).thenReturn(internalKeyCache);
    Mockito.when(internalKeyCache.get("28f8d7b0-9e62-4341-bf17-094453d5ffa4")).thenReturn(null);
    Cache internalKeyDataCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getGatewayInternalKeyDataCache()).thenReturn(internalKeyDataCache);
    Cache invalidCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getInvalidGatewayInternalKeyCache()).thenReturn(invalidCache);
    Mockito.when(invalidCache.get("28f8d7b0-9e62-4341-bf17-094453d5ffa4")).thenReturn(null);
    String cacheKey = GatewayUtils.getAccessTokenCacheKey("28f8d7b0-9e62-4341-bf17-094453d5ffa4", "/api1/1.0.0", "1.0.0", "/resource", "GET");
    JSONObject subscribedAPI = Mockito.mock(JSONObject.class);
    PowerMockito.when(GatewayUtils.verifyTokenSignature(Mockito.any(SignedJWT.class), Mockito.anyString())).thenReturn(false);
    PowerMockito.when(GatewayUtils.isJwtTokenExpired(signedJWT.getJWTClaimsSet())).thenReturn(true);
    PowerMockito.when(GatewayUtils.validateAPISubscription("/api1/1.0.0", "1.0.0", signedJWT.getJWTClaimsSet(), internalKey.split("\\."), false)).thenReturn(subscribedAPI);
    AuthenticationContext authenticationContext = Mockito.mock(AuthenticationContext.class);
    PowerMockito.when(GatewayUtils.generateAuthenticationContext("28f8d7b0-9e62-4341-bf17-094453d5ffa4", signedJWT.getJWTClaimsSet(), subscribedAPI, api.getApiTier())).thenReturn(authenticationContext);
    PowerMockito.doNothing().when(APISecurityUtils.class, "setAuthenticationContext", messageContext, authenticationContext);
    AuthenticationResponse authenticate = internalAPIKeyAuthenticator.authenticate(messageContext);
    Assert.assertNotNull(authenticate);
    Assert.assertTrue(authenticate.isMandatoryAuthentication());
    Assert.assertFalse(authenticate.isAuthenticated());
    Assert.assertFalse(authenticate.isContinueToNextAuthenticator());
    Assert.assertEquals(authenticate.getErrorCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS);
    Assert.assertEquals(authenticate.getErrorMessage(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
    Mockito.verify(internalKeyCache, Mockito.times(1)).get("28f8d7b0-9e62-4341-bf17-094453d5ffa4");
    Mockito.verify(invalidCache, Mockito.times(1)).get("28f8d7b0-9e62-4341-bf17-094453d5ffa4");
    Mockito.verify(internalKeyCache, Mockito.times(0)).put("28f8d7b0-9e62-4341-bf17-094453d5ffa4", "carbon.super");
    Mockito.verify(invalidCache, Mockito.times(1)).put("28f8d7b0-9e62-4341-bf17-094453d5ffa4", "carbon.super");
    Mockito.verify(internalKeyDataCache, Mockito.times(0)).put(Mockito.anyString(), Mockito.any(AuthenticationContext.class));
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) SignedJWT(com.nimbusds.jwt.SignedJWT) TreeMap(java.util.TreeMap) AuthenticationResponse(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse) JSONObject(net.minidev.json.JSONObject) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) OpenAPI(io.swagger.v3.oas.models.OpenAPI) API(org.wso2.carbon.apimgt.keymgt.model.entity.API) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Cache(javax.cache.Cache) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 20 with AuthenticationResponse

use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse in project carbon-apimgt by wso2.

the class InternalAPIKeyAuthenticatorTest method testAuthenticate.

@Test
public void testAuthenticate() throws Exception {
    PowerMockito.when(GatewayUtils.isInternalKey(Mockito.any(JWTClaimsSet.class))).thenReturn(true);
    InternalAPIKeyAuthenticator internalAPIKeyAuthenticator = new InternalAPIKeyAuthenticator(APIMgtGatewayConstants.INTERNAL_KEY);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1/1.0.0");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0.0");
    API api = new API();
    PowerMockito.when(GatewayUtils.getAPI(messageContext)).thenReturn(api);
    TreeMap transportHeaders = new TreeMap();
    transportHeaders.put(APIMgtGatewayConstants.INTERNAL_KEY, internalKey);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(transportHeaders);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET");
    Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/resource");
    OpenAPI openAPI = Mockito.mock(OpenAPI.class);
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.OPEN_API_OBJECT)).thenReturn(openAPI);
    PowerMockito.when(OpenAPIUtils.getResourceThrottlingTier(openAPI, messageContext)).thenReturn("GOLD");
    PowerMockito.when(GatewayUtils.getTenantDomain()).thenReturn("carbon.super");
    Cache internalKeyCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getGatewayInternalKeyCache()).thenReturn(internalKeyCache);
    Mockito.when(internalKeyCache.get("28f8d7b0-9e62-4341-bf17-094453d5ffa4")).thenReturn("carbon.super");
    Cache internalKeyDataCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getGatewayInternalKeyDataCache()).thenReturn(internalKeyDataCache);
    JWTTokenPayloadInfo jwtTokenPayloadInfo = new JWTTokenPayloadInfo();
    jwtTokenPayloadInfo.setPayload(signedJWT.getJWTClaimsSet());
    jwtTokenPayloadInfo.setAccessToken(internalKey);
    String cacheKey = GatewayUtils.getAccessTokenCacheKey("28f8d7b0-9e62-4341-bf17-094453d5ffa4", "/api1/1.0.0", "1.0.0", "/resource", "GET");
    JSONObject subscribedAPI = Mockito.mock(JSONObject.class);
    Mockito.when(internalKeyDataCache.get(cacheKey)).thenReturn(jwtTokenPayloadInfo);
    PowerMockito.when(GatewayUtils.isJwtTokenExpired(signedJWT.getJWTClaimsSet())).thenReturn(false);
    PowerMockito.when(GatewayUtils.validateAPISubscription("/api1/1.0.0", "1.0.0", signedJWT.getJWTClaimsSet(), internalKey.split("\\."), false)).thenReturn(subscribedAPI);
    AuthenticationContext authenticationContext = Mockito.mock(AuthenticationContext.class);
    PowerMockito.when(GatewayUtils.generateAuthenticationContext("28f8d7b0-9e62-4341-bf17-094453d5ffa4", signedJWT.getJWTClaimsSet(), subscribedAPI, api.getApiTier())).thenReturn(authenticationContext);
    PowerMockito.doNothing().when(APISecurityUtils.class, "setAuthenticationContext", messageContext, authenticationContext);
    AuthenticationResponse authenticate = internalAPIKeyAuthenticator.authenticate(messageContext);
    Assert.assertNotNull(authenticate);
    Assert.assertTrue(authenticate.isMandatoryAuthentication());
    Assert.assertTrue(authenticate.isAuthenticated());
    Assert.assertFalse(authenticate.isContinueToNextAuthenticator());
    Assert.assertEquals(authenticate.getErrorCode(), 0);
    Assert.assertNull(authenticate.getErrorMessage());
}
Also used : JWTTokenPayloadInfo(org.wso2.carbon.apimgt.gateway.dto.JWTTokenPayloadInfo) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) TreeMap(java.util.TreeMap) AuthenticationResponse(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse) JSONObject(net.minidev.json.JSONObject) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) OpenAPI(io.swagger.v3.oas.models.OpenAPI) API(org.wso2.carbon.apimgt.keymgt.model.entity.API) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Cache(javax.cache.Cache) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

AuthenticationResponse (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse)27 Test (org.junit.Test)22 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)22 TreeMap (java.util.TreeMap)21 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)21 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)17 OpenAPI (io.swagger.v3.oas.models.OpenAPI)17 MessageContext (org.apache.synapse.MessageContext)16 API (org.wso2.carbon.apimgt.keymgt.model.entity.API)16 AuthenticationContext (org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext)12 Cache (javax.cache.Cache)9 JSONObject (net.minidev.json.JSONObject)9 SignedJWT (com.nimbusds.jwt.SignedJWT)8 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)5 ArrayList (java.util.ArrayList)4 JWTTokenPayloadInfo (org.wso2.carbon.apimgt.gateway.dto.JWTTokenPayloadInfo)4 ParseException (java.text.ParseException)3 VerbInfoDTO (org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO)3 JWSHeader (com.nimbusds.jose.JWSHeader)2 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)2