mirror of
https://repository.entgra.net/community/device-mgt-core.git
synced 2025-10-06 02:01:45 +00:00
Merge pull request #1056 from Megala21/master
Adding test cases for webapp authenticator framework component
This commit is contained in:
commit
d03e03dd1c
@ -20,7 +20,7 @@ package org.wso2.carbon.device.mgt.extensions.device.type.template;
|
||||
|
||||
import org.h2.jdbcx.JdbcDataSource;
|
||||
import org.mockito.Mockito;
|
||||
import org.testng.annotations.BeforeTest;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.base.MultitenantConstants;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
@ -69,7 +69,7 @@ public class DeviceTypeManagerNegativeTest {
|
||||
private PropertyBasedPluginDAOImpl propertyBasedPluginDAO;
|
||||
private Device sampleDevice;
|
||||
|
||||
@BeforeTest
|
||||
@BeforeClass
|
||||
public void setup()
|
||||
throws SAXException, JAXBException, ParserConfigurationException, DeviceTypeConfigurationException,
|
||||
IOException, NoSuchFieldException, IllegalAccessException {
|
||||
|
||||
@ -21,14 +21,16 @@ package org.wso2.carbon.device.mgt.extensions.device.type.template;
|
||||
|
||||
import org.mockito.Mockito;
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeTest;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.base.MultitenantConstants;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
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.PlatformConfiguration;
|
||||
import org.wso2.carbon.device.mgt.common.license.mgt.License;
|
||||
@ -75,7 +77,7 @@ public class DeviceTypeManagerServiceTest {
|
||||
private Method setPolicyMonitoringManager;
|
||||
private Method setPullNotificationSubscriber;
|
||||
|
||||
@BeforeTest
|
||||
@BeforeClass
|
||||
public void setup() throws NoSuchMethodException, SAXException, JAXBException, ParserConfigurationException,
|
||||
DeviceTypeConfigurationException, IOException, NoSuchFieldException, IllegalAccessException,
|
||||
DeviceManagementException, RegistryException {
|
||||
|
||||
@ -20,7 +20,7 @@ package org.wso2.carbon.device.mgt.extensions.device.type.template;
|
||||
|
||||
import org.mockito.Mockito;
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeTest;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
@ -73,7 +73,7 @@ public class DeviceTypeManagerTest {
|
||||
private String[] customDeviceTypeProperties = {"custom_property", "custom_property2"};
|
||||
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,
|
||||
ParserConfigurationException, DeviceTypeConfigurationException, JAXBException {
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
|
||||
@ -19,7 +19,7 @@
|
||||
package org.wso2.carbon.device.mgt.extensions.device.type.template;
|
||||
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeTest;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
@ -60,7 +60,7 @@ public class HttpDeviceTypeManagerServiceAndDeviceTypeGeneratorServceTest {
|
||||
private String androidSenseDeviceType = "androidsense";
|
||||
private DeviceManagementService generatedDeviceManagementService;
|
||||
|
||||
@BeforeTest
|
||||
@BeforeClass
|
||||
public void setup() throws RegistryException, IOException, SAXException, ParserConfigurationException,
|
||||
DeviceTypeConfigurationException, JAXBException {
|
||||
createSampleDeviceTypeMetaDefinition();
|
||||
|
||||
@ -20,7 +20,7 @@
|
||||
package org.wso2.carbon.device.mgt.extensions.utils;
|
||||
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeTest;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.base.MultitenantConstants;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
@ -51,7 +51,7 @@ import java.util.List;
|
||||
public class UtilsTest {
|
||||
private FileSystemBasedLicenseManager fileSystemBasedLicenseManager;
|
||||
|
||||
@BeforeTest
|
||||
@BeforeClass
|
||||
public void setup() {
|
||||
fileSystemBasedLicenseManager = new FileSystemBasedLicenseManager();
|
||||
}
|
||||
|
||||
@ -248,6 +248,11 @@
|
||||
<artifactId>h2-database-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-api-mockito</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
|
||||
@ -97,44 +97,6 @@ public class OAuthTokenValidationStubFactory implements PoolableObjectFactory {
|
||||
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
|
||||
public Object makeObject() throws Exception {
|
||||
return this.createStub();
|
||||
|
||||
@ -134,10 +134,10 @@ public class Utils {
|
||||
authenticationInfo.setUsername(username);
|
||||
authenticationInfo.setTenantDomain(tenantDomain);
|
||||
authenticationInfo.setTenantId(getTenantIdOFUser(username + "@" + tenantDomain));
|
||||
if (oAuthValidationResponse.isValid())
|
||||
authenticationInfo.setStatus(WebappAuthenticator.Status.CONTINUE);
|
||||
} else {
|
||||
authenticationInfo.setMessage(oAuthValidationResponse.getErrorMsg());
|
||||
authenticationInfo.setStatus(WebappAuthenticator.Status.FAILURE);
|
||||
}
|
||||
return authenticationInfo;
|
||||
}
|
||||
|
||||
@ -18,7 +18,6 @@
|
||||
|
||||
package org.wso2.carbon.webapp.authenticator.framework.authenticator;
|
||||
|
||||
import com.nimbusds.jose.JOSEException;
|
||||
import com.nimbusds.jose.JWSVerifier;
|
||||
import com.nimbusds.jose.crypto.RSASSAVerifier;
|
||||
import com.nimbusds.jwt.SignedJWT;
|
||||
@ -46,6 +45,7 @@ import java.security.interfaces.RSAPublicKey;
|
||||
import java.text.ParseException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Properties;
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
@ -164,8 +164,6 @@ public class JWTAuthenticator implements WebappAuthenticator {
|
||||
log.error("Error occurred while obtaining the user.", e);
|
||||
} catch (ParseException e) {
|
||||
log.error("Error occurred while parsing the JWT header.", e);
|
||||
} catch (JOSEException e) {
|
||||
log.error("Error occurred while verifying the JWT header.", e);
|
||||
} catch (Exception e) {
|
||||
log.error("Error occurred while verifying the JWT header.", e);
|
||||
} finally {
|
||||
@ -203,12 +201,12 @@ public class JWTAuthenticator implements WebappAuthenticator {
|
||||
private String tenantDomain;
|
||||
private final String DEFAULT_ISSUER = "default";
|
||||
|
||||
public IssuerAlias(String tenantDomain) {
|
||||
IssuerAlias(String tenantDomain) {
|
||||
this.issuer = DEFAULT_ISSUER;
|
||||
this.tenantDomain = tenantDomain;
|
||||
}
|
||||
|
||||
public IssuerAlias(String issuer, String tenantDomain) {
|
||||
IssuerAlias(String issuer, String tenantDomain) {
|
||||
this.issuer = issuer;
|
||||
this.tenantDomain = tenantDomain;
|
||||
}
|
||||
@ -223,7 +221,7 @@ public class JWTAuthenticator implements WebappAuthenticator {
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
return (obj instanceof IssuerAlias) && issuer.equals(
|
||||
((IssuerAlias) obj).issuer) && tenantDomain == ((IssuerAlias) obj).tenantDomain;
|
||||
((IssuerAlias) obj).issuer) && Objects.equals(tenantDomain, ((IssuerAlias) obj).tenantDomain);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -68,11 +68,11 @@ public class LocalOAuthValidator implements OAuth2TokenValidator {
|
||||
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
|
||||
tenantDomain = MultitenantUtils.getTenantDomain(userName);
|
||||
}
|
||||
return new OAuthValidationResponse(userName, tenantDomain, true);
|
||||
} else {
|
||||
OAuthValidationResponse oAuthValidationResponse = new OAuthValidationResponse();
|
||||
oAuthValidationResponse.setErrorMsg(tokenValidationResponse.getErrorMsg());
|
||||
return oAuthValidationResponse;
|
||||
}
|
||||
return new OAuthValidationResponse(userName,tenantDomain,isValid);
|
||||
}
|
||||
}
|
||||
|
||||
@ -55,42 +55,41 @@ public class RemoteOAuthValidator implements OAuth2TokenValidator {
|
||||
try {
|
||||
OAuth2TokenValidationRequestDTO validationRequest = createValidationRequest(accessToken, resource);
|
||||
stub = (OAuth2TokenValidationServiceStub) this.stubs.borrowObject();
|
||||
validationResponse =
|
||||
stub.findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse();
|
||||
validationResponse = stub.findOAuthConsumerIfTokenIsValid(validationRequest)
|
||||
.getAccessTokenValidationResponse();
|
||||
} catch (RemoteException e) {
|
||||
throw new OAuthTokenValidationException("Remote Exception occurred while invoking the Remote " +
|
||||
"IS server for OAuth2 token validation.", e);
|
||||
throw new OAuthTokenValidationException(
|
||||
"Remote Exception occurred while invoking the Remote " + "IS server for OAuth2 token validation.",
|
||||
e);
|
||||
} catch (Exception e) {
|
||||
throw new OAuthTokenValidationException("Error occurred while borrowing an oauth token validation " +
|
||||
"service stub from the pool", e);
|
||||
throw new OAuthTokenValidationException(
|
||||
"Error occurred while borrowing an oauth token validation " + "service stub from the pool", e);
|
||||
} finally {
|
||||
try {
|
||||
this.stubs.returnObject(stub);
|
||||
} catch (Exception e) {
|
||||
log.warn("Error occurred while returning the object back to the oauth token validation service " +
|
||||
"stub pool", e);
|
||||
log.warn("Error occurred while returning the object back to the oauth token validation service "
|
||||
+ "stub pool", e);
|
||||
}
|
||||
}
|
||||
|
||||
if (validationResponse == null) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Response returned by the OAuth token validation service is null");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
boolean isValid = validationResponse.getValid();
|
||||
String tenantDomain;
|
||||
String username;
|
||||
if (isValid) {
|
||||
username = MultitenantUtils.getTenantAwareUsername(validationResponse.getAuthorizedUser());
|
||||
tenantDomain = MultitenantUtils.getTenantDomain(validationResponse.getAuthorizedUser());
|
||||
return new OAuthValidationResponse(username, tenantDomain, true);
|
||||
} else {
|
||||
OAuthValidationResponse oAuthValidationResponse = new OAuthValidationResponse();
|
||||
oAuthValidationResponse.setErrorMsg(validationResponse.getErrorMsg());
|
||||
return oAuthValidationResponse;
|
||||
}
|
||||
return new OAuthValidationResponse(username, tenantDomain, isValid);
|
||||
}
|
||||
|
||||
private OAuth2TokenValidationRequestDTO createValidationRequest(String accessToken, String resource) {
|
||||
|
||||
@ -19,12 +19,29 @@
|
||||
|
||||
package org.wso2.carbon.webapp.authenticator.framework.authenticator;
|
||||
|
||||
import org.apache.catalina.Context;
|
||||
import org.apache.catalina.connector.Request;
|
||||
import org.apache.catalina.core.StandardContext;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
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.BeforeTest;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
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.authenticator.oauth.OAuth2TokenValidator;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.internal.AuthenticatorFrameworkDataHolder;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.util.TestInputBuffer;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.net.URL;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
@ -33,11 +50,29 @@ import java.util.Properties;
|
||||
public class BSTAuthenticatorTest {
|
||||
private BSTAuthenticator bstAuthenticator;
|
||||
private Properties properties;
|
||||
private Field headersField;
|
||||
private OAuth2TokenValidationService oAuth2TokenValidationService;
|
||||
private OAuth2ClientApplicationDTO oAuth2ClientApplicationDTO;
|
||||
|
||||
@BeforeTest
|
||||
public void init() {
|
||||
@BeforeClass
|
||||
public void init() throws NoSuchFieldException {
|
||||
bstAuthenticator = new BSTAuthenticator();
|
||||
properties = new Properties();
|
||||
headersField = org.apache.coyote.Request.class.getDeclaredField("headers");
|
||||
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 "
|
||||
@ -89,4 +124,125 @@ public class BSTAuthenticatorTest {
|
||||
Assert.assertNotNull(oAuth2TokenValidator, "Token validation creation failed even with the required "
|
||||
+ "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")
|
||||
public void testCanHandleWithFalseConditions() throws IllegalAccessException {
|
||||
Request request = new Request();
|
||||
org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request();
|
||||
request.setCoyoteRequest(coyoteRequest);
|
||||
Assert.assertFalse(bstAuthenticator.canHandle(request),
|
||||
"BST Authenticator can handle a request without content type");
|
||||
|
||||
MimeHeaders mimeHeaders = new MimeHeaders();
|
||||
MessageBytes bytes = mimeHeaders.addValue("content-type");
|
||||
bytes.setString("test");
|
||||
headersField.set(coyoteRequest, mimeHeaders);
|
||||
request.setCoyoteRequest(coyoteRequest);
|
||||
Assert.assertFalse(bstAuthenticator.canHandle(request),
|
||||
"BST Authenticator can handle a request with content type test");
|
||||
}
|
||||
|
||||
|
||||
@Test(description = "This test case tests the canHandle method of the BSTAuthenticator under valid conditions")
|
||||
public void testCanHandleWithValidRequest() throws IOException, IllegalAccessException {
|
||||
Request request = createSoapRequest("CorrectBST.xml");
|
||||
Assert.assertTrue(bstAuthenticator.canHandle(request), "BST Authenticator cannot handle a valid "
|
||||
+ "authentication request");
|
||||
}
|
||||
|
||||
@Test(description = "This test case tests the canHandle method of the BSTAuthenticator under missing soap headers")
|
||||
public void testCanHandleWithMissingHeaders() throws IOException, IllegalAccessException {
|
||||
Request request = createSoapRequest("WrongBST1.xml");
|
||||
Assert.assertFalse(bstAuthenticator.canHandle(request),
|
||||
"BST Authenticator can handle a request with missing headers ");
|
||||
request = createSoapRequest("WrongBST2.xml");
|
||||
Assert.assertFalse(bstAuthenticator.canHandle(request),
|
||||
"BST Authenticator can handle a request with missing headers ");
|
||||
}
|
||||
|
||||
@Test(description = "This method tests the authenticate method of BST Authenticator when only minimal information"
|
||||
+ " is provided")
|
||||
public void testAuthenticateWithMinimalConditions() throws NoSuchFieldException, IllegalAccessException {
|
||||
Request request = new Request();
|
||||
org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request();
|
||||
request.setCoyoteRequest(coyoteRequest);
|
||||
AuthenticationInfo authenticationInfo = bstAuthenticator.authenticate(request, null);
|
||||
Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.CONTINUE,
|
||||
"Authentication status of authentication info is wrong");
|
||||
}
|
||||
|
||||
@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);
|
||||
MessageBytes bytes = MessageBytes.newInstance();
|
||||
bytes.setString("test");
|
||||
uriMB.set(coyoteRequest, bytes);
|
||||
request.setCoyoteRequest(coyoteRequest);
|
||||
bstAuthenticator.canHandle(request);
|
||||
AuthenticationInfo authenticationInfo = bstAuthenticator.authenticate(request, null);
|
||||
Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.CONTINUE,
|
||||
"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");
|
||||
}
|
||||
|
||||
/**
|
||||
* To create a soap request by reading the request from given file.
|
||||
*
|
||||
* @param fileName Name of the file that has the soap request content.
|
||||
* @return Request created with soap content.
|
||||
* @throws IllegalAccessException Illegal Access Exception.
|
||||
* @throws IOException IO Exception.
|
||||
*/
|
||||
private Request createSoapRequest(String fileName) throws IllegalAccessException, IOException {
|
||||
Request request = new Request();
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
URL resourceUrl = classLoader
|
||||
.getResource("requests" + File.separator + "BST" + File.separator + fileName);
|
||||
String bstRequestContent = null;
|
||||
if (resourceUrl != null) {
|
||||
File bst = new File(resourceUrl.getFile());
|
||||
bstRequestContent = FileUtils.readFileToString(bst);
|
||||
}
|
||||
org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request();
|
||||
MimeHeaders mimeHeaders = new MimeHeaders();
|
||||
MessageBytes bytes = mimeHeaders.addValue("content-type");
|
||||
bytes.setString("application/xml");
|
||||
bytes = mimeHeaders.addValue("custom");
|
||||
bytes.setString(bstRequestContent);
|
||||
headersField.set(coyoteRequest, mimeHeaders);
|
||||
TestInputBuffer inputBuffer = new TestInputBuffer();
|
||||
coyoteRequest.setInputBuffer(inputBuffer);
|
||||
Context context = new StandardContext();
|
||||
request.setContext(context);
|
||||
request.setCoyoteRequest(coyoteRequest);
|
||||
return request;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -26,6 +26,7 @@ import org.apache.commons.codec.EncoderException;
|
||||
import org.apache.tomcat.util.buf.MessageBytes;
|
||||
import org.apache.tomcat.util.http.MimeHeaders;
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.BeforeTest;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
|
||||
@ -51,7 +52,7 @@ public class BasicAuthAuthenticatorTest {
|
||||
private MessageBytes bytes;
|
||||
private final String BASIC_HEADER = "basic ";
|
||||
|
||||
@BeforeTest
|
||||
@BeforeClass
|
||||
public void init() throws NoSuchFieldException {
|
||||
basicAuthAuthenticator = new BasicAuthAuthenticator();
|
||||
headersField = org.apache.coyote.Request.class.getDeclaredField("headers");
|
||||
|
||||
@ -0,0 +1,156 @@
|
||||
/*
|
||||
* 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 {
|
||||
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,62 @@
|
||||
/*
|
||||
* 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.util;
|
||||
|
||||
import org.apache.catalina.connector.InputBuffer;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.coyote.Request;
|
||||
import org.apache.tomcat.util.buf.ByteChunk;
|
||||
import org.apache.tomcat.util.buf.MessageBytes;
|
||||
import org.apache.tomcat.util.http.MimeHeaders;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
/**
|
||||
* This is a dummy implementation of {@link InputBuffer} for the test cases.
|
||||
*/
|
||||
public class TestInputBuffer implements org.apache.coyote.InputBuffer {
|
||||
private Log log = LogFactory.getLog(TestInputBuffer.class);
|
||||
|
||||
@Override
|
||||
public int doRead(ByteChunk byteChunk, Request request) throws IOException {
|
||||
String string = request.getHeader("custom");
|
||||
MimeHeaders mimeHeaders = new MimeHeaders();
|
||||
Field byteC = null;
|
||||
try {
|
||||
byteC = MessageBytes.class.getDeclaredField("byteC");
|
||||
byteC.setAccessible(true);
|
||||
} catch (NoSuchFieldException e) {
|
||||
log.error("Cannot get the byteC field", e);
|
||||
}
|
||||
MessageBytes bytes = mimeHeaders.addValue("content-type");
|
||||
try {
|
||||
if (byteC != null) {
|
||||
byteC.set(bytes, byteChunk);
|
||||
}
|
||||
} catch (IllegalAccessException e) {
|
||||
log.error("Cannot set byteC field", e);
|
||||
}
|
||||
bytes.setString(string);
|
||||
bytes.toBytes();
|
||||
return byteChunk.getLength();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,25 @@
|
||||
<!--
|
||||
~ Copyright 2017 WSO2 Inc. (http://wso2.com)
|
||||
~
|
||||
~ Licensed 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.
|
||||
-->
|
||||
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
|
||||
xmlns:w="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
|
||||
<soap:Header>
|
||||
<w:Security>
|
||||
<w:BinarySecurityToken>test</w:BinarySecurityToken>
|
||||
</w:Security>
|
||||
</soap:Header>
|
||||
<soap:Body>
|
||||
</soap:Body>
|
||||
</soap:Envelope>
|
||||
@ -0,0 +1,25 @@
|
||||
<!--
|
||||
~ Copyright 2017 WSO2 Inc. (http://wso2.com)
|
||||
~
|
||||
~ Licensed 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.
|
||||
-->
|
||||
|
||||
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
|
||||
xmlns:w="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
|
||||
<soap:Header>
|
||||
<w:Security>
|
||||
</w:Security>
|
||||
</soap:Header>
|
||||
<soap:Body>
|
||||
</soap:Body>
|
||||
</soap:Envelope>
|
||||
@ -0,0 +1,19 @@
|
||||
<!--
|
||||
~ Copyright 2017 WSO2 Inc. (http://wso2.com)
|
||||
~
|
||||
~ Licensed 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.
|
||||
-->
|
||||
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
|
||||
<soap:Header/>
|
||||
<soap:Body/>
|
||||
</soap:Envelope>
|
||||
@ -30,6 +30,7 @@
|
||||
<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.BSTAuthenticatorTest" />
|
||||
<class name="org.wso2.carbon.webapp.authenticator.framework.authenticator.OauthAuthenticatorTest" />
|
||||
</classes>
|
||||
</test>
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user