Adding more test cases for webapp.authenticator.framework

merge-requests/1/head
megala21 7 years ago
parent 9c6f15506d
commit cbaace4e93

@ -20,7 +20,7 @@ package org.wso2.carbon.device.mgt.extensions.device.type.template;
import org.h2.jdbcx.JdbcDataSource; import org.h2.jdbcx.JdbcDataSource;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.testng.annotations.BeforeTest; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
@ -31,11 +31,7 @@ import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceD
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration; import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Properties; import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Properties;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.exception.DeviceTypeConfigurationException; import org.wso2.carbon.device.mgt.extensions.device.type.template.config.exception.DeviceTypeConfigurationException;
import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceDAODefinition; import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.*;
import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceTypeDAOHandler;
import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOImpl;
import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOManager;
import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.PropertyBasedPluginDAOImpl;
import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeDeployerPayloadException; import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeDeployerPayloadException;
import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException; import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException;
import org.wso2.carbon.device.mgt.extensions.utils.Utils; import org.wso2.carbon.device.mgt.extensions.utils.Utils;
@ -69,7 +65,7 @@ public class DeviceTypeManagerNegativeTest {
private PropertyBasedPluginDAOImpl propertyBasedPluginDAO; private PropertyBasedPluginDAOImpl propertyBasedPluginDAO;
private Device sampleDevice; private Device sampleDevice;
@BeforeTest @BeforeClass
public void setup() public void setup()
throws SAXException, JAXBException, ParserConfigurationException, DeviceTypeConfigurationException, throws SAXException, JAXBException, ParserConfigurationException, DeviceTypeConfigurationException,
IOException, NoSuchFieldException, IllegalAccessException { IOException, NoSuchFieldException, IllegalAccessException {

@ -21,25 +21,18 @@ package org.wso2.carbon.device.mgt.extensions.device.type.template;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.testng.Assert; import org.testng.Assert;
import org.testng.annotations.BeforeTest; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig;
import org.wso2.carbon.device.mgt.common.InitialOperationConfig; import org.wso2.carbon.device.mgt.common.InitialOperationConfig;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.ProvisioningConfig; import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceStatusTaskConfiguration; import org.wso2.carbon.device.mgt.extensions.device.type.template.config.*;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.PolicyMonitoring;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.PullNotificationSubscriberConfig;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.PushNotificationProvider;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.TaskConfiguration;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.exception.DeviceTypeConfigurationException; import org.wso2.carbon.device.mgt.extensions.device.type.template.config.exception.DeviceTypeConfigurationException;
import org.wso2.carbon.device.mgt.extensions.utils.Utils; import org.wso2.carbon.device.mgt.extensions.utils.Utils;
import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.exceptions.RegistryException;
@ -75,7 +68,7 @@ public class DeviceTypeManagerServiceTest {
private Method setPolicyMonitoringManager; private Method setPolicyMonitoringManager;
private Method setPullNotificationSubscriber; private Method setPullNotificationSubscriber;
@BeforeTest @BeforeClass
public void setup() throws NoSuchMethodException, SAXException, JAXBException, ParserConfigurationException, public void setup() throws NoSuchMethodException, SAXException, JAXBException, ParserConfigurationException,
DeviceTypeConfigurationException, IOException, NoSuchFieldException, IllegalAccessException, DeviceTypeConfigurationException, IOException, NoSuchFieldException, IllegalAccessException,
DeviceManagementException, RegistryException { DeviceManagementException, RegistryException {

@ -20,7 +20,7 @@ package org.wso2.carbon.device.mgt.extensions.device.type.template;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.testng.Assert; import org.testng.Assert;
import org.testng.annotations.BeforeTest; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
@ -30,12 +30,7 @@ import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceD
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration; import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Properties; import org.wso2.carbon.device.mgt.extensions.device.type.template.config.Properties;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.exception.DeviceTypeConfigurationException; import org.wso2.carbon.device.mgt.extensions.device.type.template.config.exception.DeviceTypeConfigurationException;
import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceDAODefinition; import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.*;
import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceTypeDAOHandler;
import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOImpl;
import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOManager;
import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.PluginDAO;
import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.PropertyBasedPluginDAOImpl;
import org.wso2.carbon.device.mgt.extensions.utils.Utils; import org.wso2.carbon.device.mgt.extensions.utils.Utils;
import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
@ -73,7 +68,7 @@ public class DeviceTypeManagerTest {
private String[] customDeviceTypeProperties = {"custom_property", "custom_property2"}; private String[] customDeviceTypeProperties = {"custom_property", "custom_property2"};
private final String SQL_FOLDER = "sql-files" + File.separator; private final String SQL_FOLDER = "sql-files" + File.separator;
@BeforeTest(description = "Mocking the classes for testing") @BeforeClass(description = "Mocking the classes for testing")
public void setup() throws NoSuchFieldException, IllegalAccessException, IOException, SQLException, SAXException, public void setup() throws NoSuchFieldException, IllegalAccessException, IOException, SQLException, SAXException,
ParserConfigurationException, DeviceTypeConfigurationException, JAXBException { ParserConfigurationException, DeviceTypeConfigurationException, JAXBException {
ClassLoader classLoader = getClass().getClassLoader(); ClassLoader classLoader = getClass().getClassLoader();

@ -19,7 +19,7 @@
package org.wso2.carbon.device.mgt.extensions.device.type.template; package org.wso2.carbon.device.mgt.extensions.device.type.template;
import org.testng.Assert; import org.testng.Assert;
import org.testng.annotations.BeforeTest; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
@ -60,7 +60,7 @@ public class HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest {
private String androidSenseDeviceType = "androidsense"; private String androidSenseDeviceType = "androidsense";
private DeviceManagementService generatedDeviceManagementService; private DeviceManagementService generatedDeviceManagementService;
@BeforeTest @BeforeClass
public void setup() throws RegistryException, IOException, SAXException, ParserConfigurationException, public void setup() throws RegistryException, IOException, SAXException, ParserConfigurationException,
DeviceTypeConfigurationException, JAXBException { DeviceTypeConfigurationException, JAXBException {
createSampleDeviceTypeMetaDefinition(); createSampleDeviceTypeMetaDefinition();

@ -20,7 +20,7 @@
package org.wso2.carbon.device.mgt.extensions.utils; package org.wso2.carbon.device.mgt.extensions.utils;
import org.testng.Assert; import org.testng.Assert;
import org.testng.annotations.BeforeTest; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
@ -51,7 +51,7 @@ import java.util.List;
public class UtilsTest { public class UtilsTest {
private FileSystemBasedLicenseManager fileSystemBasedLicenseManager; private FileSystemBasedLicenseManager fileSystemBasedLicenseManager;
@BeforeTest @BeforeClass
public void setup() { public void setup() {
fileSystemBasedLicenseManager = new FileSystemBasedLicenseManager(); fileSystemBasedLicenseManager = new FileSystemBasedLicenseManager();
} }

@ -248,6 +248,11 @@
<artifactId>h2-database-engine</artifactId> <artifactId>h2-database-engine</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
</project> </project>

@ -97,44 +97,6 @@ public class OAuthTokenValidationStubFactory implements PoolableObjectFactory {
return connectionManager; return connectionManager;
} }
/**
* Creates an instance of PoolingHttpClientConnectionManager using HttpClient 4.x APIs
*
* @param properties Properties to configure PoolingHttpClientConnectionManager
* @return An instance of properly configured PoolingHttpClientConnectionManager
*/
private HttpClientConnectionManager createClientConnectionManager(Properties properties) {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
if (properties != null) {
String maxConnectionsPerHostParam = properties.getProperty("MaxConnectionsPerHost");
if (maxConnectionsPerHostParam == null || maxConnectionsPerHostParam.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("MaxConnectionsPerHost parameter is not explicitly defined. Therefore, the default, " +
"which is 2, will be used");
}
} else {
connectionManager.setDefaultMaxPerRoute(Integer.parseInt(maxConnectionsPerHostParam));
}
String maxTotalConnectionsParam = properties.getProperty("MaxTotalConnections");
if (maxTotalConnectionsParam == null || maxTotalConnectionsParam.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("MaxTotalConnections parameter is not explicitly defined. Therefore, the default, " +
"which is 10, will be used");
}
} else {
connectionManager.setMaxTotal(Integer.parseInt(maxTotalConnectionsParam));
}
} else {
if (log.isDebugEnabled()) {
log.debug("Properties, i.e. MaxTotalConnections/MaxConnectionsPerHost, required to tune the " +
"HttpClient used in OAuth token validation service stub instances are not provided. " +
"Therefore, the defaults, 2/10 respectively, will be used");
}
}
return connectionManager;
}
@Override @Override
public Object makeObject() throws Exception { public Object makeObject() throws Exception {
return this.createStub(); return this.createStub();

@ -134,10 +134,10 @@ public class Utils {
authenticationInfo.setUsername(username); authenticationInfo.setUsername(username);
authenticationInfo.setTenantDomain(tenantDomain); authenticationInfo.setTenantDomain(tenantDomain);
authenticationInfo.setTenantId(getTenantIdOFUser(username + "@" + tenantDomain)); authenticationInfo.setTenantId(getTenantIdOFUser(username + "@" + tenantDomain));
if (oAuthValidationResponse.isValid()) authenticationInfo.setStatus(WebappAuthenticator.Status.CONTINUE);
authenticationInfo.setStatus(WebappAuthenticator.Status.CONTINUE);
} else { } else {
authenticationInfo.setMessage(oAuthValidationResponse.getErrorMsg()); authenticationInfo.setMessage(oAuthValidationResponse.getErrorMsg());
authenticationInfo.setStatus(WebappAuthenticator.Status.FAILURE);
} }
return authenticationInfo; return authenticationInfo;
} }

@ -25,16 +25,25 @@ import org.apache.catalina.core.StandardContext;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.http.MimeHeaders; import org.apache.tomcat.util.http.MimeHeaders;
import org.mockito.Mockito;
import org.testng.Assert; import org.testng.Assert;
import org.testng.annotations.BeforeTest; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService;
import org.wso2.carbon.identity.oauth2.dto.OAuth2ClientApplicationDTO;
import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo;
import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuth2TokenValidator; import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuth2TokenValidator;
import org.wso2.carbon.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder;
import org.wso2.carbon.webapp.authenticator.framework.util.TestInputBuffer; import org.wso2.carbon.webapp.authenticator.framework.util.TestInputBuffer;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL; import java.net.URL;
import java.util.Properties; import java.util.Properties;
@ -45,13 +54,28 @@ public class BSTAuthenticatorTest {
private BSTAuthenticator bstAuthenticator; private BSTAuthenticator bstAuthenticator;
private Properties properties; private Properties properties;
private Field headersField; private Field headersField;
private OAuth2TokenValidationService oAuth2TokenValidationService;
private OAuth2ClientApplicationDTO oAuth2ClientApplicationDTO;
@BeforeTest @BeforeClass
public void init() throws NoSuchFieldException { public void init() throws NoSuchFieldException {
bstAuthenticator = new BSTAuthenticator(); bstAuthenticator = new BSTAuthenticator();
properties = new Properties(); properties = new Properties();
headersField = org.apache.coyote.Request.class.getDeclaredField("headers"); headersField = org.apache.coyote.Request.class.getDeclaredField("headers");
headersField.setAccessible(true); headersField.setAccessible(true);
oAuth2TokenValidationService = Mockito
.mock(OAuth2TokenValidationService.class, Mockito.CALLS_REAL_METHODS);
oAuth2ClientApplicationDTO = Mockito
.mock(OAuth2ClientApplicationDTO.class, Mockito.CALLS_REAL_METHODS);
OAuth2TokenValidationResponseDTO authorizedValidationResponse = new OAuth2TokenValidationResponseDTO();
authorizedValidationResponse.setValid(true);
authorizedValidationResponse.setAuthorizedUser("admin@" + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
Mockito.doReturn(oAuth2ClientApplicationDTO).when(oAuth2TokenValidationService)
.findOAuthConsumerIfTokenIsValid(Mockito.any());
oAuth2ClientApplicationDTO.setAccessTokenValidationResponse(authorizedValidationResponse);
AuthenticatorFrameworkDataHolder.getInstance().setOAuth2TokenValidationService(oAuth2TokenValidationService);
} }
@Test(description = "This test case is used to test the behaviour of BST Authenticator when the properties are " @Test(description = "This test case is used to test the behaviour of BST Authenticator when the properties are "
@ -104,6 +128,18 @@ public class BSTAuthenticatorTest {
+ "parameters."); + "parameters.");
} }
@Test(description = "This method tests the get methods of the BST Authenticator",
dependsOnMethods = {"testInitWithRemote"})
public void testGetterMethods() {
Assert.assertNotNull(bstAuthenticator.getProperties(), "Retrieval of properties from BSTAuthenticator failed");
Assert.assertNotNull(bstAuthenticator.getProperty("Password"),
"Retrieval of added property failed in " + "BSTAuthenticator");
Assert.assertNull(bstAuthenticator.getProperty("test"),
"Retrieval of property test is successful, which is " + "never added");
Assert.assertEquals(bstAuthenticator.getName(), "BSTAuthenticator",
"Name returned by BSTAuthenticator does" + " not match.");
}
@Test(description = "This test case tests the canHandle method of the BSTAuthenticator under faulty conditions") @Test(description = "This test case tests the canHandle method of the BSTAuthenticator under faulty conditions")
public void testCanHandleWithFalseConditions() throws IllegalAccessException { public void testCanHandleWithFalseConditions() throws IllegalAccessException {
Request request = new Request(); Request request = new Request();
@ -148,20 +184,36 @@ public class BSTAuthenticatorTest {
AuthenticationInfo authenticationInfo = bstAuthenticator.authenticate(request, null); AuthenticationInfo authenticationInfo = bstAuthenticator.authenticate(request, null);
Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.CONTINUE, Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.CONTINUE,
"Authentication status of authentication info is wrong"); "Authentication status of authentication info is wrong");
Field uriMB = org.apache.coyote.Request.class.getDeclaredField("uriMB");
// coyoteRequest = new org.apache.coyote.Request(); }
@Test(description = "This method tests the authenticate method of BST Authenticator when all the relevant "
+ "details", dependsOnMethods = "testInitWithRemote")
public void testAuthenticate() throws NoSuchFieldException, IllegalAccessException, IOException {
Request request = createSoapRequest("CorrectBST.xml");
org.apache.coyote.Request coyoteRequest = request.getCoyoteRequest();
Field uriMB = org.apache.coyote.Request.class.getDeclaredField("uriMB");
uriMB.setAccessible(true); uriMB.setAccessible(true);
MessageBytes bytes = MessageBytes.newInstance(); MessageBytes bytes = MessageBytes.newInstance();
bytes.setString(""); bytes.setString("test");
uriMB.set(coyoteRequest, bytes); uriMB.set(coyoteRequest, bytes);
request.setCoyoteRequest(coyoteRequest); request.setCoyoteRequest(coyoteRequest);
authenticationInfo = bstAuthenticator.authenticate(request, null); bstAuthenticator.canHandle(request);
AuthenticationInfo authenticationInfo = bstAuthenticator.authenticate(request, null);
Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.CONTINUE, Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.CONTINUE,
"Authentication status of authentication info is wrong"); "Authentication status of authentication info is wrong");
Assert.assertEquals(authenticationInfo.getUsername(), "admin",
"User name in the authentication info is different than original user");
OAuth2TokenValidationResponseDTO unAuthorizedValidationRespose = new OAuth2TokenValidationResponseDTO();
unAuthorizedValidationRespose.setValid(false);
unAuthorizedValidationRespose.setErrorMsg("User is not authorized");
Mockito.doReturn(oAuth2ClientApplicationDTO).when(oAuth2TokenValidationService)
.findOAuthConsumerIfTokenIsValid(Mockito.any());
oAuth2ClientApplicationDTO.setAccessTokenValidationResponse(unAuthorizedValidationRespose);
AuthenticatorFrameworkDataHolder.getInstance().setOAuth2TokenValidationService(oAuth2TokenValidationService);
authenticationInfo = bstAuthenticator.authenticate(request, null);
Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.FAILURE,
"Un-authorized user " + "got authenticated with BST");
} }
/** /**

@ -26,6 +26,7 @@ import org.apache.commons.codec.EncoderException;
import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.http.MimeHeaders; import org.apache.tomcat.util.http.MimeHeaders;
import org.testng.Assert; import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeTest; import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
@ -51,7 +52,7 @@ public class BasicAuthAuthenticatorTest {
private MessageBytes bytes; private MessageBytes bytes;
private final String BASIC_HEADER = "basic "; private final String BASIC_HEADER = "basic ";
@BeforeTest @BeforeClass
public void init() throws NoSuchFieldException { public void init() throws NoSuchFieldException {
basicAuthAuthenticator = new BasicAuthAuthenticator(); basicAuthAuthenticator = new BasicAuthAuthenticator();
headersField = org.apache.coyote.Request.class.getDeclaredField("headers"); headersField = org.apache.coyote.Request.class.getDeclaredField("headers");

@ -0,0 +1,165 @@
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.webapp.authenticator.framework.authenticator;
import org.apache.catalina.connector.Request;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.http.MimeHeaders;
import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.core.security.AuthenticatorsConfiguration;
import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub;
import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2ClientApplicationDTO;
import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo;
import org.wso2.carbon.webapp.authenticator.framework.BaseWebAppAuthenticatorFrameworkTest;
import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.impl.RemoteOAuthValidator;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
/**
* This is a test case for {@link OAuthAuthenticator}
*/
public class OauthAuthenticatorTest {
private OAuthAuthenticator oAuthAuthenticator;
private final String BEARER_HEADER = "bearer ";
private Field headersField;
private Properties properties;
@BeforeClass
public void setup()
throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Field instance = org.wso2.carbon.core.security.AuthenticatorsConfiguration.class.getDeclaredField("instance");
instance.setAccessible(true);
AuthenticatorsConfiguration authenticatorsConfiguration = Mockito
.mock(AuthenticatorsConfiguration.class, Mockito.CALLS_REAL_METHODS);
Method initialize = AuthenticatorsConfiguration.class.getDeclaredMethod("initialize");
initialize.setAccessible(true);
initialize.invoke(authenticatorsConfiguration);
instance.set(null, authenticatorsConfiguration);
oAuthAuthenticator = new OAuthAuthenticator();
headersField = org.apache.coyote.Request.class.getDeclaredField("headers");
headersField.setAccessible(true);
}
@Test(description = "This method tests the successful execution of init method")
public void testInit() throws NoSuchFieldException, IllegalAccessException {
properties = new Properties();
properties.setProperty("TokenValidationEndpointUrl", "test");
properties.setProperty("Username", "admin");
properties.setProperty("Password", "admin");
properties.setProperty("IsRemote", "true");
properties.setProperty("MaxConnectionsPerHost", "100");
properties.setProperty("MaxTotalConnections", "1000");
Assert.assertNull(oAuthAuthenticator.getProperty("test"),
"OAuth authenticator is returning the properties that were never set");
oAuthAuthenticator.setProperties(properties);
oAuthAuthenticator.init();
Field tokenValidator = OAuthAuthenticator.class.getDeclaredField("tokenValidator");
tokenValidator.setAccessible(true);
Assert.assertNotNull(tokenValidator.get(oAuthAuthenticator), "OauthAuthenticator initialization failed");
Assert.assertEquals(oAuthAuthenticator.getName(), "OAuth", "Name of the OauthAuthenticator does not match");
}
@Test(description = "This method tests the canHandle method of OAuthAuthenticator")
public void testCanHandle() throws IllegalAccessException {
Request request = createOauthRequest(BEARER_HEADER);
Assert.assertTrue(oAuthAuthenticator.canHandle(request),
"The request with the bearer authorization header cannot be handled by OauthAuthenticator");
request = createOauthRequest("test");
Assert.assertFalse(oAuthAuthenticator.canHandle(request),
"The request without bearer authorization header can be handled by OauthAuthenticator");
}
@Test(description = "This method tests the authenticate under different parameters",
dependsOnMethods = {"testInit"})
public void testAuthenticate() throws Exception {
Request request = createOauthRequest(BEARER_HEADER);
Assert.assertEquals(oAuthAuthenticator.authenticate(request, null).getStatus(),
WebappAuthenticator.Status.CONTINUE, "Authentication status mismatched");
request = createOauthRequest(BEARER_HEADER + "abc");
org.apache.coyote.Request coyoteRequest = request.getCoyoteRequest();
Field uriMB = org.apache.coyote.Request.class.getDeclaredField("uriMB");
uriMB.setAccessible(true);
MessageBytes bytes = MessageBytes.newInstance();
bytes.setString("test");
uriMB.set(coyoteRequest, bytes);
request.setCoyoteRequest(coyoteRequest);
Field tokenValidator = OAuthAuthenticator.class.getDeclaredField("tokenValidator");
tokenValidator.setAccessible(true);
GenericObjectPool genericObjectPool = Mockito.mock(GenericObjectPool.class, Mockito.CALLS_REAL_METHODS);
RemoteOAuthValidator remoteOAuthValidator = Mockito
.mock(RemoteOAuthValidator.class, Mockito.CALLS_REAL_METHODS);
tokenValidator.set(oAuthAuthenticator, remoteOAuthValidator);
Field stubs = RemoteOAuthValidator.class.getDeclaredField("stubs");
stubs.setAccessible(true);
stubs.set(remoteOAuthValidator, genericObjectPool);
OAuth2TokenValidationResponseDTO oAuth2TokenValidationResponseDTO = new OAuth2TokenValidationResponseDTO();
oAuth2TokenValidationResponseDTO.setValid(true);
oAuth2TokenValidationResponseDTO.setAuthorizedUser("admin@carbon.super");
OAuth2ClientApplicationDTO oAuth2ClientApplicationDTO = Mockito
.mock(OAuth2ClientApplicationDTO.class, Mockito.CALLS_REAL_METHODS);
Mockito.doReturn(oAuth2TokenValidationResponseDTO).when(oAuth2ClientApplicationDTO)
.getAccessTokenValidationResponse();
OAuth2TokenValidationServiceStub oAuth2TokenValidationServiceStub = Mockito
.mock(OAuth2TokenValidationServiceStub.class, Mockito.CALLS_REAL_METHODS);
Mockito.doReturn(oAuth2ClientApplicationDTO).when(oAuth2TokenValidationServiceStub)
.findOAuthConsumerIfTokenIsValid(Mockito.any());
Mockito.doReturn(oAuth2TokenValidationServiceStub).when(genericObjectPool).borrowObject();
oAuthAuthenticator.canHandle(request);
AuthenticationInfo authenticationInfo = oAuthAuthenticator.authenticate(request, null);
Assert.assertEquals(authenticationInfo.getUsername(), "admin");
}
@Test(description = "This method is used to test getProperty method of the OAuthAuthenticator",
dependsOnMethods = {"testInit"})
public void testGetProperty() {
Assert.assertEquals(oAuthAuthenticator.getProperty("Username"), "admin",
"Username property of " + "OauthAuthenticator is not matching with the assigned one.");
Assert.assertEquals(oAuthAuthenticator.getProperties().size(), properties.size(),
"Property list assigned " + "does not match with retrieved list");
}
/**
* This will create an OAuth request.
*
* @param authorizationHeader Authorization Header
*/
private Request createOauthRequest(String authorizationHeader) throws IllegalAccessException {
Request request = new Request();
org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request();
MimeHeaders mimeHeaders = new MimeHeaders();
MessageBytes bytes = mimeHeaders.addValue(BaseWebAppAuthenticatorFrameworkTest.AUTHORIZATION_HEADER);
bytes.setString(authorizationHeader);
headersField.set(coyoteRequest, mimeHeaders);
request.setCoyoteRequest(coyoteRequest);
return request;
}
}

@ -0,0 +1,68 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<!--
This is the configuration file for Carbon authenticators. All the authenticator related configurations
should go here.
-->
<Authenticators xmlns="http://wso2.org/projects/carbon/authenticators.xml">
<!-- authenticator Configurations for OAuthAuthenticator -->
<Authenticator name="SignedJWTAuthenticator" disabled="false">
<Priority>5</Priority>
</Authenticator>
<!-- authenticator Configurations for TokenUIAuthenticator -->
<Authenticator name="TokenUIAuthenticator" disabled="false">
<Priority>5</Priority>
</Authenticator>
<!-- Authenticator Configurations for MutualSSLAuthenticator -->
<!--Authenticator name="MutualSSLAuthenticator" disabled="false">
<Priority>5</Priority>
<Config>
<Parameter name="UsernameHeader">UserName</Parameter>
<Parameter name="WhiteListEnabled">false</Parameter>
<Parameter name="WhiteList"/>
</Config>
</Authenticator-->
<!-- authenticator Configurations for SAML2SSOAuthenticator -->
<Authenticator name="SAML2SSOAuthenticator" disabled="true">
<Priority>10</Priority>
<Config>
<Parameter name="LoginPage">/carbon/admin/login.jsp</Parameter>
<Parameter name="ServiceProviderID">carbonServer</Parameter>
<Parameter name="IdentityProviderSSOServiceURL">https://localhost:9443/samlsso</Parameter>
<Parameter name="NameIDPolicyFormat">urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified</Parameter>
</Config>
<!-- If this authenticator should skip any URI from authentication, specify it under "SkipAuthentication"
<SkipAuthentication>
<UrlContains></UrlContains>
</SkipAuthentication> -->
<!-- If this authenticator should skip any URI from session validation, specify it under "SkipAuthentication
<SkipSessionValidation>
<UrlContains></UrlContains>
</SkipSessionValidation> -->
</Authenticator>
</Authenticators>

@ -30,6 +30,7 @@
<class name="org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticatorRepositoryTest"/> <class name="org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticatorRepositoryTest"/>
<class name="org.wso2.carbon.webapp.authenticator.framework.authenticator.BasicAuthAuthenticatorTest" /> <class name="org.wso2.carbon.webapp.authenticator.framework.authenticator.BasicAuthAuthenticatorTest" />
<class name="org.wso2.carbon.webapp.authenticator.framework.authenticator.BSTAuthenticatorTest" /> <class name="org.wso2.carbon.webapp.authenticator.framework.authenticator.BSTAuthenticatorTest" />
<class name="org.wso2.carbon.webapp.authenticator.framework.authenticator.OauthAuthenticatorTest" />
</classes> </classes>
</test> </test>

Loading…
Cancel
Save