Search in sources :

Example 1 with BasicAuthAuthenticator

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

the class BasicAuthAuthenticatorTestCase method testAuthenticate.

@Test
public void testAuthenticate() throws Exception {
    final String authorizationHttpHeader = "Basic YWRtaW46YWRtaW4=";
    final String authorizationHttpHeader1 = "DummyHeader YWRtaW46YWRtaW4=";
    HTTPCarbonMessage carbonMessage = Mockito.mock(HTTPCarbonMessage.class);
    Request requestObj = new Request(carbonMessage);
    try {
        PowerMockito.whenNew(Request.class).withArguments(carbonMessage).thenReturn(requestObj);
    } catch (Exception e) {
        throw new APIMgtSecurityException("Error while mocking Request Object ", e);
    }
    try {
        BasicAuthAuthenticator basicAuthAuthenticator = new BasicAuthAuthenticator();
        basicAuthAuthenticator.authenticate(requestObj, null, null);
    } catch (APIMgtSecurityException e) {
        Assert.assertEquals(e.getMessage(), "Missing Authorization header in the request.`");
    }
    when(requestObj.getHeader(RestApiConstants.AUTHORIZATION_HTTP_HEADER)).thenReturn(authorizationHttpHeader1);
    Response responseObj = Mockito.mock(Response.class);
    ServiceMethodInfo serviceMethodInfoObj = Mockito.mock(ServiceMethodInfo.class);
    try {
        BasicAuthAuthenticator basicAuthAuthenticator = new BasicAuthAuthenticator();
        basicAuthAuthenticator.authenticate(requestObj, responseObj, serviceMethodInfoObj);
    } catch (APIMgtSecurityException e) {
        Assert.assertEquals(e.getMessage(), "Missing 'Authorization : Basic' header in the request.`");
    }
    when(requestObj.getHeader(RestApiConstants.AUTHORIZATION_HTTP_HEADER)).thenReturn(authorizationHttpHeader);
    BasicAuthAuthenticator basicAuthAuthenticator = new BasicAuthAuthenticator();
    boolean isAuthenticated = basicAuthAuthenticator.authenticate(requestObj, responseObj, serviceMethodInfoObj);
    if (isAuthenticated) {
        Assert.assertEquals(isAuthenticated, true);
    } else {
        Assert.assertEquals(isAuthenticated, false);
    }
}
Also used : Response(org.wso2.msf4j.Response) HTTPCarbonMessage(org.wso2.transport.http.netty.message.HTTPCarbonMessage) BasicAuthAuthenticator(org.wso2.carbon.apimgt.rest.api.common.impl.BasicAuthAuthenticator) APIMgtSecurityException(org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException) ServiceMethodInfo(org.wso2.msf4j.ServiceMethodInfo) Request(org.wso2.msf4j.Request) APIMgtSecurityException(org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException) Test(org.testng.annotations.Test)

Example 2 with BasicAuthAuthenticator

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

the class BasicAuthAuthenticatorTest method setup.

@Before
public void setup() throws Exception {
    PowerMockito.mockStatic(OpenAPIUtils.class);
    PowerMockito.when(OpenAPIUtils.getResourceAuthenticationScheme(Mockito.any(), Mockito.any())).thenReturn(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN);
    messageContext = Mockito.mock(Axis2MessageContext.class);
    axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(axis2MsgCntxt.getProperty(APIMgtGatewayConstants.REQUEST_RECEIVED_TIME)).thenReturn("1506576365");
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when((messageContext.getProperty(APIMgtGatewayConstants.OPEN_API_OBJECT))).thenReturn(Mockito.mock(OpenAPI.class));
    basicAuthAuthenticator = new BasicAuthAuthenticator(CUSTOM_AUTH_HEADER, true, UNLIMITED_THROTTLE_POLICY);
    BasicAuthCredentialValidator basicAuthCredentialValidator = Mockito.mock(BasicAuthCredentialValidator.class);
    BasicAuthValidationInfoDTO basicAuthValidationInfoDTO = new BasicAuthValidationInfoDTO();
    Mockito.when(basicAuthCredentialValidator.validate(Mockito.anyString(), Mockito.anyString())).thenAnswer(invocationOnMock -> {
        Object argument1 = invocationOnMock.getArguments()[0];
        Object argument2 = invocationOnMock.getArguments()[1];
        if ((argument1.equals("test_username@carbon.super") || argument1.equals("test_username_blocked@carbon.super")) && argument2.equals("test_password")) {
            basicAuthValidationInfoDTO.setAuthenticated(true);
            basicAuthValidationInfoDTO.setHashedPassword("hashed_test_password");
            if ("test_username@carbon.super".equals(argument1)) {
                basicAuthValidationInfoDTO.setDomainQualifiedUsername("test_username@carbon.super");
            } else if ("test_username_blocked@carbon.super".equals(argument1)) {
                basicAuthValidationInfoDTO.setDomainQualifiedUsername("test_username_blocked@carbon.super");
            }
            String[] userRoleList = { "roleQ", "roleX" };
            basicAuthValidationInfoDTO.setUserRoleList(userRoleList);
            return basicAuthValidationInfoDTO;
        }
        return basicAuthValidationInfoDTO;
    });
    Mockito.when(basicAuthCredentialValidator.validateScopes(Mockito.anyString(), Mockito.any(OpenAPI.class), Mockito.any(MessageContext.class), Mockito.anyObject())).thenAnswer(invocationOnMock -> {
        Object argument = invocationOnMock.getArguments()[0];
        if (argument.equals("test_username@carbon.super")) {
            return true;
        } else if (argument.equals("test_username_blocked@carbon.super")) {
            throw new APISecurityException(APISecurityConstants.INVALID_SCOPE, "Scope validation failed");
        }
        return false;
    });
    PowerMockito.whenNew(BasicAuthCredentialValidator.class).withNoArguments().thenReturn(basicAuthCredentialValidator);
    Mockito.when(messageContext.getProperty(BasicAuthAuthenticator.PUBLISHER_TENANT_DOMAIN)).thenReturn("carbon.super");
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) BasicAuthValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.BasicAuthValidationInfoDTO) 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) Before(org.junit.Before)

Example 3 with BasicAuthAuthenticator

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

the class APIAuthenticationHandler method initializeAuthenticators.

@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "LEST_LOST_EXCEPTION_STACK_TRACE", justification = "The exception needs to thrown for fault sequence invocation")
protected void initializeAuthenticators() {
    isAuthenticatorsInitialized = true;
    boolean isOAuthProtected = false;
    boolean isMutualSSLProtected = false;
    boolean isBasicAuthProtected = false;
    boolean isApiKeyProtected = false;
    boolean isMutualSSLMandatory = false;
    boolean isOAuthBasicAuthMandatory = false;
    // Set security conditions
    if (apiSecurity == null) {
        isOAuthProtected = true;
    } else {
        String[] apiSecurityLevels = apiSecurity.split(",");
        for (String apiSecurityLevel : apiSecurityLevels) {
            if (apiSecurityLevel.trim().equalsIgnoreCase(APIConstants.DEFAULT_API_SECURITY_OAUTH2)) {
                isOAuthProtected = true;
            } else if (apiSecurityLevel.trim().equalsIgnoreCase(APIConstants.API_SECURITY_MUTUAL_SSL)) {
                isMutualSSLProtected = true;
            } else if (apiSecurityLevel.trim().equalsIgnoreCase(APIConstants.API_SECURITY_BASIC_AUTH)) {
                isBasicAuthProtected = true;
            } else if (apiSecurityLevel.trim().equalsIgnoreCase(APIConstants.API_SECURITY_MUTUAL_SSL_MANDATORY)) {
                isMutualSSLMandatory = true;
            } else if (apiSecurityLevel.trim().equalsIgnoreCase(APIConstants.API_SECURITY_OAUTH_BASIC_AUTH_API_KEY_MANDATORY)) {
                isOAuthBasicAuthMandatory = true;
            } else if (apiSecurityLevel.trim().equalsIgnoreCase((APIConstants.API_SECURITY_API_KEY))) {
                isApiKeyProtected = true;
            }
        }
    }
    if (!isMutualSSLProtected && !isOAuthBasicAuthMandatory) {
        isOAuthBasicAuthMandatory = true;
    }
    if (!isBasicAuthProtected && !isOAuthProtected && !isMutualSSLMandatory && !isApiKeyProtected) {
        isMutualSSLMandatory = true;
    }
    // Set authenticators
    if (isMutualSSLProtected) {
        Authenticator authenticator = new MutualSSLAuthenticator(apiLevelPolicy, isMutualSSLMandatory, certificateInformation);
        authenticator.init(synapseEnvironment);
        authenticators.add(authenticator);
    }
    if (isOAuthProtected) {
        Authenticator authenticator = new OAuthAuthenticator(authorizationHeader, isOAuthBasicAuthMandatory, removeOAuthHeadersFromOutMessage);
        authenticator.init(synapseEnvironment);
        authenticators.add(authenticator);
    }
    if (isBasicAuthProtected) {
        Authenticator authenticator = new BasicAuthAuthenticator(authorizationHeader, isOAuthBasicAuthMandatory, apiLevelPolicy);
        authenticator.init(synapseEnvironment);
        authenticators.add(authenticator);
    }
    if (isApiKeyProtected) {
        Authenticator authenticator = new ApiKeyAuthenticator(APIConstants.API_KEY_HEADER_QUERY_PARAM, apiLevelPolicy, isOAuthBasicAuthMandatory);
        authenticator.init(synapseEnvironment);
        authenticators.add(authenticator);
    }
    Authenticator authenticator = new InternalAPIKeyAuthenticator(APIMgtGatewayConstants.INTERNAL_KEY);
    authenticator.init(synapseEnvironment);
    authenticators.add(authenticator);
    authenticators.sort(new Comparator<Authenticator>() {

        @Override
        public int compare(Authenticator o1, Authenticator o2) {
            return (o1.getPriority() - o2.getPriority());
        }
    });
}
Also used : InternalAPIKeyAuthenticator(org.wso2.carbon.apimgt.gateway.handlers.security.authenticator.InternalAPIKeyAuthenticator) MutualSSLAuthenticator(org.wso2.carbon.apimgt.gateway.handlers.security.authenticator.MutualSSLAuthenticator) BasicAuthAuthenticator(org.wso2.carbon.apimgt.gateway.handlers.security.basicauth.BasicAuthAuthenticator) OAuthAuthenticator(org.wso2.carbon.apimgt.gateway.handlers.security.oauth.OAuthAuthenticator) OAuthAuthenticator(org.wso2.carbon.apimgt.gateway.handlers.security.oauth.OAuthAuthenticator) BasicAuthAuthenticator(org.wso2.carbon.apimgt.gateway.handlers.security.basicauth.BasicAuthAuthenticator) InternalAPIKeyAuthenticator(org.wso2.carbon.apimgt.gateway.handlers.security.authenticator.InternalAPIKeyAuthenticator) MutualSSLAuthenticator(org.wso2.carbon.apimgt.gateway.handlers.security.authenticator.MutualSSLAuthenticator) ApiKeyAuthenticator(org.wso2.carbon.apimgt.gateway.handlers.security.apikey.ApiKeyAuthenticator) ApiKeyAuthenticator(org.wso2.carbon.apimgt.gateway.handlers.security.apikey.ApiKeyAuthenticator)

Aggregations

OpenAPI (io.swagger.v3.oas.models.OpenAPI)1 MessageContext (org.apache.synapse.MessageContext)1 Axis2MessageContext (org.apache.synapse.core.axis2.Axis2MessageContext)1 Before (org.junit.Before)1 Test (org.testng.annotations.Test)1 APISecurityException (org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException)1 ApiKeyAuthenticator (org.wso2.carbon.apimgt.gateway.handlers.security.apikey.ApiKeyAuthenticator)1 InternalAPIKeyAuthenticator (org.wso2.carbon.apimgt.gateway.handlers.security.authenticator.InternalAPIKeyAuthenticator)1 MutualSSLAuthenticator (org.wso2.carbon.apimgt.gateway.handlers.security.authenticator.MutualSSLAuthenticator)1 BasicAuthAuthenticator (org.wso2.carbon.apimgt.gateway.handlers.security.basicauth.BasicAuthAuthenticator)1 OAuthAuthenticator (org.wso2.carbon.apimgt.gateway.handlers.security.oauth.OAuthAuthenticator)1 BasicAuthValidationInfoDTO (org.wso2.carbon.apimgt.impl.dto.BasicAuthValidationInfoDTO)1 APIMgtSecurityException (org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException)1 BasicAuthAuthenticator (org.wso2.carbon.apimgt.rest.api.common.impl.BasicAuthAuthenticator)1 Request (org.wso2.msf4j.Request)1 Response (org.wso2.msf4j.Response)1 ServiceMethodInfo (org.wso2.msf4j.ServiceMethodInfo)1 HTTPCarbonMessage (org.wso2.transport.http.netty.message.HTTPCarbonMessage)1