mirror of
https://repository.entgra.net/community/device-mgt-core.git
synced 2025-10-06 02:01:45 +00:00
Merge branch 'master' of https://github.com/wso2/carbon-device-mgt
This commit is contained in:
commit
c7b53f7110
@ -60,15 +60,7 @@ public class OAuthEndpointProxy {
|
||||
int status = serverResponse.getStatusLine().getStatusCode();
|
||||
String resp = EntityUtils.toString(responseData, Constants.CharSets.CHARSET_UTF_8);
|
||||
response = Response.status(DCRProxyUtils.getResponseStatus(status)).entity(resp).build();
|
||||
} catch (URISyntaxException e) {
|
||||
String msg = "Service invoke error occurred while registering client";
|
||||
log.error(msg, e);
|
||||
response = Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
String msg = "Service invoke error occurred while registering client";
|
||||
log.error(msg, e);
|
||||
response = Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||
} catch (IOException e) {
|
||||
} catch (URISyntaxException | IOException e) {
|
||||
String msg = "Service invoke error occurred while registering client";
|
||||
log.error(msg, e);
|
||||
response = Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||
|
||||
@ -105,12 +105,29 @@
|
||||
org.apache.axis2.client,
|
||||
org.apache.commons.codec.binary,
|
||||
org.apache.commons.httpclient,
|
||||
org.wso2.carbon.core.security
|
||||
org.wso2.carbon.core.security,
|
||||
org.apache.axis2.context,
|
||||
org.apache.commons.httpclient.params,
|
||||
org.apache.commons.pool,
|
||||
org.apache.commons.pool.impl,
|
||||
org.apache.http.conn,
|
||||
org.apache.http.impl.conn
|
||||
</Import-Package>
|
||||
<!--<Fragment-Host>tomcat</Fragment-Host>-->
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<log4j.configuration>file:src/test/resources/log4j.properties</log4j.configuration>
|
||||
</systemPropertyVariables>
|
||||
<suiteXmlFiles>
|
||||
<suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
|
||||
</suiteXmlFiles>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
@ -175,6 +192,22 @@
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents.wso2</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-httpclient.wso2</groupId>
|
||||
<artifactId>commons-httpclient</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-pool.wso2</groupId>
|
||||
<artifactId>commons-pool</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
|
||||
@ -0,0 +1,211 @@
|
||||
/*
|
||||
* Copyright (c) 2015, 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.Utils;
|
||||
|
||||
import org.apache.axis2.AxisFault;
|
||||
import org.apache.axis2.client.Options;
|
||||
import org.apache.axis2.client.ServiceClient;
|
||||
import org.apache.axis2.transport.http.HTTPConstants;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.httpclient.Header;
|
||||
import org.apache.commons.httpclient.HttpClient;
|
||||
import org.apache.commons.httpclient.HttpConnectionManager;
|
||||
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
|
||||
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.commons.pool.PoolableObjectFactory;
|
||||
import org.apache.http.conn.HttpClientConnectionManager;
|
||||
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
||||
import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthConstants;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthTokenValidationException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
public class OAuthTokenValidationStubFactory implements PoolableObjectFactory {
|
||||
|
||||
private String url;
|
||||
private String basicAuthHeader;
|
||||
private HttpClient httpClient;
|
||||
|
||||
private static final Log log = LogFactory.getLog(OAuthTokenValidationStubFactory.class);
|
||||
|
||||
public OAuthTokenValidationStubFactory(String url, String adminUsername, String adminPassword,
|
||||
Properties properties) {
|
||||
this.validateUrl(url);
|
||||
this.url = url;
|
||||
|
||||
this.validateCredentials(adminUsername, adminPassword);
|
||||
this.basicAuthHeader = new String(Base64.encodeBase64((adminUsername + ":" + adminPassword).getBytes()));
|
||||
|
||||
HttpConnectionManager connectionManager = this.createConnectionManager(properties);
|
||||
this.httpClient = new HttpClient(connectionManager);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an instance of MultiThreadedHttpConnectionManager using HttpClient 3.x APIs
|
||||
*
|
||||
* @param properties Properties to configure MultiThreadedHttpConnectionManager
|
||||
* @return An instance of properly configured MultiThreadedHttpConnectionManager
|
||||
*/
|
||||
private HttpConnectionManager createConnectionManager(Properties properties) {
|
||||
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
|
||||
if (properties == null || properties.isEmpty()) {
|
||||
throw new IllegalArgumentException("Parameters required to initialize HttpClient instances " +
|
||||
"associated with OAuth token validation service stub are not provided");
|
||||
}
|
||||
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 {
|
||||
params.setDefaultMaxConnectionsPerHost(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 {
|
||||
params.setMaxTotalConnections(Integer.parseInt(maxTotalConnectionsParam));
|
||||
}
|
||||
HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
|
||||
connectionManager.setParams(params);
|
||||
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();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroyObject(Object o) throws Exception {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean validateObject(Object o) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void activateObject(Object o) throws Exception {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("OAuth token validate stub instance is activated");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void passivateObject(Object o) throws Exception {
|
||||
if (o instanceof OAuth2TokenValidationServiceStub) {
|
||||
OAuth2TokenValidationServiceStub stub = (OAuth2TokenValidationServiceStub) o;
|
||||
stub._getServiceClient().cleanupTransport();
|
||||
}
|
||||
}
|
||||
|
||||
private OAuth2TokenValidationServiceStub createStub() throws OAuthTokenValidationException {
|
||||
OAuth2TokenValidationServiceStub stub;
|
||||
try {
|
||||
stub = new OAuth2TokenValidationServiceStub(url);
|
||||
ServiceClient client = stub._getServiceClient();
|
||||
client.getServiceContext().getConfigurationContext().setProperty(
|
||||
HTTPConstants.CACHED_HTTP_CLIENT, httpClient);
|
||||
|
||||
List<Header> headerList = new ArrayList<>();
|
||||
Header header = new Header();
|
||||
header.setName(HTTPConstants.HEADER_AUTHORIZATION);
|
||||
header.setValue(OAuthConstants.AUTHORIZATION_HEADER_PREFIX_BASIC + " " + basicAuthHeader);
|
||||
headerList.add(header);
|
||||
|
||||
Options options = client.getOptions();
|
||||
options.setProperty(HTTPConstants.HTTP_HEADERS, headerList);
|
||||
options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, "true");
|
||||
client.setOptions(options);
|
||||
} catch (AxisFault axisFault) {
|
||||
throw new OAuthTokenValidationException("Error occurred while creating the " +
|
||||
"OAuth2TokenValidationServiceStub.", axisFault);
|
||||
}
|
||||
return stub;
|
||||
}
|
||||
|
||||
private void validateUrl(String url) {
|
||||
if (url == null || url.isEmpty()) {
|
||||
throw new IllegalArgumentException("Url provided as the endpoint of the OAuth token validation service " +
|
||||
"is null");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateCredentials(String adminUsername, String adminPassword) {
|
||||
if (adminUsername == null || adminUsername.isEmpty()) {
|
||||
throw new IllegalArgumentException("An appropriate username required to initialize OAuth token " +
|
||||
"validation service stub factory hasn't been provided");
|
||||
}
|
||||
if (adminPassword == null || adminPassword.isEmpty()) {
|
||||
throw new IllegalArgumentException("An appropriate password required to initialize OAuth token " +
|
||||
"validation service stub factory hasn't been provided");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -26,7 +26,8 @@ import java.util.Map;
|
||||
public class WebappAuthenticatorFactory {
|
||||
|
||||
public static WebappAuthenticator getAuthenticator(String authScheme) {
|
||||
return AuthenticatorFrameworkDataHolder.getInstance().getWebappAuthenticatorRepository().getAuthenticator(authScheme);
|
||||
return AuthenticatorFrameworkDataHolder.getInstance().getWebappAuthenticatorRepository().
|
||||
getAuthenticator(authScheme);
|
||||
}
|
||||
|
||||
public static WebappAuthenticator getAuthenticator(Request request) {
|
||||
|
||||
@ -27,10 +27,17 @@ import org.apache.tomcat.util.buf.MessageBytes;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.Constants;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
public class BasicAuthAuthenticator implements WebappAuthenticator {
|
||||
|
||||
private static final String BASIC_AUTH_AUTHENTICATOR = "BasicAuth";
|
||||
|
||||
@Override
|
||||
public void init() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canHandle(Request request) {
|
||||
MessageBytes authorization =
|
||||
@ -55,6 +62,21 @@ public class BasicAuthAuthenticator implements WebappAuthenticator {
|
||||
return BasicAuthAuthenticator.BASIC_AUTH_AUTHENTICATOR;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setProperties(Properties properties) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Properties getProperties() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getProperty(String name) {
|
||||
return null;
|
||||
}
|
||||
|
||||
private Credentials getCredentials(Request request) {
|
||||
Credentials credentials = null;
|
||||
MessageBytes authorization =
|
||||
|
||||
@ -15,6 +15,7 @@ import org.wso2.carbon.webapp.authenticator.framework.AuthenticatorFrameworkData
|
||||
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo;
|
||||
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* This authenticator authenticates HTTP requests using certificates.
|
||||
@ -25,6 +26,11 @@ public class CertificateAuthenticator implements WebappAuthenticator {
|
||||
private static final String CERTIFICATE_AUTHENTICATOR = "CertificateAuth";
|
||||
private static final String CERTIFICATE_VERIFICATION_HEADER = "certificate-verification-header";
|
||||
|
||||
@Override
|
||||
public void init() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canHandle(Request request) {
|
||||
String certVerificationHeader = request.getContext().findParameter(CERTIFICATE_VERIFICATION_HEADER);
|
||||
@ -93,4 +99,20 @@ public class CertificateAuthenticator implements WebappAuthenticator {
|
||||
public String getName() {
|
||||
return CERTIFICATE_AUTHENTICATOR;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setProperties(Properties properties) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Properties getProperties() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getProperty(String name) {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -39,6 +39,7 @@ import org.wso2.carbon.webapp.authenticator.framework.AuthenticatorFrameworkData
|
||||
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.text.ParseException;
|
||||
import java.util.Properties;
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
/**
|
||||
@ -51,6 +52,11 @@ public class JWTAuthenticator implements WebappAuthenticator {
|
||||
private static final String JWT_AUTHENTICATOR = "JWT";
|
||||
private static final String JWT_ASSERTION_HEADER = "X-JWT-Assertion";
|
||||
|
||||
@Override
|
||||
public void init() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canHandle(Request request) {
|
||||
String authorizationHeader = request.getHeader(JWTAuthenticator.JWT_ASSERTION_HEADER);
|
||||
@ -137,4 +143,19 @@ public class JWTAuthenticator implements WebappAuthenticator {
|
||||
public String getName() {
|
||||
return JWTAuthenticator.JWT_AUTHENTICATOR;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setProperties(Properties properties) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Properties getProperties() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getProperty(String name) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@ -18,22 +18,21 @@
|
||||
*/
|
||||
package org.wso2.carbon.webapp.authenticator.framework.authenticator;
|
||||
|
||||
import org.apache.catalina.connector.Request;
|
||||
import org.apache.catalina.connector.Response;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.tomcat.util.buf.ByteChunk;
|
||||
import org.apache.tomcat.util.buf.MessageBytes;
|
||||
import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO;
|
||||
import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO;
|
||||
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.*;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationException;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationFrameworkUtil;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.Utils.Utils;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuth2TokenValidator;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthTokenValidationException;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthValidationResponse;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthValidatorFactory;
|
||||
|
||||
import java.util.Properties;
|
||||
import java.util.StringTokenizer;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
@ -42,22 +41,51 @@ public class OAuthAuthenticator implements WebappAuthenticator {
|
||||
|
||||
private static final String OAUTH_AUTHENTICATOR = "OAuth";
|
||||
private static final String REGEX_BEARER_PATTERN = "[B|b]earer\\s";
|
||||
private static final Pattern PATTERN = Pattern.compile(REGEX_BEARER_PATTERN);
|
||||
private static final Pattern PATTERN = Pattern.compile("[B|b]earer\\s");
|
||||
private static final String BEARER_TOKEN_TYPE = "bearer";
|
||||
private static final String RESOURCE_KEY = "resource";
|
||||
|
||||
|
||||
private Properties properties;
|
||||
private OAuth2TokenValidator tokenValidator;
|
||||
private static final Log log = LogFactory.getLog(OAuthAuthenticator.class);
|
||||
|
||||
@Override
|
||||
public boolean canHandle(Request request) {
|
||||
MessageBytes authorization =
|
||||
request.getCoyoteRequest().getMimeHeaders().getValue(Constants.HTTPHeaders.HEADER_HTTP_AUTHORIZATION);
|
||||
String tokenValue;
|
||||
public void init() {
|
||||
if (this.properties == null) {
|
||||
throw new IllegalArgumentException("Required properties needed to initialize OAuthAuthenticator " +
|
||||
"are not provided");
|
||||
}
|
||||
|
||||
String url = this.properties.getProperty("TokenValidationEndpointUrl");
|
||||
if ((url == null) || (url.isEmpty())) {
|
||||
throw new IllegalArgumentException("OAuth token validation endpoint url is not provided");
|
||||
}
|
||||
String adminUsername = this.properties.getProperty("Username");
|
||||
if (adminUsername == null) {
|
||||
throw new IllegalArgumentException("Username to connect to the OAuth token validation endpoint " +
|
||||
"is not provided");
|
||||
}
|
||||
|
||||
String adminPassword = this.properties.getProperty("Password");
|
||||
if (adminPassword == null) {
|
||||
throw new IllegalArgumentException("Password to connect to the OAuth token validation endpoint " +
|
||||
"is not provided");
|
||||
}
|
||||
|
||||
boolean isRemote = Boolean.parseBoolean(this.properties.getProperty("IsRemote"));
|
||||
|
||||
Properties validatorProperties = new Properties();
|
||||
validatorProperties.setProperty("MaxTotalConnections", this.properties.getProperty("MaxTotalConnections"));
|
||||
validatorProperties.setProperty("MaxConnectionsPerHost", this.properties.getProperty("MaxConnectionsPerHost"));
|
||||
this.tokenValidator =
|
||||
OAuthValidatorFactory.getValidator(url, adminUsername, adminPassword, isRemote, validatorProperties);
|
||||
}
|
||||
|
||||
public boolean canHandle(org.apache.catalina.connector.Request request) {
|
||||
MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders().getValue("Authorization");
|
||||
|
||||
if (authorization != null) {
|
||||
authorization.toBytes();
|
||||
ByteChunk authBC = authorization.getByteChunk();
|
||||
tokenValue = authBC.toString();
|
||||
String tokenValue = authBC.toString();
|
||||
Matcher matcher = PATTERN.matcher(tokenValue);
|
||||
if (matcher.find()) {
|
||||
return true;
|
||||
@ -66,50 +94,46 @@ public class OAuthAuthenticator implements WebappAuthenticator {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AuthenticationInfo authenticate(Request request, Response response) {
|
||||
public AuthenticationInfo authenticate(org.apache.catalina.connector.Request request, Response response) {
|
||||
String requestUri = request.getRequestURI();
|
||||
String requestMethod = request.getMethod();
|
||||
AuthenticationInfo authenticationInfo = new AuthenticationInfo();
|
||||
if (requestUri == null || "".equals(requestUri)) {
|
||||
authenticationInfo.setStatus(Status.CONTINUE);
|
||||
if ((requestUri == null) || ("".equals(requestUri))) {
|
||||
authenticationInfo.setStatus(WebappAuthenticator.Status.CONTINUE);
|
||||
return authenticationInfo;
|
||||
}
|
||||
|
||||
StringTokenizer tokenizer = new StringTokenizer(requestUri, "/");
|
||||
String context = tokenizer.nextToken();
|
||||
if (context == null || "".equals(context)) {
|
||||
authenticationInfo.setStatus(Status.CONTINUE);
|
||||
if ((context == null) || ("".equals(context))) {
|
||||
authenticationInfo.setStatus(WebappAuthenticator.Status.CONTINUE);
|
||||
}
|
||||
String apiVersion = tokenizer.nextToken();
|
||||
//String authLevel = authenticator.getResourceAuthenticationScheme(context, apiVersion, requestUri, requestMethod);
|
||||
|
||||
String authLevel = "any";
|
||||
try {
|
||||
if (Constants.NO_MATCHING_AUTH_SCHEME.equals(authLevel)) {
|
||||
AuthenticationFrameworkUtil.handleNoMatchAuthScheme(request, response, requestMethod, apiVersion,
|
||||
context);
|
||||
authenticationInfo.setStatus(Status.CONTINUE);
|
||||
if ("noMatchedAuthScheme".equals(authLevel)) {
|
||||
AuthenticationFrameworkUtil.handleNoMatchAuthScheme(
|
||||
request, response, requestMethod, apiVersion, context);
|
||||
|
||||
authenticationInfo.setStatus(WebappAuthenticator.Status.CONTINUE);
|
||||
} else {
|
||||
String bearerToken = this.getBearerToken(request);
|
||||
//Set the resource context param. This will be used in scope validation.
|
||||
String bearerToken = getBearerToken(request);
|
||||
|
||||
String resource = requestUri + ":" + requestMethod;
|
||||
//Get the appropriate OAuth validator from OAuthValidatorFactory.
|
||||
OAuth2TokenValidator oAuth2TokenValidator = OAuthValidatorFactory.getValidator();
|
||||
OAuthValidationResponse oAuthValidationResponse = oAuth2TokenValidator.validateToken(bearerToken, resource);
|
||||
|
||||
OAuthValidationResponse oAuthValidationResponse =
|
||||
this.tokenValidator.validateToken(bearerToken, resource);
|
||||
|
||||
if (oAuthValidationResponse.isValid()) {
|
||||
String username = oAuthValidationResponse.getUserName();
|
||||
String tenantDomain = oAuthValidationResponse.getTenantDomain();
|
||||
//Remove the userstore domain from username
|
||||
/*if (username.contains("/")) {
|
||||
username = username.substring(username.indexOf('/') + 1);
|
||||
}*/
|
||||
|
||||
authenticationInfo.setUsername(username);
|
||||
authenticationInfo.setTenantDomain(tenantDomain);
|
||||
authenticationInfo.setTenantId(Utils.getTenantIdOFUser(username + "@" + tenantDomain));
|
||||
if (oAuthValidationResponse.isValid()) {
|
||||
authenticationInfo.setStatus(Status.CONTINUE);
|
||||
}
|
||||
if (oAuthValidationResponse.isValid())
|
||||
authenticationInfo.setStatus(WebappAuthenticator.Status.CONTINUE);
|
||||
} else {
|
||||
authenticationInfo.setMessage(oAuthValidationResponse.getErrorMsg());
|
||||
}
|
||||
@ -122,15 +146,28 @@ public class OAuthAuthenticator implements WebappAuthenticator {
|
||||
return authenticationInfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return OAuthAuthenticator.OAUTH_AUTHENTICATOR;
|
||||
return "OAuth";
|
||||
}
|
||||
|
||||
private String getBearerToken(Request request) {
|
||||
MessageBytes authorization =
|
||||
request.getCoyoteRequest().getMimeHeaders().
|
||||
getValue(Constants.HTTPHeaders.HEADER_HTTP_AUTHORIZATION);
|
||||
public String getProperty(String name) {
|
||||
if (this.properties == null) {
|
||||
return null;
|
||||
}
|
||||
return this.properties.getProperty(name);
|
||||
}
|
||||
|
||||
public Properties getProperties() {
|
||||
return this.properties;
|
||||
}
|
||||
|
||||
public void setProperties(Properties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
private String getBearerToken(org.apache.catalina.connector.Request request) {
|
||||
MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders().getValue("Authorization");
|
||||
|
||||
String tokenValue = null;
|
||||
if (authorization != null) {
|
||||
authorization.toBytes();
|
||||
|
||||
@ -22,16 +22,26 @@ import org.apache.catalina.connector.Request;
|
||||
import org.apache.catalina.connector.Response;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
public interface WebappAuthenticator {
|
||||
|
||||
enum Status {
|
||||
SUCCESS, FAILURE, CONTINUE
|
||||
}
|
||||
|
||||
void init();
|
||||
|
||||
boolean canHandle(Request request);
|
||||
|
||||
AuthenticationInfo authenticate(Request request, Response response);
|
||||
|
||||
String getName();
|
||||
|
||||
void setProperties(Properties properties);
|
||||
|
||||
Properties getProperties();
|
||||
|
||||
String getProperty(String name);
|
||||
|
||||
}
|
||||
|
||||
@ -21,51 +21,27 @@ import org.wso2.carbon.core.security.AuthenticatorsConfiguration;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.impl.RemoteOAuthValidator;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.impl.LocalOAuthValidator;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* The class validate the configurations and provide the most suitable implementation according to the configuration.
|
||||
* Factory class for OAuthValidator.
|
||||
*/
|
||||
public class OAuthValidatorFactory {
|
||||
|
||||
private static final String AUTHENTICATOR_CONFIG_IS_REMOTE = "isRemote";
|
||||
private static final String AUTHENTICATOR_CONFIG_HOST_URL = "hostURL";
|
||||
private static final String AUTHENTICATOR_CONFIG_ADMIN_USERNAME = "adminUsername";
|
||||
private static final String AUTHENTICATOR_CONFIG_ADMIN_PASSWORD = "adminPassword";
|
||||
private static final String AUTHENTICATOR_CONFIG_OAUTH_AUTHENTICATOR_NAME = "OAuthAuthenticator";
|
||||
private static String OAUTH_ENDPOINT_POSTFIX =
|
||||
"/services/OAuth2TokenValidationService.OAuth2TokenValidationServiceHttpsSoap12Endpoint/";
|
||||
|
||||
/**
|
||||
* This factory method checks the authenticators.xml configuration file and provides an appropriate implementation
|
||||
* of OAuth2TokenValidator.
|
||||
* @return OAuth2TokenValidator
|
||||
*/
|
||||
public static OAuth2TokenValidator getValidator() throws IllegalArgumentException {
|
||||
AuthenticatorsConfiguration authenticatorsConfiguration = AuthenticatorsConfiguration.getInstance();
|
||||
AuthenticatorsConfiguration.AuthenticatorConfig authenticatorConfig = authenticatorsConfiguration.
|
||||
getAuthenticatorConfig(AUTHENTICATOR_CONFIG_OAUTH_AUTHENTICATOR_NAME);
|
||||
boolean isRemote;
|
||||
String hostUrl;
|
||||
String adminUserName;
|
||||
String adminPassword;
|
||||
if (authenticatorConfig != null && authenticatorConfig.getParameters() != null) {
|
||||
isRemote = Boolean.parseBoolean(authenticatorConfig.getParameters().get(
|
||||
AUTHENTICATOR_CONFIG_IS_REMOTE));
|
||||
hostUrl = authenticatorConfig.getParameters().get(AUTHENTICATOR_CONFIG_HOST_URL);
|
||||
adminUserName = authenticatorConfig.getParameters().get(AUTHENTICATOR_CONFIG_ADMIN_USERNAME);
|
||||
adminPassword = authenticatorConfig.getParameters().get(AUTHENTICATOR_CONFIG_ADMIN_PASSWORD);
|
||||
}else{
|
||||
throw new IllegalArgumentException("OAuth Authenticator configuration parameters need to be defined in " +
|
||||
"Authenticators.xml.");
|
||||
}
|
||||
public static OAuth2TokenValidator getValidator(String url, String adminUsername, String adminPassword,
|
||||
boolean isRemote, Properties properties)
|
||||
throws IllegalArgumentException
|
||||
{
|
||||
if (isRemote) {
|
||||
if (!(hostUrl == null || hostUrl.trim().isEmpty())) {
|
||||
hostUrl = hostUrl + OAUTH_ENDPOINT_POSTFIX;
|
||||
return new RemoteOAuthValidator(hostUrl, adminUserName, adminPassword);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Remote server host can't be empty in authenticators.xml.");
|
||||
if ((url != null) && (!url.trim().isEmpty())) {
|
||||
url = url + "/services/OAuth2TokenValidationService.OAuth2TokenValidationServiceHttpsSoap12Endpoint/";
|
||||
return new RemoteOAuthValidator(url, adminUsername, adminPassword, properties);
|
||||
}
|
||||
throw new IllegalArgumentException("Remote server host can't be empty in OAuthAuthenticator configuration.");
|
||||
}
|
||||
|
||||
return new LocalOAuthValidator();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -17,104 +17,103 @@
|
||||
*/
|
||||
package org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.impl;
|
||||
|
||||
import org.apache.axis2.AxisFault;
|
||||
import org.apache.axis2.client.Options;
|
||||
import org.apache.axis2.client.ServiceClient;
|
||||
import org.apache.axis2.transport.http.HTTPConstants;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.httpclient.Header;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.commons.pool.impl.GenericObjectPool;
|
||||
import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub;
|
||||
import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO;
|
||||
import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_OAuth2AccessToken;
|
||||
import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_TokenValidationContextParam;
|
||||
import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO;
|
||||
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.Utils.OAuthTokenValidationStubFactory;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuth2TokenValidator;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthConstants;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthTokenValidationException;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.authenticator.oauth.OAuthValidationResponse;
|
||||
|
||||
import java.rmi.RemoteException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* Handles the OAuth2 token validation from remote IS servers using remote OAuthValidation service-stub.
|
||||
*/
|
||||
public class RemoteOAuthValidator implements OAuth2TokenValidator {
|
||||
|
||||
private String hostURL;
|
||||
private String adminUserName;
|
||||
private String adminPassword;
|
||||
private GenericObjectPool stubs;
|
||||
private static final Log log = LogFactory.getLog(RemoteOAuthValidator.class);
|
||||
|
||||
public RemoteOAuthValidator(String hostURL, String adminUserName, String adminPassword) {
|
||||
this.hostURL = hostURL;
|
||||
this.adminUserName = adminUserName;
|
||||
this.adminPassword = adminPassword;
|
||||
public RemoteOAuthValidator(String hostURL, String adminUserName, String adminPassword, Properties properties) {
|
||||
this.stubs =
|
||||
new GenericObjectPool(new OAuthTokenValidationStubFactory(
|
||||
hostURL, adminUserName, adminPassword, properties));
|
||||
}
|
||||
|
||||
private String getBasicAuthCredentials() {
|
||||
byte[] bytesEncoded = Base64.encodeBase64((adminUserName + ":" + adminPassword).getBytes());
|
||||
return new String(bytesEncoded);
|
||||
public OAuthValidationResponse validateToken(String accessToken,
|
||||
String resource) throws OAuthTokenValidationException {
|
||||
OAuth2TokenValidationServiceStub stub = null;
|
||||
OAuth2TokenValidationResponseDTO validationResponse;
|
||||
try {
|
||||
OAuth2TokenValidationRequestDTO validationRequest = createValidationRequest(accessToken, resource);
|
||||
stub = (OAuth2TokenValidationServiceStub) this.stubs.borrowObject();
|
||||
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);
|
||||
} catch (Exception 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);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuthValidationResponse validateToken(String accessToken, String resource) throws
|
||||
OAuthTokenValidationException {
|
||||
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());
|
||||
} else {
|
||||
OAuthValidationResponse oAuthValidationResponse = new OAuthValidationResponse();
|
||||
oAuthValidationResponse.setErrorMsg(validationResponse.getErrorMsg());
|
||||
return oAuthValidationResponse;
|
||||
}
|
||||
return new OAuthValidationResponse(username, tenantDomain, isValid);
|
||||
}
|
||||
|
||||
private OAuth2TokenValidationRequestDTO createValidationRequest(String accessToken, String resource) {
|
||||
OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO();
|
||||
OAuth2TokenValidationRequestDTO_OAuth2AccessToken oauthToken =
|
||||
new OAuth2TokenValidationRequestDTO_OAuth2AccessToken();
|
||||
oauthToken.setTokenType(OAuthConstants.BEARER_TOKEN_TYPE);
|
||||
|
||||
oauthToken.setTokenType("bearer");
|
||||
oauthToken.setIdentifier(accessToken);
|
||||
validationRequest.setAccessToken(oauthToken);
|
||||
|
||||
//Set the resource context param. This will be used in scope validation.
|
||||
OAuth2TokenValidationRequestDTO_TokenValidationContextParam resourceContextParam = new
|
||||
OAuth2TokenValidationRequestDTO_TokenValidationContextParam();
|
||||
resourceContextParam.setKey(OAuthConstants.RESOURCE_KEY);
|
||||
OAuth2TokenValidationRequestDTO_TokenValidationContextParam resourceContextParam =
|
||||
new OAuth2TokenValidationRequestDTO_TokenValidationContextParam();
|
||||
|
||||
resourceContextParam.setKey("resource");
|
||||
resourceContextParam.setValue(resource);
|
||||
|
||||
OAuth2TokenValidationRequestDTO_TokenValidationContextParam[] tokenValidationContextParams =
|
||||
new OAuth2TokenValidationRequestDTO_TokenValidationContextParam[1];
|
||||
|
||||
tokenValidationContextParams[0] = resourceContextParam;
|
||||
validationRequest.setContext(tokenValidationContextParams);
|
||||
|
||||
OAuth2TokenValidationServiceStub tokenValidationService;
|
||||
try {
|
||||
tokenValidationService = new OAuth2TokenValidationServiceStub(hostURL);
|
||||
} catch (AxisFault axisFault) {
|
||||
throw new OAuthTokenValidationException("Exception occurred while obtaining the " +
|
||||
"OAuth2TokenValidationServiceStub.", axisFault);
|
||||
}
|
||||
ServiceClient client = tokenValidationService._getServiceClient();
|
||||
Options options = client.getOptions();
|
||||
List<Header> headerList = new ArrayList<>();
|
||||
Header header = new Header();
|
||||
header.setName(HTTPConstants.HEADER_AUTHORIZATION);
|
||||
header.setValue(OAuthConstants.AUTHORIZATION_HEADER_PREFIX_BASIC + " " + getBasicAuthCredentials());
|
||||
headerList.add(header);
|
||||
options.setProperty(HTTPConstants.HTTP_HEADERS, headerList);
|
||||
client.setOptions(options);
|
||||
OAuth2TokenValidationResponseDTO tokenValidationResponse;
|
||||
try {
|
||||
tokenValidationResponse = tokenValidationService.
|
||||
findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse();
|
||||
} catch (RemoteException e) {
|
||||
throw new OAuthTokenValidationException("Remote Exception occurred while invoking the Remote IS server for " +
|
||||
"OAuth2 token validation.", e);
|
||||
}
|
||||
boolean isValid = tokenValidationResponse.getValid();
|
||||
String userName;
|
||||
String tenantDomain;
|
||||
if (isValid) {
|
||||
userName = MultitenantUtils.getTenantAwareUsername(
|
||||
tokenValidationResponse.getAuthorizedUser());
|
||||
tenantDomain = MultitenantUtils.getTenantDomain(tokenValidationResponse.getAuthorizedUser());
|
||||
} else {
|
||||
OAuthValidationResponse oAuthValidationResponse = new OAuthValidationResponse();
|
||||
oAuthValidationResponse.setErrorMsg(tokenValidationResponse.getErrorMsg());
|
||||
return oAuthValidationResponse;
|
||||
}
|
||||
return new OAuthValidationResponse(userName,tenantDomain,isValid);
|
||||
return validationRequest;
|
||||
}
|
||||
}
|
||||
|
||||
@ -18,14 +18,15 @@
|
||||
*/
|
||||
package org.wso2.carbon.webapp.authenticator.framework.config;
|
||||
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import javax.xml.bind.annotation.*;
|
||||
import java.util.List;
|
||||
|
||||
@XmlRootElement(name = "Authenticator")
|
||||
public class AuthenticatorConfig {
|
||||
|
||||
private String name;
|
||||
private String className;
|
||||
private List<Parameter> params;
|
||||
|
||||
@XmlElement(name = "Name", required = true)
|
||||
public String getName() {
|
||||
@ -45,4 +46,38 @@ public class AuthenticatorConfig {
|
||||
this.className = className;
|
||||
}
|
||||
|
||||
@XmlElementWrapper(name = "Parameters", nillable = true)
|
||||
@XmlElement(name = "Parameter", nillable = false)
|
||||
public List<Parameter> getParams() {
|
||||
return this.params;
|
||||
}
|
||||
|
||||
public void setParams(List<Parameter> params) {
|
||||
this.params = params;
|
||||
}
|
||||
|
||||
@XmlRootElement(name = "Parameter")
|
||||
public static class Parameter {
|
||||
private String name;
|
||||
private String value;
|
||||
|
||||
@XmlAttribute(name = "Name")
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@XmlValue
|
||||
public String getValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -36,6 +36,7 @@ import org.wso2.carbon.webapp.authenticator.framework.config.WebappAuthenticator
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* @scr.component name="org.wso2.carbon.webapp.authenticator" immediate="true"
|
||||
@ -77,8 +78,17 @@ public class WebappAuthenticatorFrameworkServiceComponent {
|
||||
WebappAuthenticatorConfig.init();
|
||||
WebappAuthenticatorRepository repository = new WebappAuthenticatorRepository();
|
||||
for (AuthenticatorConfig config : WebappAuthenticatorConfig.getInstance().getAuthenticators()) {
|
||||
WebappAuthenticator authenticator = (WebappAuthenticator) Class.forName(config.getClassName()).
|
||||
newInstance();
|
||||
WebappAuthenticator authenticator =
|
||||
(WebappAuthenticator) Class.forName(config.getClassName()).newInstance();
|
||||
|
||||
if ((config.getParams() != null) && (!config.getParams().isEmpty())) {
|
||||
Properties properties = new Properties();
|
||||
for (AuthenticatorConfig.Parameter param : config.getParams()) {
|
||||
properties.setProperty(param.getName(), param.getValue());
|
||||
}
|
||||
authenticator.setProperties(properties);
|
||||
}
|
||||
authenticator.init();
|
||||
repository.addAuthenticator(authenticator);
|
||||
}
|
||||
AuthenticatorFrameworkDataHolder.getInstance().setWebappAuthenticatorRepository(repository);
|
||||
|
||||
@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright (c) 2015, 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.test;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.AfterClass;
|
||||
import org.testng.annotations.BeforeClass;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.utils.ServerConstants;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.AuthenticatorFrameworkException;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.config.AuthenticatorConfig;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.config.WebappAuthenticatorConfig;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class WebappAuthenticatorConfigTest {
|
||||
|
||||
@BeforeClass
|
||||
public void init() {
|
||||
System.setProperty(ServerConstants.CARBON_CONFIG_DIR_PATH, "src/test/resources/config");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConfigInitialization() {
|
||||
try {
|
||||
WebappAuthenticatorConfig.init();
|
||||
|
||||
WebappAuthenticatorConfig config = WebappAuthenticatorConfig.getInstance();
|
||||
Assert.assertNotNull(config);
|
||||
|
||||
List<AuthenticatorConfig> authConfigs = config.getAuthenticators();
|
||||
Assert.assertNotNull(authConfigs);
|
||||
} catch (AuthenticatorFrameworkException e) {
|
||||
Assert.fail("Error occurred while testing webapp authenticator config initialization", e);
|
||||
} catch (Throwable e) {
|
||||
Assert.fail("Unexpected error has been encountered while testing webapp authenticator config " +
|
||||
"initialization", e);
|
||||
}
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public void cleanup() {
|
||||
System.setProperty(ServerConstants.CARBON_CONFIG_DIR_PATH, "");
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,106 @@
|
||||
/*
|
||||
* Copyright (c) 2015, 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.test;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.commons.pool.ObjectPool;
|
||||
import org.apache.commons.pool.impl.GenericObjectPool;
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.Test;
|
||||
import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub;
|
||||
import org.wso2.carbon.webapp.authenticator.framework.Utils.OAuthTokenValidationStubFactory;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
public class WebappAuthenticatorFrameworkUtilTest {
|
||||
|
||||
private static final Log log = LogFactory.getLog(WebappAuthenticatorFrameworkUtilTest.class);
|
||||
|
||||
private static final String TOKEN_VALIDATION_SERVICE_URL = "https://localhost:9443";
|
||||
private static final String ADMIN_USERNAME = "admin";
|
||||
private static final String ADMIN_PASSWORD = "admin";
|
||||
private static final Properties PROPERTIES = new Properties();
|
||||
|
||||
static {
|
||||
PROPERTIES.setProperty("MaxTotalConnections", "100");
|
||||
PROPERTIES.setProperty("MaxConnectionsPerHost", "100");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOAuthTokenValidatorStubPool() {
|
||||
ObjectPool stubs = null;
|
||||
OAuth2TokenValidationServiceStub stub = null;
|
||||
|
||||
try {
|
||||
stubs = new GenericObjectPool(
|
||||
new OAuthTokenValidationStubFactory(
|
||||
TOKEN_VALIDATION_SERVICE_URL, ADMIN_USERNAME, ADMIN_PASSWORD, PROPERTIES));
|
||||
|
||||
stub = (OAuth2TokenValidationServiceStub) stubs.borrowObject();
|
||||
Assert.assertNotNull(stub);
|
||||
} catch (Exception e) {
|
||||
String msg = "Error occurred while borrowing an oauth validator service stub instance from the pool";
|
||||
log.error(msg, e);
|
||||
Assert.fail(msg, e);
|
||||
} finally {
|
||||
if (stubs != null) {
|
||||
try {
|
||||
if (stub != null) {
|
||||
stubs.returnObject(stub);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Error occurred while returning oauth validator service stub instance to the pool", e);
|
||||
}
|
||||
|
||||
/* Checks if the stub instance used above has been properly returned to the pool */
|
||||
Assert.assertEquals(stubs.getNumIdle(), 1);
|
||||
/* Verifies that there's no hanging connections after the operation performed above */
|
||||
Assert.assertEquals(stubs.getNumActive(), 0);
|
||||
|
||||
try {
|
||||
stubs.close();
|
||||
} catch (Exception e) {
|
||||
log.warn("Error occurred while closing the object pool", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expectedExceptions = IllegalArgumentException.class)
|
||||
public void testStubFactoryInitWithInvalidHttpClientProperties() {
|
||||
new OAuthTokenValidationStubFactory(TOKEN_VALIDATION_SERVICE_URL, null, ADMIN_PASSWORD, PROPERTIES);
|
||||
}
|
||||
|
||||
@Test(expectedExceptions = IllegalArgumentException.class)
|
||||
public void testStubFactoryInitWithInvalidUsername() {
|
||||
new OAuthTokenValidationStubFactory(TOKEN_VALIDATION_SERVICE_URL, null, ADMIN_PASSWORD, PROPERTIES);
|
||||
}
|
||||
|
||||
@Test(expectedExceptions = IllegalArgumentException.class)
|
||||
public void testStubFactoryInitWithInvalidPassword() {
|
||||
new OAuthTokenValidationStubFactory(TOKEN_VALIDATION_SERVICE_URL, ADMIN_USERNAME, null, PROPERTIES);
|
||||
}
|
||||
|
||||
@Test(expectedExceptions = IllegalArgumentException.class)
|
||||
public void testStubFactoryInitWithInvalidUrl() {
|
||||
new OAuthTokenValidationStubFactory(null, ADMIN_USERNAME, ADMIN_PASSWORD, PROPERTIES);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,28 @@
|
||||
<WebappAuthenticatorConfig>
|
||||
<Authenticators>
|
||||
<Authenticator>
|
||||
<Name>OAuth</Name>
|
||||
<ClassName>org.wso2.carbon.webapp.authenticator.framework.authenticator.OAuthAuthenticator</ClassName>
|
||||
<Parameters>
|
||||
<Parameter Name="TokenValidationEndpointUrl">https://localhost:9443</Parameter>
|
||||
<Parameter Name="Username">admin</Parameter>
|
||||
<Parameter Name="Password">admin</Parameter>
|
||||
<Parameter Name="IsRemote">true</Parameter>
|
||||
<Parameter Name="MaxConnectionsPerHost">10000</Parameter>
|
||||
<Parameter Name="MaxTotalConnections">10000</Parameter>
|
||||
</Parameters>
|
||||
</Authenticator>
|
||||
<Authenticator>
|
||||
<Name>BasicAuth</Name>
|
||||
<ClassName>org.wso2.carbon.webapp.authenticator.framework.authenticator.BasicAuthAuthenticator</ClassName>
|
||||
</Authenticator>
|
||||
<Authenticator>
|
||||
<Name>JWT</Name>
|
||||
<ClassName>org.wso2.carbon.webapp.authenticator.framework.authenticator.JWTAuthenticator</ClassName>
|
||||
</Authenticator>
|
||||
<Authenticator>
|
||||
<Name>CertificateAuth</Name>
|
||||
<ClassName>org.wso2.carbon.webapp.authenticator.framework.authenticator.CertificateAuthenticator</ClassName>
|
||||
</Authenticator>
|
||||
</Authenticators>
|
||||
</WebappAuthenticatorConfig>
|
||||
@ -0,0 +1,32 @@
|
||||
#
|
||||
# Copyright 2009 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.
|
||||
#
|
||||
|
||||
#
|
||||
# This is the log4j configuration file used by WSO2 Carbon
|
||||
#
|
||||
# IMPORTANT : Please do not remove or change the names of any
|
||||
# of the Appenders defined here. The layout pattern & log file
|
||||
# can be changed using the WSO2 Carbon Management Console, and those
|
||||
# settings will override the settings in this file.
|
||||
#
|
||||
|
||||
log4j.rootLogger=ERROR, STD_OUT
|
||||
|
||||
# Redirect log messages to console
|
||||
log4j.appender.STD_OUT=org.apache.log4j.ConsoleAppender
|
||||
log4j.appender.STD_OUT.Target=System.out
|
||||
log4j.appender.STD_OUT.layout=org.apache.log4j.PatternLayout
|
||||
log4j.appender.STD_OUT.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
|
||||
@ -0,0 +1,37 @@
|
||||
|
||||
<!--
|
||||
~ Copyright (c) 2014, 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.
|
||||
-->
|
||||
|
||||
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
|
||||
|
||||
<suite name="WebappAuthenticatorFramework">
|
||||
<parameter name="useDefaultListeners" value="false"/>
|
||||
|
||||
<test name="WebappAuthenticatorConfigTests" preserve-order="true">
|
||||
<classes>
|
||||
<class name="org.wso2.carbon.webapp.authenticator.framework.test.WebappAuthenticatorConfigTest"/>
|
||||
</classes>
|
||||
</test>
|
||||
|
||||
<test name="WebappAuthenticatorUtilTests" preserve-order="true">
|
||||
<classes>
|
||||
<class name="org.wso2.carbon.webapp.authenticator.framework.test.WebappAuthenticatorFrameworkUtilTest"/>
|
||||
</classes>
|
||||
</test>
|
||||
|
||||
</suite>
|
||||
@ -3,6 +3,14 @@
|
||||
<Authenticator>
|
||||
<Name>OAuth</Name>
|
||||
<ClassName>org.wso2.carbon.webapp.authenticator.framework.authenticator.OAuthAuthenticator</ClassName>
|
||||
<Parameters>
|
||||
<Parameter Name="IsRemote">true</Parameter>
|
||||
<Parameter Name="TokenValidationEndpointUrl">https://localhost:9443</Parameter>
|
||||
<Parameter Name="Username">admin</Parameter>
|
||||
<Parameter Name="Password">admin</Parameter>
|
||||
<Parameter Name="MaxTotalConnections">100</Parameter>
|
||||
<Parameter Name="MaxConnectionsPerHost">100</Parameter>
|
||||
</Parameters>
|
||||
</Authenticator>
|
||||
<Authenticator>
|
||||
<Name>BasicAuth</Name>
|
||||
|
||||
27
pom.xml
27
pom.xml
@ -1263,6 +1263,23 @@
|
||||
<artifactId>neethi</artifactId>
|
||||
<version>${neethi.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-pool.wso2</groupId>
|
||||
<artifactId>commons-pool</artifactId>
|
||||
<version>${commons.pool.wso2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents.wso2</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>${httpcomponents.httpclient.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-httpclient.wso2</groupId>
|
||||
<artifactId>commons-httpclient</artifactId>
|
||||
<version>${commons.httpclient.version}</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
@ -1374,6 +1391,11 @@
|
||||
<artifactId>build-helper-maven-plugin</artifactId>
|
||||
<version>1.8</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.18</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
@ -1556,6 +1578,11 @@
|
||||
|
||||
<!-- Release plugin ID for github-->
|
||||
<project.scm.id>github-scm</project.scm.id>
|
||||
|
||||
<commons.pool.wso2.version>1.5.6.wso2v1</commons.pool.wso2.version>
|
||||
<httpcomponents.httpclient.version>4.2.3.wso2v1</httpcomponents.httpclient.version>
|
||||
<commons.httpclient.version>3.1.0.wso2v2</commons.httpclient.version>
|
||||
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
Loading…
Reference in New Issue
Block a user