Add constants to common class

merge-requests/1/head
warunalakshitha 7 years ago
parent dde525dd91
commit 4c56d65925

@ -23,7 +23,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>remote-session-extension</artifactId> <artifactId>remote-session-extension</artifactId>
<version>4.0.66-SNAPSHOT</version> <version>4.0.87-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>remote-session-extension</artifactId> <artifactId>remote-session-extension</artifactId>
<version>4.0.66-SNAPSHOT</version> <version>4.0.87-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -28,18 +28,18 @@ import java.io.IOException;
public interface RemoteSessionManagementService { public interface RemoteSessionManagementService {
/** /**
* Initialize session based on web socket request .this method use by the device to connect * Initialize session based on web socket request .This method is used by the device to connect
* *
* @param session Web socket RemoteSession * @param session Web socket RemoteSession
* @param deviceType Device Type * @param deviceType Device Type
* @param deviceId Device Id * @param deviceId Device Id
* @throws RemoteSessionManagementException throws when session has errors with accessing device resources * @throws RemoteSessionManagementException throws when session has errors with accessing device resources
*/ */
public void initializeSession(Session session, String deviceType, String deviceId) throws void initializeSession(Session session, String deviceType, String deviceId) throws
RemoteSessionManagementException; RemoteSessionManagementException;
/** /**
* Initialize session based on web socket request . This method use by the device to connect * Initialize session based on web socket request . This method is used by the device to connect
* *
* @param session Web socket RemoteSession * @param session Web socket RemoteSession
* @param deviceType Device Type * @param deviceType Device Type
@ -47,7 +47,7 @@ public interface RemoteSessionManagementService {
* @param operationId Operation Id that device needs to connec * @param operationId Operation Id that device needs to connec
* @throws RemoteSessionManagementException throws when session has errors with accessing device resources * @throws RemoteSessionManagementException throws when session has errors with accessing device resources
*/ */
public void initializeSession(Session session, String deviceType, String deviceId, String operationId) throws void initializeSession(Session session, String deviceType, String deviceId, String operationId) throws
RemoteSessionManagementException; RemoteSessionManagementException;
/** /**
@ -57,7 +57,7 @@ public interface RemoteSessionManagementService {
* @param message Message needs to send to peer connection client * @param message Message needs to send to peer connection client
* @throws RemoteSessionManagementException * @throws RemoteSessionManagementException
*/ */
public void sendMessageToPeer(Session session, String message) throws RemoteSessionManagementException; void sendMessageToPeer(Session session, String message) throws RemoteSessionManagementException;
/** /**
* Send byte message to connected remote device or client * Send byte message to connected remote device or client
@ -66,13 +66,13 @@ public interface RemoteSessionManagementService {
* @param message Message needs to send to peer connection * @param message Message needs to send to peer connection
* @throws RemoteSessionManagementException * @throws RemoteSessionManagementException
*/ */
public void sendMessageToPeer(Session session, byte[] message) throws RemoteSessionManagementException; void sendMessageToPeer(Session session, byte[] message) throws RemoteSessionManagementException;
/** /**
* Close the session * Close the session
* *
* @param session Web socket RemoteSession * @param session Web socket RemoteSession
*/ */
public void endSession(Session session,String closeReason); void endSession(Session session, String closeReason);
} }

@ -47,6 +47,10 @@ import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
/**
* Class @{@link RemoteSessionManagementServiceImpl} is the implementation of @{@link RemoteSessionManagementService}
* which is used manage initial connection, sending messages to peer session, manage and close the session.
*/
public class RemoteSessionManagementServiceImpl implements RemoteSessionManagementService { public class RemoteSessionManagementServiceImpl implements RemoteSessionManagementService {
private static final Log log = LogFactory.getLog(RemoteSessionManagementServiceImpl.class); private static final Log log = LogFactory.getLog(RemoteSessionManagementServiceImpl.class);

@ -27,7 +27,6 @@ import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_
import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.rmi.RemoteException; import java.rmi.RemoteException;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -38,160 +37,161 @@ import java.util.Map;
*/ */
public class OAuthTokenValidator { public class OAuthTokenValidator {
private static String cookie; private static String cookie;
private GenericObjectPool stubs; private GenericObjectPool stubs;
private static Log log = LogFactory.getLog(OAuthTokenValidator.class); private static Log log = LogFactory.getLog(OAuthTokenValidator.class);
private static final String COOKIE_KEY_VALUE_SEPERATOR = "="; private static OAuthTokenValidator oAuthTokenValidator;
private static final String COOKIE_KEYPAIR_SEPERATOR = ";";
private static final String COOKIE = "cookie";
private static final String TOKEN_TYPE = "bearer";
private static final String TOKEN_IDENTIFIER = "websocketToken";
private static final String QUERY_STRING_SEPERATOR = "&";
private static final String QUERY_KEY_VALUE_SEPERATOR = "=";
private static final String QUERY_STRING = "queryString";
private static OAuthTokenValidator oAuthTokenValidator;
public OAuthTokenValidator(Map<String, String> globalProperties) { public OAuthTokenValidator(Map<String, String> globalProperties) {
this.stubs = new GenericObjectPool(new OAuthTokenValidatorStubFactory(globalProperties)); this.stubs = new GenericObjectPool(new OAuthTokenValidatorStubFactory(globalProperties));
} }
/** /**
* This method gets a string accessToken and validates it * This method gets a string accessToken and validates it
* @param webSocketConnectionProperties WebSocket connection information including http headers *
* @return AuthenticationInfo with the validated results. * @param webSocketConnectionProperties WebSocket connection information including http headers
*/ * @return AuthenticationInfo with the validated results.
public AuthenticationInfo validateToken(Map<String, List<String>> webSocketConnectionProperties) { */
String token = getTokenFromSession(webSocketConnectionProperties); public AuthenticationInfo validateToken(Map<String, List<String>> webSocketConnectionProperties) {
if (token == null) { String token = getTokenFromSession(webSocketConnectionProperties);
AuthenticationInfo authenticationInfo = new AuthenticationInfo(); if (token == null) {
authenticationInfo.setAuthenticated(false); AuthenticationInfo authenticationInfo = new AuthenticationInfo();
return authenticationInfo; authenticationInfo.setAuthenticated(false);
} return authenticationInfo;
OAuth2TokenValidationServiceStub tokenValidationServiceStub = null; }
try { OAuth2TokenValidationServiceStub tokenValidationServiceStub = null;
Object stub = this.stubs.borrowObject(); try {
if (stub != null) { Object stub = this.stubs.borrowObject();
tokenValidationServiceStub = (OAuth2TokenValidationServiceStub) stub; if (stub != null) {
if (cookie != null) { tokenValidationServiceStub = (OAuth2TokenValidationServiceStub) stub;
tokenValidationServiceStub._getServiceClient().getOptions().setProperty( if (cookie != null) {
HTTPConstants.COOKIE_STRING, cookie); tokenValidationServiceStub._getServiceClient().getOptions().setProperty(
} HTTPConstants.COOKIE_STRING, cookie);
return getAuthenticationInfo(token, tokenValidationServiceStub); }
} else { return getAuthenticationInfo(token, tokenValidationServiceStub);
log.warn("Stub initialization failed."); } else {
} log.warn("Stub initialization failed.");
} catch (RemoteException e) { }
log.error("Error on connecting with the validation endpoint.", e); } catch (RemoteException e) {
} catch (Exception e) { log.error("Error on connecting with the validation endpoint.", e);
log.error("Error occurred in borrowing an validation stub from the pool.", e); } catch (Exception e) {
log.error("Error occurred in borrowing an validation stub from the pool.", e);
} finally { } finally {
try { try {
if (tokenValidationServiceStub != null) { if (tokenValidationServiceStub != null) {
this.stubs.returnObject(tokenValidationServiceStub); this.stubs.returnObject(tokenValidationServiceStub);
} }
} catch (Exception e) { } catch (Exception e) {
log.warn("Error occurred while returning the object back to the oauth token validation service " + log.warn("Error occurred while returning the object back to the oauth token validation service " +
"stub pool.", e); "stub pool.", e);
} }
} }
AuthenticationInfo authenticationInfo = new AuthenticationInfo(); AuthenticationInfo authenticationInfo = new AuthenticationInfo();
authenticationInfo.setAuthenticated(false); authenticationInfo.setAuthenticated(false);
return authenticationInfo; return authenticationInfo;
} }
/** /**
* This creates an AuthenticationInfo object that is used for authorization. This method will validate the token * This creates an AuthenticationInfo object that is used for authorization. This method will validate the token
* and * and
* sets the required parameters to the object. * sets the required parameters to the object.
* *
* @param token that needs to be validated. * @param token that needs to be validated.
* @param tokenValidationServiceStub stub that is used to call the external service. * @param tokenValidationServiceStub stub that is used to call the external service.
* @return AuthenticationInfo This contains the information related to authenticated client. * @return AuthenticationInfo This contains the information related to authenticated client.
* @throws RemoteException that triggers when failing to call the external service.. * @throws RemoteException that triggers when failing to call the external service..
*/ */
private AuthenticationInfo getAuthenticationInfo(String token, private AuthenticationInfo getAuthenticationInfo(String token,
OAuth2TokenValidationServiceStub tokenValidationServiceStub) OAuth2TokenValidationServiceStub tokenValidationServiceStub)
throws RemoteException { throws RemoteException {
AuthenticationInfo authenticationInfo = new AuthenticationInfo(); AuthenticationInfo authenticationInfo = new AuthenticationInfo();
OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO(); OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO();
OAuth2TokenValidationRequestDTO_OAuth2AccessToken accessToken = OAuth2TokenValidationRequestDTO_OAuth2AccessToken accessToken =
new OAuth2TokenValidationRequestDTO_OAuth2AccessToken(); new OAuth2TokenValidationRequestDTO_OAuth2AccessToken();
accessToken.setTokenType(TOKEN_TYPE); accessToken.setTokenType(RemoteSessionConstants.OAuthTokenValidator.TOKEN_TYPE);
accessToken.setIdentifier(token); accessToken.setIdentifier(token);
validationRequest.setAccessToken(accessToken); validationRequest.setAccessToken(accessToken);
boolean authenticated; boolean authenticated;
OAuth2TokenValidationResponseDTO tokenValidationResponse; OAuth2TokenValidationResponseDTO tokenValidationResponse;
tokenValidationResponse = tokenValidationServiceStub.validate(validationRequest); tokenValidationResponse = tokenValidationServiceStub.validate(validationRequest);
if (tokenValidationResponse == null) { if (tokenValidationResponse == null) {
authenticationInfo.setAuthenticated(false); authenticationInfo.setAuthenticated(false);
return authenticationInfo; return authenticationInfo;
} }
authenticated = tokenValidationResponse.getValid(); authenticated = tokenValidationResponse.getValid();
if (authenticated) { if (authenticated) {
String authorizedUser = tokenValidationResponse.getAuthorizedUser(); String authorizedUser = tokenValidationResponse.getAuthorizedUser();
String username = MultitenantUtils.getTenantAwareUsername(authorizedUser); String username = MultitenantUtils.getTenantAwareUsername(authorizedUser);
String tenantDomain = MultitenantUtils.getTenantDomain(authorizedUser); String tenantDomain = MultitenantUtils.getTenantDomain(authorizedUser);
authenticationInfo.setUsername(username); authenticationInfo.setUsername(username);
authenticationInfo.setTenantDomain(tenantDomain); authenticationInfo.setTenantDomain(tenantDomain);
String scopes[] = tokenValidationResponse.getScope(); String scopes[] = tokenValidationResponse.getScope();
if (scopes != null) { if (scopes != null) {
Map<String, Object> properties = new HashMap<>(); Map<String, Object> properties = new HashMap<>();
properties.put(RemoteSessionConstants.SCOPE_IDENTIFIER, scopes); properties.put(RemoteSessionConstants.SCOPE_IDENTIFIER, scopes);
authenticationInfo.setProperties(properties); authenticationInfo.setProperties(properties);
} }
} else { } else {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Token validation failed for token: " + token); log.debug("Token validation failed for token: " + token);
} }
} }
ServiceContext serviceContext = tokenValidationServiceStub._getServiceClient() ServiceContext serviceContext = tokenValidationServiceStub._getServiceClient()
.getLastOperationContext().getServiceContext(); .getLastOperationContext().getServiceContext();
cookie = (String) serviceContext.getProperty(HTTPConstants.COOKIE_STRING); cookie = (String) serviceContext.getProperty(HTTPConstants.COOKIE_STRING);
authenticationInfo.setAuthenticated(authenticated); authenticationInfo.setAuthenticated(authenticated);
return authenticationInfo; return authenticationInfo;
} }
/** /**
* Retrieving the token from the http header * Retrieving the token from the http header
* @param webSocketConnectionProperties WebSocket connection information including http headers *
* @return retrieved token * @param webSocketConnectionProperties WebSocket connection information including http headers
*/ * @return retrieved token
private String getToken(Map<String, List<String>> webSocketConnectionProperties) { */
String cookieString = webSocketConnectionProperties.get(COOKIE).get(0); private String getToken(Map<String, List<String>> webSocketConnectionProperties) {
String[] properties = cookieString.split(COOKIE_KEYPAIR_SEPERATOR); String cookieString = webSocketConnectionProperties.get(RemoteSessionConstants.OAuthTokenValidator.COOKIE)
String token; .get(0);
for (String keyValuePair: properties) { String[] properties = cookieString.split(RemoteSessionConstants.OAuthTokenValidator.COOKIE_KEYPAIR_SEPERATOR);
if(TOKEN_IDENTIFIER.equals((keyValuePair.split(COOKIE_KEY_VALUE_SEPERATOR)[0]).trim())){ String token;
token = (keyValuePair.split(COOKIE_KEY_VALUE_SEPERATOR)[1]).trim(); for (String keyValuePair : properties) {
return token; if (RemoteSessionConstants.OAuthTokenValidator.TOKEN_IDENTIFIER.equals((keyValuePair.
split(RemoteSessionConstants.OAuthTokenValidator.COOKIE_KEY_VALUE_SEPERATOR)[0]).trim())) {
token = (keyValuePair.split(RemoteSessionConstants.OAuthTokenValidator.COOKIE_KEY_VALUE_SEPERATOR)
[1]).trim();
return token;
} }
} }
log.error("WebSocket token should be specified in cookie"); log.error("WebSocket token should be specified in cookie");
return null; return null;
} }
/** /**
* Retrieving the token from the http session * Retrieving the token from the http session
* @param webSocketConnectionProperties WebSocket connection information including http headers *
* @return retrieved token * @param webSocketConnectionProperties WebSocket connection information including http headers
*/ * @return retrieved token
private String getTokenFromSession(Map<String, List<String>> webSocketConnectionProperties) { */
String queryString = webSocketConnectionProperties.get(QUERY_STRING).get(0); private String getTokenFromSession(Map<String, List<String>> webSocketConnectionProperties) {
if (queryString != null) { String queryString = webSocketConnectionProperties.get(RemoteSessionConstants.OAuthTokenValidator
String[] allQueryParamPairs = queryString.split(QUERY_STRING_SEPERATOR); .QUERY_STRING).get(0);
for (String keyValuePair : allQueryParamPairs) { if (queryString != null) {
String[] queryParamPair = keyValuePair.split(QUERY_KEY_VALUE_SEPERATOR); String[] allQueryParamPairs = queryString.split(RemoteSessionConstants.OAuthTokenValidator
if (queryParamPair.length != 2) { .QUERY_STRING_SEPERATOR);
log.warn("Invalid query string [" + queryString + "] passed in."); for (String keyValuePair : allQueryParamPairs) {
break; String[] queryParamPair = keyValuePair.split(RemoteSessionConstants.OAuthTokenValidator
} .QUERY_KEY_VALUE_SEPERATOR);
if (queryParamPair[0].equals(TOKEN_IDENTIFIER)) { if (queryParamPair.length != 2) {
return queryParamPair[1]; log.warn("Invalid query string [" + queryString + "] passed in.");
} break;
} }
} if (queryParamPair[0].equals(RemoteSessionConstants.OAuthTokenValidator.TOKEN_IDENTIFIER)) {
return null; return queryParamPair[1];
} }
}
}
return null;
}
} }

@ -143,8 +143,7 @@ public class OAuthTokenValidatorStubFactory extends BasePoolableObjectFactory {
*/ */
private EasySSLProtocolSocketFactory createProtocolSocketFactory() throws OAuthTokenValidationException { private EasySSLProtocolSocketFactory createProtocolSocketFactory() throws OAuthTokenValidationException {
try { try {
EasySSLProtocolSocketFactory easySSLPSFactory = new EasySSLProtocolSocketFactory(); return new EasySSLProtocolSocketFactory();
return easySSLPSFactory;
} catch (IOException e) { } catch (IOException e) {
String errorMsg = "Failed to initiate EasySSLProtocolSocketFactory."; String errorMsg = "Failed to initiate EasySSLProtocolSocketFactory.";
throw new OAuthTokenValidationException(errorMsg, e); throw new OAuthTokenValidationException(errorMsg, e);

@ -44,4 +44,21 @@ public class RemoteSessionConstants {
private RemoteSessionConstants() { private RemoteSessionConstants() {
} }
/**
* OAuthTokenValidator specific constants
*/
public final class OAuthTokenValidator {
public static final String COOKIE_KEY_VALUE_SEPERATOR = "=";
public static final String COOKIE_KEYPAIR_SEPERATOR = ";";
public static final String COOKIE = "cookie";
public static final String TOKEN_TYPE = "bearer";
public static final String TOKEN_IDENTIFIER = "websocketToken";
public static final String QUERY_STRING_SEPERATOR = "&";
public static final String QUERY_KEY_VALUE_SEPERATOR = "=";
public static final String QUERY_STRING = "queryString";
private OAuthTokenValidator() {
}
}
} }

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>extensions</artifactId> <artifactId>extensions</artifactId>
<version>4.0.66-SNAPSHOT</version> <version>4.0.87-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -3,14 +3,14 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>extensions-feature</artifactId> <artifactId>extensions-feature</artifactId>
<version>4.0.66-SNAPSHOT</version> <version>4.0.87-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.remote.session.feature</artifactId> <artifactId>org.wso2.carbon.device.mgt.remote.session.feature</artifactId>
<packaging>pom</packaging> <packaging>pom</packaging>
<version>4.0.66-SNAPSHOT</version> <version>4.0.87-SNAPSHOT</version>
<name>WSO2 Carbon - Remote Session Manager</name> <name>WSO2 Carbon - Remote Session Manager</name>
<url>http://wso2.org</url> <url>http://wso2.org</url>
<description>This feature contains the core bundles required iot Remote Sessions</description> <description>This feature contains the core bundles required iot Remote Sessions</description>

Loading…
Cancel
Save