Fix compilation issues in user handler

remotes/1725333865317989910/tmp_refs/heads/master
tcdlpds 1 year ago
parent db3555f59e
commit 66eac3c744

@ -18,21 +18,20 @@
package io.entgra.device.mgt.core.ui.request.interceptor; package io.entgra.device.mgt.core.ui.request.interceptor;
import com.google.gson.Gson; import com.fasterxml.jackson.core.type.TypeReference;
import com.google.gson.JsonElement; import com.fasterxml.jackson.databind.JsonNode;
import com.google.gson.JsonObject; import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonParser; import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData;
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants;
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHeaders; import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder; import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse;
import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.MultipartConfig;
@ -42,11 +41,13 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import java.io.IOException; import java.io.IOException;
import java.util.Map;
@MultipartConfig @MultipartConfig
@WebServlet("/default-oauth2-credentials") @WebServlet("/default-oauth2-credentials")
public class DefaultOauth2TokenHandler extends HttpServlet { public class DefaultOauth2TokenHandler extends HttpServlet {
private static final Log log = LogFactory.getLog(DefaultTokenHandler.class); private static final Log log = LogFactory.getLog(DefaultTokenHandler.class);
private static final long serialVersionUID = 2254408216447549205L;
@Override @Override
@ -80,17 +81,16 @@ public class DefaultOauth2TokenHandler extends HttpServlet {
} }
} }
String iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR ClassicHttpRequest defaultTokenRequest =
ClassicRequestBuilder.get(req.getScheme() + HandlerConstants.SCHEME_SEPARATOR
+ System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR)
+ HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme()); + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme())
String tokenUrl = iotsCoreUrl + "/api/device-mgt/v1.0/devices/" + clientId + "/api/device-mgt/v1.0/devices/" + clientId + HandlerConstants.URI_SEPARATOR
+ "/" + clientSecret + "/default-token" + scopeString; + clientSecret + "/default-token" + scopeString)
.setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, org.apache.hc.core5.http.ContentType.APPLICATION_FORM_URLENCODED.toString())
HttpGet defaultTokenRequest = new HttpGet(tokenUrl); .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken())
defaultTokenRequest .build();
.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken());
defaultTokenRequest
.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString());
ProxyResponse tokenResultResponse = HandlerUtil.execute(defaultTokenRequest); ProxyResponse tokenResultResponse = HandlerUtil.execute(defaultTokenRequest);
if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
@ -98,29 +98,24 @@ public class DefaultOauth2TokenHandler extends HttpServlet {
HandlerUtil.handleError(resp, tokenResultResponse); HandlerUtil.handleError(resp, tokenResultResponse);
return; return;
} }
String tokenResult = tokenResultResponse.getData(); JsonNode tokenResult = tokenResultResponse.getData();
if (tokenResult == null) { if (tokenResult == null) {
log.error("Invalid default token response is received."); log.error("Invalid default token response is received.");
HandlerUtil.handleError(resp, tokenResultResponse); HandlerUtil.handleError(resp, tokenResultResponse);
return; return;
} }
JsonParser jsonParser = new JsonParser();
JsonElement jTokenResult = jsonParser.parse(tokenResult);
if (jTokenResult.isJsonObject()) {
JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
AuthData newDefaultAuthData = new AuthData(); AuthData newDefaultAuthData = new AuthData();
newDefaultAuthData.setClientId(clientId); newDefaultAuthData.setClientId(clientId);
newDefaultAuthData.setClientSecret(clientSecret); newDefaultAuthData.setClientSecret(clientSecret);
String defaultToken = jTokenResultAsJsonObject.get("accessToken").getAsString(); String defaultToken = tokenResult.get("accessToken").asText();
newDefaultAuthData.setAccessToken(defaultToken); newDefaultAuthData.setAccessToken(defaultToken);
newDefaultAuthData.setRefreshToken(jTokenResultAsJsonObject.get("refreshToken").getAsString()); newDefaultAuthData.setRefreshToken(tokenResult.get("refreshToken").asText());
newDefaultAuthData.setScope(jTokenResultAsJsonObject.get("scopes").getAsString()); newDefaultAuthData.setScope(tokenResult.get("scopes").asText());
httpSession.setAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY, newDefaultAuthData); httpSession.setAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY, newDefaultAuthData);
HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultToken)); HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultToken));
}
} else { } else {
HandlerUtil.sendUnAuthorizeResponse(resp); HandlerUtil.sendUnAuthorizeResponse(resp);
} }
@ -152,19 +147,19 @@ public class DefaultOauth2TokenHandler extends HttpServlet {
ub3.setHost(System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR)); ub3.setHost(System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR));
ub3.setPort(Integer.parseInt(System.getProperty(HandlerConstants.IOT_GATEWAY_WEBSOCKET_WS_PORT_ENV_VAR))); ub3.setPort(Integer.parseInt(System.getProperty(HandlerConstants.IOT_GATEWAY_WEBSOCKET_WS_PORT_ENV_VAR)));
JsonObject responseJsonObj = new JsonObject(); ObjectMapper mapper = new ObjectMapper();
responseJsonObj.addProperty("default-access-token", defaultAccessToken); JsonNode node = JsonNodeFactory.instance.objectNode();
responseJsonObj.addProperty("remote-session-base-url", ub.toString()); Map<String, Object> nodeMap = mapper.convertValue(node, new TypeReference<>() {
responseJsonObj.addProperty("secured-websocket-gateway-url", ub2.toString()); });
responseJsonObj.addProperty("unsecured-websocket-gateway-url", ub3.toString()); nodeMap.put("default-access-token", defaultAccessToken);
nodeMap.put("remote-session-base-url", ub.toString());
Gson gson = new Gson(); nodeMap.put("secured-websocket-gateway-url", ub2.toString());
String payload = gson.toJson(responseJsonObj); nodeMap.put("unsecured-websocket-gateway-url", ub3.toString());
ProxyResponse proxyResponse = new ProxyResponse(); ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_OK); proxyResponse.setCode(HttpStatus.SC_OK);
proxyResponse.setStatus(ProxyResponse.Status.SUCCESS); proxyResponse.setStatus(ProxyResponse.Status.SUCCESS);
proxyResponse.setData(payload); proxyResponse.setData(mapper.convertValue(nodeMap, JsonNode.class));
return proxyResponse; return proxyResponse;
} }
} }

@ -18,8 +18,10 @@
package io.entgra.device.mgt.core.ui.request.interceptor; package io.entgra.device.mgt.core.ui.request.interceptor;
import com.google.gson.Gson; import com.fasterxml.jackson.core.type.TypeReference;
import com.google.gson.JsonObject; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse;
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants;
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil;
@ -43,11 +45,13 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import java.io.IOException; import java.io.IOException;
import java.util.Map;
@MultipartConfig @MultipartConfig
@WebServlet("/default-credentials") @WebServlet("/default-credentials")
public class DefaultTokenHandler extends HttpServlet { public class DefaultTokenHandler extends HttpServlet {
private static final Log log = LogFactory.getLog(DefaultTokenHandler.class); private static final Log log = LogFactory.getLog(DefaultTokenHandler.class);
private static final long serialVersionUID = 6356346497117534430L;
@Override @Override
@ -110,19 +114,19 @@ public class DefaultTokenHandler extends HttpServlet {
ub3.setHost(System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR)); ub3.setHost(System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR));
ub3.setPort(Integer.parseInt(System.getProperty(HandlerConstants.IOT_GATEWAY_WEBSOCKET_WS_PORT_ENV_VAR))); ub3.setPort(Integer.parseInt(System.getProperty(HandlerConstants.IOT_GATEWAY_WEBSOCKET_WS_PORT_ENV_VAR)));
JsonObject responseJsonObj = new JsonObject(); ObjectMapper mapper = new ObjectMapper();
responseJsonObj.addProperty("default-access-token", defaultAccessToken); JsonNode node = JsonNodeFactory.instance.objectNode();
responseJsonObj.addProperty("remote-session-base-url", ub.toString()); Map<String, Object> nodeMap = mapper.convertValue(node, new TypeReference<>() {
responseJsonObj.addProperty("secured-websocket-gateway-url", ub2.toString()); });
responseJsonObj.addProperty("unsecured-websocket-gateway-url", ub3.toString()); nodeMap.put("default-access-token", defaultAccessToken);
nodeMap.put("remote-session-base-url", ub.toString());
Gson gson = new Gson(); nodeMap.put("secured-websocket-gateway-url", ub2.toString());
String payload = gson.toJson(responseJsonObj); nodeMap.put("unsecured-websocket-gateway-url", ub3.toString());
ProxyResponse proxyResponse = new ProxyResponse(); ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_OK); proxyResponse.setCode(HttpStatus.SC_OK);
proxyResponse.setStatus(ProxyResponse.Status.SUCCESS); proxyResponse.setStatus(ProxyResponse.Status.SUCCESS);
proxyResponse.setData(payload); proxyResponse.setData(mapper.convertValue(nodeMap, JsonNode.class));
return proxyResponse; return proxyResponse;
} }
} }

@ -18,17 +18,15 @@
package io.entgra.device.mgt.core.ui.request.interceptor; package io.entgra.device.mgt.core.ui.request.interceptor;
import com.google.gson.JsonObject; import com.fasterxml.jackson.databind.JsonNode;
import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse;
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants;
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
import org.apache.http.HttpHeaders; import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet; import javax.servlet.annotation.WebServlet;
@ -52,7 +50,7 @@ public class HubspotHandler extends HttpServlet {
private HttpSession httpSession; private HttpSession httpSession;
private static String hubspotEndpoint; private static String hubspotEndpoint;
private static String chatConfig; private static String chatConfig;
private JsonObject uiConfigJsonObject; private JsonNode uiConfigJsonObject;
private static String gatewayUrl; private static String gatewayUrl;
private static String iotsCoreUrl; private static String iotsCoreUrl;
@ -60,12 +58,12 @@ public class HubspotHandler extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp) { protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
try { try {
if (validateRequest(req, resp)) { if (validateRequest(req, resp)) {
HttpPost postRequest = new HttpPost(HandlerUtil.generateBackendRequestURL(req, hubspotEndpoint)); ClassicHttpRequest postRequest = ClassicRequestBuilder.post(HandlerUtil.generateBackendRequestURL(req, hubspotEndpoint))
.setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, "application/json")
.setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig)
.build();
HandlerUtil.generateChatRequestEntity(req, postRequest); HandlerUtil.generateChatRequestEntity(req, postRequest);
postRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); HandlerUtil.handleSuccess(resp, HandlerUtil.execute(postRequest));
postRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig);
ProxyResponse proxyResponse = HandlerUtil.execute(postRequest);
HandlerUtil.handleSuccess(resp, proxyResponse);
} }
} catch (IOException e) { } catch (IOException e) {
log.error("Error occurred when processing POST request.", e); log.error("Error occurred when processing POST request.", e);
@ -76,11 +74,12 @@ public class HubspotHandler extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) { protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
try { try {
if (validateRequest(req, resp)) { if (validateRequest(req, resp)) {
HttpGet getRequest = new HttpGet(HandlerUtil.generateBackendRequestURL(req,hubspotEndpoint)); ClassicHttpRequest getRequest =
getRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); ClassicRequestBuilder.get(HandlerUtil.generateBackendRequestURL(req, hubspotEndpoint))
getRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig); .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, "application/json")
ProxyResponse proxyResponse = HandlerUtil.execute(getRequest); .setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION,
HandlerUtil.handleSuccess(resp, proxyResponse); HandlerConstants.BEARER + chatConfig).build();
HandlerUtil.handleSuccess(resp, HandlerUtil.execute(getRequest));
} }
} catch (IOException e) { } catch (IOException e) {
log.error("Error occurred when processing GET request.", e); log.error("Error occurred when processing GET request.", e);
@ -88,16 +87,20 @@ public class HubspotHandler extends HttpServlet {
} }
@Override @Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp){ protected void doDelete(HttpServletRequest req, HttpServletResponse resp) {
try{ try {
if(validateRequest(req, resp)){ if (validateRequest(req, resp)) {
HttpDelete deleteRequest = new HttpDelete(HandlerUtil.generateBackendRequestURL(req,hubspotEndpoint)); ClassicHttpRequest deleteRequest =
ClassicRequestBuilder.delete(HandlerUtil.generateBackendRequestURL(req, hubspotEndpoint))
.setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, "application/json")
.setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION,
HandlerConstants.BEARER + chatConfig).build();
deleteRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); deleteRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
deleteRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig); deleteRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig);
ProxyResponse proxyResponse = HandlerUtil.execute(deleteRequest); HandlerUtil.handleSuccess(resp, HandlerUtil.execute(deleteRequest));
HandlerUtil.handleSuccess(resp, proxyResponse);
} }
} catch (IOException e){ } catch (IOException e) {
log.error("Error occurred when processing DELETE request.", e); log.error("Error occurred when processing DELETE request.", e);
} }
} }
@ -129,7 +132,7 @@ public class HubspotHandler extends HttpServlet {
+ HandlerConstants.COLON + HandlerUtil.getCorePort(req.getScheme()); + HandlerConstants.COLON + HandlerUtil.getCorePort(req.getScheme());
String uiConfigUrl = iotsCoreUrl + HandlerConstants.UI_CONFIG_ENDPOINT; String uiConfigUrl = iotsCoreUrl + HandlerConstants.UI_CONFIG_ENDPOINT;
uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, resp); uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, resp);
chatConfig = uiConfigJsonObject.get("hubspotChat").getAsJsonObject().get("accessToken").getAsString(); chatConfig = uiConfigJsonObject.get("hubspotChat").get("accessToken").textValue();
hubspotEndpoint = HandlerConstants.HTTPS_PROTOCOL + HandlerConstants.SCHEME_SEPARATOR + HandlerConstants.HUBSPOT_CHAT_URL; hubspotEndpoint = HandlerConstants.HTTPS_PROTOCOL + HandlerConstants.SCHEME_SEPARATOR + HandlerConstants.HUBSPOT_CHAT_URL;
return true; return true;
} }

@ -18,6 +18,7 @@
package io.entgra.device.mgt.core.ui.request.interceptor; package io.entgra.device.mgt.core.ui.request.interceptor;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.gson.*; import com.google.gson.*;
import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData;
import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse;
@ -68,7 +69,8 @@ public class LoginHandler extends HttpServlet {
} }
httpSession = req.getSession(true); httpSession = req.getSession(true);
JsonObject uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, resp); JsonNode uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession,
resp);
JsonArray tags = uiConfigJsonObject.get("appRegistration").getAsJsonObject().get("tags").getAsJsonArray(); JsonArray tags = uiConfigJsonObject.get("appRegistration").getAsJsonObject().get("tags").getAsJsonArray();
JsonArray scopes = uiConfigJsonObject.get("scopes").getAsJsonArray(); JsonArray scopes = uiConfigJsonObject.get("scopes").getAsJsonArray();
int sessionTimeOut = Integer.parseInt(String.valueOf(uiConfigJsonObject.get("sessionTimeOut"))); int sessionTimeOut = Integer.parseInt(String.valueOf(uiConfigJsonObject.get("sessionTimeOut")));
@ -225,7 +227,7 @@ public class LoginHandler extends HttpServlet {
* @return Invoke token endpoint and return the response as string. * @return Invoke token endpoint and return the response as string.
* @throws IOException IO exception throws if an error occurred when invoking token endpoint * @throws IOException IO exception throws if an error occurred when invoking token endpoint
*/ */
private ProxyResponse getTokenResult(String encodedClientApp, JsonArray scopes) throws IOException { private ProxyResponse getTokenResult(String encodedClientApp, JsonNode scopes) throws IOException {
HttpPost tokenEndpoint = new HttpPost(gatewayUrl + HandlerConstants.INTERNAL_TOKEN_ENDPOINT); HttpPost tokenEndpoint = new HttpPost(gatewayUrl + HandlerConstants.INTERNAL_TOKEN_ENDPOINT);
tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + encodedClientApp); tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + encodedClientApp);
tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString());

@ -18,15 +18,17 @@
package io.entgra.device.mgt.core.ui.request.interceptor; package io.entgra.device.mgt.core.ui.request.interceptor;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData;
import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse;
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants;
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet; import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServlet;
@ -34,12 +36,15 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import java.io.IOException; import java.io.IOException;
import java.util.Map;
@MultipartConfig @MultipartConfig
@WebServlet("/login-user/scopes") @WebServlet("/login-user/scopes")
public class PermissionScopeHandler extends HttpServlet { public class PermissionScopeHandler extends HttpServlet {
private static final long serialVersionUID = 976006906915355611L;
@Override @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
HttpSession httpSession = req.getSession(false); HttpSession httpSession = req.getSession(false);
if (httpSession == null) { if (httpSession == null) {
HandlerUtil.sendUnAuthorizeResponse(resp); HandlerUtil.sendUnAuthorizeResponse(resp);
@ -54,11 +59,15 @@ public class PermissionScopeHandler extends HttpServlet {
if (!StringUtils.isEmpty(authData.getScope())) { if (!StringUtils.isEmpty(authData.getScope())) {
ProxyResponse proxyResponse = new ProxyResponse(); ProxyResponse proxyResponse = new ProxyResponse();
JSONObject jsonObject = new JSONObject();
jsonObject.put(HandlerConstants.USER_SCOPES, authData.getScope()); ObjectMapper mapper = new ObjectMapper();
JsonNode node = JsonNodeFactory.instance.objectNode();
Map<String, Object> nodeMap = mapper.convertValue(node, new TypeReference<>() {
});
nodeMap.put(HandlerConstants.USER_SCOPES, authData.getScope());
proxyResponse.setCode(HttpStatus.SC_OK); proxyResponse.setCode(HttpStatus.SC_OK);
proxyResponse.setStatus(ProxyResponse.Status.SUCCESS); proxyResponse.setStatus(ProxyResponse.Status.SUCCESS);
proxyResponse.setData(jsonObject.toString()); proxyResponse.setData(mapper.convertValue(nodeMap, JsonNode.class));
HandlerUtil.handleSuccess(resp, proxyResponse); HandlerUtil.handleSuccess(resp, proxyResponse);
return; return;
} }

@ -18,20 +18,18 @@
package io.entgra.device.mgt.core.ui.request.interceptor; package io.entgra.device.mgt.core.ui.request.interceptor;
import com.google.gson.JsonElement; import com.fasterxml.jackson.databind.JsonNode;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData;
import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse;
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants;
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHeaders; import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.http.HttpStatus; import org.apache.hc.core5.http.ContentType;
import org.apache.http.client.methods.HttpPost; import org.apache.hc.core5.http.HttpStatus;
import org.apache.http.entity.ContentType; import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.http.entity.StringEntity; import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet; import javax.servlet.annotation.WebServlet;
@ -75,33 +73,35 @@ public class SsoLoginCallbackHandler extends HttpServlet {
} }
String scope = session.getAttribute("scope").toString(); String scope = session.getAttribute("scope").toString();
HttpPost tokenEndpoint = new HttpPost(keyManagerUrl + HandlerConstants.OAUTH2_TOKEN_ENDPOINT);
tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + session.getAttribute("encodedClientApp"));
tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString());
String loginCallbackUrl = iotsCoreUrl + req.getContextPath() + HandlerConstants.SSO_LOGIN_CALLBACK; String loginCallbackUrl = iotsCoreUrl + req.getContextPath() + HandlerConstants.SSO_LOGIN_CALLBACK;
StringEntity tokenEPPayload = new StringEntity( StringEntity tokenEPPayload = new StringEntity(
"grant_type=" + HandlerConstants.CODE_GRANT_TYPE + "&code=" + code + "&scope=" + scope + "grant_type=" + HandlerConstants.CODE_GRANT_TYPE + "&code=" + code + "&scope=" + scope +
"&redirect_uri=" + loginCallbackUrl, "&redirect_uri=" + loginCallbackUrl,
ContentType.APPLICATION_FORM_URLENCODED); ContentType.APPLICATION_FORM_URLENCODED);
tokenEndpoint.setEntity(tokenEPPayload);
ClassicHttpRequest tokenEndpoint = ClassicRequestBuilder.post(keyManagerUrl + HandlerConstants.OAUTH2_TOKEN_ENDPOINT)
.setEntity(tokenEPPayload)
.setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE, org.apache.hc.core5.http.ContentType.APPLICATION_FORM_URLENCODED.toString())
.setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + session.getAttribute("encodedClientApp"))
.build();
ProxyResponse tokenResultResponse = HandlerUtil.execute(tokenEndpoint); ProxyResponse tokenResultResponse = HandlerUtil.execute(tokenEndpoint);
JsonNode jsonNode = tokenResultResponse.getData();
JsonParser jsonParser = new JsonParser(); if (jsonNode != null) {
JsonElement jTokenResult = jsonParser.parse(tokenResultResponse.getData());
if (jTokenResult.isJsonObject()) {
JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
AuthData authData = new AuthData(); AuthData authData = new AuthData();
authData.setClientId(session.getAttribute("clientId").toString()); authData.setClientId(session.getAttribute("clientId").toString());
authData.setClientSecret(session.getAttribute("clientSecret").toString()); authData.setClientSecret(session.getAttribute("clientSecret").toString());
authData.setEncodedClientApp(session.getAttribute("encodedClientApp").toString()); authData.setEncodedClientApp(session.getAttribute("encodedClientApp").toString());
authData.setAccessToken(jTokenResultAsJsonObject.get("access_token").getAsString()); authData.setAccessToken(jsonNode.get("access_token").textValue());
authData.setRefreshToken(jTokenResultAsJsonObject.get("refresh_token").getAsString()); authData.setRefreshToken(jsonNode.get("refresh_token").textValue());
authData.setScope(jTokenResultAsJsonObject.get("scope").getAsString()); authData.setScope(jsonNode.get("scope").textValue());
session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, authData); session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, authData);
resp.sendRedirect(session.getAttribute("redirectUrl").toString()); resp.sendRedirect(session.getAttribute("redirectUrl").toString());
} else {
log.error("Found empty response for token call.");
HandlerUtil.handleError(resp, HandlerConstants.INTERNAL_ERROR_CODE);
} }
} }
} }

@ -18,7 +18,8 @@
package io.entgra.device.mgt.core.ui.request.interceptor; package io.entgra.device.mgt.core.ui.request.interceptor;
import com.google.gson.*; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse;
import io.entgra.device.mgt.core.ui.request.interceptor.cache.LoginCache; import io.entgra.device.mgt.core.ui.request.interceptor.cache.LoginCache;
import io.entgra.device.mgt.core.ui.request.interceptor.cache.OAuthApp; import io.entgra.device.mgt.core.ui.request.interceptor.cache.OAuthApp;
@ -26,21 +27,12 @@ import io.entgra.device.mgt.core.ui.request.interceptor.cache.OAuthAppCacheKey;
import io.entgra.device.mgt.core.ui.request.interceptor.exceptions.LoginException; import io.entgra.device.mgt.core.ui.request.interceptor.exceptions.LoginException;
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants;
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil;
import org.apache.commons.lang.text.StrSubstitutor;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHeaders; import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.MultipartConfig;
@ -54,30 +46,25 @@ import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.StringReader; import java.util.ArrayList;
import java.util.Base64; import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
@MultipartConfig @MultipartConfig
@WebServlet("/ssoLogin") @WebServlet("/ssoLogin")
public class SsoLoginHandler extends HttpServlet { public class SsoLoginHandler extends HttpServlet {
private static final Log log = LogFactory.getLog(SsoLoginHandler.class); private static final Log log = LogFactory.getLog(SsoLoginHandler.class);
private static final long serialVersionUID = 5594017767311123453L;
private static String adminUsername; private static String adminUsername;
private static String adminPassword; private static String adminPassword;
private static String gatewayUrl; private static String gatewayUrl;
private static String iotsCoreUrl; private static String iotSCoreUrl;
private static String apiMgtUrl;
private static String keyManagerUrl;
private static int sessionTimeOut; private static int sessionTimeOut;
private static String encodedAdminCredentials;
private static String encodedClientApp; private static String encodedClientApp;
private static String applicationId;
private static String applicationName; private static String applicationName;
private static String baseContextPath; private static String baseContextPath;
private JsonObject uiConfigJsonObject; private JsonNode uiConfigJsonObject;
private HttpSession httpSession; private HttpSession httpSession;
private LoginCache loginCache; private LoginCache loginCache;
private OAuthApp oAuthApp; private OAuthApp oAuthApp;
@ -101,15 +88,14 @@ public class SsoLoginHandler extends HttpServlet {
gatewayUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) gatewayUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR)
+ HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme()); + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme());
iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR) iotSCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR)
+ HandlerConstants.COLON + HandlerUtil.getCorePort(req.getScheme()); + HandlerConstants.COLON + HandlerUtil.getCorePort(req.getScheme());
apiMgtUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_APIM_HOST_ENV_VAR) String keyManagerUrl =
+ HandlerConstants.COLON + HandlerUtil.getAPIManagerPort(req.getScheme()); req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_KM_HOST_ENV_VAR)
keyManagerUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_KM_HOST_ENV_VAR)
+ HandlerConstants.COLON + HandlerUtil.getKeyManagerPort(req.getScheme()); + HandlerConstants.COLON + HandlerUtil.getKeyManagerPort(req.getScheme());
// Fetch ui config and persists in session // Fetch ui config and persists in session
String uiConfigUrl = iotsCoreUrl + HandlerConstants.UI_CONFIG_ENDPOINT; String uiConfigUrl = iotSCoreUrl + HandlerConstants.UI_CONFIG_ENDPOINT;
uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, resp); uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, resp);
// Retrieving login cache and do a DCR if the cache is not available. // Retrieving login cache and do a DCR if the cache is not available.
@ -121,9 +107,10 @@ public class SsoLoginHandler extends HttpServlet {
} }
String clientId = oAuthApp.getClientId(); String clientId = oAuthApp.getClientId();
JsonArray scopesSsoJson = uiConfigJsonObject.get("scopes").getAsJsonArray();
String scopesSsoString = HandlerUtil.getScopeString(scopesSsoJson); JsonNode scopeJsonNode = uiConfigJsonObject.get("scopes");
String loginCallbackUrl = iotsCoreUrl + baseContextPath + HandlerConstants.SSO_LOGIN_CALLBACK; String scopesSsoString = HandlerUtil.getScopeString(scopeJsonNode);
String loginCallbackUrl = iotSCoreUrl + baseContextPath + HandlerConstants.SSO_LOGIN_CALLBACK;
persistAuthSessionData(req, oAuthApp.getClientId(), oAuthApp.getClientSecret(), persistAuthSessionData(req, oAuthApp.getClientId(), oAuthApp.getClientSecret(),
oAuthApp.getEncodedClientApp(), scopesSsoString, state); oAuthApp.getEncodedClientApp(), scopesSsoString, state);
resp.sendRedirect(keyManagerUrl + HandlerConstants.AUTHORIZATION_ENDPOINT + resp.sendRedirect(keyManagerUrl + HandlerConstants.AUTHORIZATION_ENDPOINT +
@ -134,8 +121,6 @@ public class SsoLoginHandler extends HttpServlet {
"&redirect_uri=" + loginCallbackUrl); "&redirect_uri=" + loginCallbackUrl);
} catch (IOException e) { } catch (IOException e) {
log.error("Error occurred while sending the response into the socket. ", e); log.error("Error occurred while sending the response into the socket. ", e);
} catch (JsonSyntaxException e) {
log.error("Error occurred while parsing the response. ", e);
} catch (ParserConfigurationException e) { } catch (ParserConfigurationException e) {
log.error("Error while creating the document builder."); log.error("Error while creating the document builder.");
} catch (SAXException e) { } catch (SAXException e) {
@ -154,34 +139,32 @@ public class SsoLoginHandler extends HttpServlet {
*/ */
private void dynamicClientRegistration(HttpServletRequest req, HttpServletResponse resp) throws LoginException { private void dynamicClientRegistration(HttpServletRequest req, HttpServletResponse resp) throws LoginException {
try { try {
JsonArray tags = uiConfigJsonObject.get("appRegistration").getAsJsonObject().get("tags").getAsJsonArray(); ArrayNode tags = (ArrayNode) uiConfigJsonObject.get("appRegistration").get("tags");
JsonArray scopes = uiConfigJsonObject.get("scopes").getAsJsonArray(); JsonNode scopes = uiConfigJsonObject.get("scopes");
sessionTimeOut = Integer.parseInt(String.valueOf(uiConfigJsonObject.get("sessionTimeOut"))); sessionTimeOut = Integer.parseInt(String.valueOf(uiConfigJsonObject.get("sessionTimeOut")));
JsonArray supportedGrantTypes = constructAppGrantTypeUpdateArray(); String callbackUrl = iotSCoreUrl + baseContextPath + HandlerConstants.SSO_LOGIN_CALLBACK;
String callbackUrl = iotsCoreUrl + baseContextPath + HandlerConstants.SSO_LOGIN_CALLBACK;
// Register the client application String encodedAdminCredentials = Base64.getEncoder()
HttpPost apiRegEndpoint = new HttpPost(gatewayUrl + HandlerConstants.APP_REG_ENDPOINT);
encodedAdminCredentials = Base64.getEncoder()
.encodeToString((adminUsername + HandlerConstants.COLON + adminPassword).getBytes()); .encodeToString((adminUsername + HandlerConstants.COLON + adminPassword).getBytes());
apiRegEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + ClassicHttpRequest apiRegEndpoint = ClassicRequestBuilder.post(gatewayUrl + HandlerConstants.APP_REG_ENDPOINT)
encodedAdminCredentials); .setEntity(HandlerUtil.constructAppRegPayload(tags, applicationName, adminUsername, adminPassword,
apiRegEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); callbackUrl, constructAppGrantTypeUpdateArray()))
apiRegEndpoint.setEntity(HandlerUtil.constructAppRegPayload(tags, applicationName, adminUsername, adminPassword, .setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE,
callbackUrl, supportedGrantTypes)); org.apache.hc.core5.http.ContentType.APPLICATION_JSON.toString())
.setHeader(org.apache.hc.core5.http.HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC +
encodedAdminCredentials)
.build();
ProxyResponse clientAppResponse = HandlerUtil.execute(apiRegEndpoint); ProxyResponse clientAppResponse = HandlerUtil.execute(apiRegEndpoint);
if (clientAppResponse.getCode() == HttpStatus.SC_CREATED) { if (clientAppResponse.getCode() == HttpStatus.SC_CREATED) {
JsonParser jsonParser = new JsonParser();
JsonElement jClientAppResult = jsonParser.parse(clientAppResponse.getData());
String clientId = null; String clientId = null;
String clientSecret = null; String clientSecret = null;
JsonNode jsonNode = clientAppResponse.getData();
if (jClientAppResult.isJsonObject()) { if (jsonNode != null) {
JsonObject jClientAppResultAsJsonObject = jClientAppResult.getAsJsonObject(); clientId = jsonNode.get("client_id").textValue();
clientId = jClientAppResultAsJsonObject.get("client_id").getAsString(); clientSecret = jsonNode.get("client_secret").textValue();
clientSecret = jClientAppResultAsJsonObject.get("client_secret").getAsString();
encodedClientApp = Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes()); encodedClientApp = Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes());
String scopesString = HandlerUtil.getScopeString(scopes); String scopesString = HandlerUtil.getScopeString(scopes);
persistAuthSessionData(req, clientId, clientSecret, encodedClientApp, scopesString, state); persistAuthSessionData(req, clientId, clientSecret, encodedClientApp, scopesString, state);
@ -206,8 +189,6 @@ public class SsoLoginHandler extends HttpServlet {
} }
} catch (IOException e) { } catch (IOException e) {
throw new LoginException("Error occurred while sending the response into the socket.", e); throw new LoginException("Error occurred while sending the response into the socket.", e);
} catch (JsonSyntaxException e) {
throw new LoginException("Error occurred while parsing the response.", e);
} }
} }
@ -228,7 +209,6 @@ public class SsoLoginHandler extends HttpServlet {
adminPassword = doc.getElementsByTagName("Password").item(0).getTextContent(); adminPassword = doc.getElementsByTagName("Password").item(0).getTextContent();
} }
/** /**
* Persist the Auth data inside the session * Persist the Auth data inside the session
* *
@ -253,64 +233,14 @@ public class SsoLoginHandler extends HttpServlet {
/*** /***
* Generates payload for application grant_type update payload * Generates payload for application grant_type update payload
* *
* @return {@link JsonArray} of the payload to update application grant type * @return {@link ArrayList<String>} of the payload to update application grant type
*/ */
private JsonArray constructAppGrantTypeUpdateArray() { private ArrayList<String> constructAppGrantTypeUpdateArray() {
JsonArray jsonArray = new JsonArray(); ArrayList<String> jsonArray = new ArrayList<>();
jsonArray.add(HandlerConstants.CODE_GRANT_TYPE); jsonArray.add(HandlerConstants.CODE_GRANT_TYPE);
jsonArray.add(HandlerConstants.REFRESH_TOKEN_GRANT_TYPE); jsonArray.add(HandlerConstants.REFRESH_TOKEN_GRANT_TYPE);
jsonArray.add(HandlerConstants.PASSWORD_GRANT_TYPE); jsonArray.add(HandlerConstants.PASSWORD_GRANT_TYPE);
jsonArray.add(HandlerConstants.JWT_BEARER_GRANT_TYPE); jsonArray.add(HandlerConstants.JWT_BEARER_GRANT_TYPE);
return jsonArray; return jsonArray;
} }
/***
* Generates tokens using password grant_type by invoking token endpoint
*
* @param encodedClientApp - Base64 encoded clientId:clientSecret.
* @return Invoke token endpoint and return the response as string.
* @throws IOException IO exception throws if an error occurred when invoking token endpoint
*/
private ProxyResponse getTokenResult(String encodedClientApp) throws IOException {
HttpPost tokenEndpoint = new HttpPost(keyManagerUrl + HandlerConstants.OAUTH2_TOKEN_ENDPOINT);
tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + encodedClientApp);
tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString());
StringEntity tokenEPPayload = new StringEntity(
"grant_type=" + HandlerConstants.PASSWORD_GRANT_TYPE + "&username=" + adminUsername + "&password=" + adminPassword +
"&scope=apim:api_view apim:api_create apim:api_publish apim:subscribe",
ContentType.APPLICATION_FORM_URLENCODED);
tokenEndpoint.setEntity(tokenEPPayload);
return HandlerUtil.execute(tokenEndpoint);
}
/***
* Retrieves and returns access token
*
* @param resp - Http Servlet Response
* @param encodedClientApp - Base64 encoded clientId:clientSecret.
* @return Returns access token
* @throws IOException IO exception throws if an error occurred when invoking token endpoint
*/
private String getAccessToken(HttpServletResponse resp, String encodedClientApp) throws IOException {
ProxyResponse tokenResultResponse = getTokenResult(encodedClientApp);
if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
log.error("Error occurred while invoking the API to get token data.");
HandlerUtil.handleError(resp, tokenResultResponse);
}
String tokenResult = tokenResultResponse.getData();
if (tokenResult == null) {
log.error("Invalid token response is received.");
HandlerUtil.handleError(resp, tokenResultResponse);
}
JsonParser jsonParser = new JsonParser();
JsonElement jTokenResult = jsonParser.parse(tokenResult);
JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
return jTokenResultAsJsonObject.get("access_token").getAsString();
}
} }

@ -18,13 +18,9 @@
package io.entgra.device.mgt.core.ui.request.interceptor; package io.entgra.device.mgt.core.ui.request.interceptor;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException; import com.google.gson.JsonSyntaxException;
import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager;
import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig;
@ -36,8 +32,11 @@ import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse;
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants;
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.core5.http.*; import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.io.entity.HttpEntities; import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
import org.apache.hc.core5.http.message.BasicNameValuePair; import org.apache.hc.core5.http.message.BasicNameValuePair;
@ -63,7 +62,7 @@ public class UserHandler extends HttpServlet {
@Override @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) { protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
try { try {
String keymanagerUrl = String keyManagerUrl =
req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + req.getScheme() + HandlerConstants.SCHEME_SEPARATOR +
System.getProperty(HandlerConstants.IOT_KM_HOST_ENV_VAR) System.getProperty(HandlerConstants.IOT_KM_HOST_ENV_VAR)
+ HandlerConstants.COLON + HandlerUtil.getKeyManagerPort(req.getScheme()); + HandlerConstants.COLON + HandlerUtil.getKeyManagerPort(req.getScheme());
@ -80,39 +79,24 @@ public class UserHandler extends HttpServlet {
} }
String accessToken = authData.getAccessToken(); String accessToken = authData.getAccessToken();
// String accessTokenWithoutPrefix = accessToken.substring(accessToken.indexOf("_") + 1);
HttpPost tokenEndpoint = new HttpPost(keymanagerUrl + HandlerConstants.INTROSPECT_ENDPOINT);
tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString());
DeviceManagementConfig dmc = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); DeviceManagementConfig dmc = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
String adminUsername = dmc.getKeyManagerConfigurations().getAdminUsername(); String adminUsername = dmc.getKeyManagerConfigurations().getAdminUsername();
String adminPassword = dmc.getKeyManagerConfigurations().getAdminPassword(); String adminPassword = dmc.getKeyManagerConfigurations().getAdminPassword();
tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder()
.encodeToString((adminUsername + HandlerConstants.COLON + adminPassword).getBytes()));
StringEntity tokenEPPayload = new StringEntity("token=" + accessToken,
ContentType.APPLICATION_FORM_URLENCODED);
tokenEndpoint.setEntity(tokenEPPayload);
JsonFactory jsonFactory = new JsonFactory();
ObjectMapper objectMapper = new ObjectMapper(jsonFactory);
List<NameValuePair> nvps = new ArrayList<>(); List<NameValuePair> nameValuePairs = new ArrayList<>();
nvps.add(new BasicNameValuePair("token", accessToken)); nameValuePairs.add(new BasicNameValuePair("token", accessToken));
// nvps.add(new BasicNameValuePair("password", "secret"));
ClassicHttpRequest httpPost = ClassicRequestBuilder.post(keymanagerUrl + HandlerConstants.INTROSPECT_ENDPOINT) ClassicHttpRequest introspectCall = ClassicRequestBuilder.post(keyManagerUrl + HandlerConstants.INTROSPECT_ENDPOINT)
.setEntity(new UrlEncodedFormEntity(nvps)) .setEntity(new UrlEncodedFormEntity(nameValuePairs))
.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()) .setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString())
.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder().encodeToString((adminUsername + HandlerConstants.COLON + adminPassword).getBytes())) .setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder().encodeToString((adminUsername + HandlerConstants.COLON + adminPassword).getBytes()))
.build(); .build();
ProxyResponse tokenStatus = HandlerUtil.execute(introspectCall);
ProxyResponse tokenStatus = HandlerUtil.execute(httpPost);
if (tokenStatus.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { if (tokenStatus.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
if (tokenStatus.getCode() == HttpStatus.SC_UNAUTHORIZED) { if (tokenStatus.getCode() == HttpStatus.SC_UNAUTHORIZED) {
tokenStatus = HandlerUtil.retryRequestWithRefreshedToken(req, tokenEndpoint, keymanagerUrl); tokenStatus = HandlerUtil.retryRequestWithRefreshedToken(req, introspectCall, keyManagerUrl);
if(!HandlerUtil.isResponseSuccessful(tokenStatus)) { if (!HandlerUtil.isResponseSuccessful(tokenStatus)) {
HandlerUtil.handleError(resp, tokenStatus); HandlerUtil.handleError(resp, tokenStatus);
return; return;
} }
@ -136,38 +120,17 @@ public class UserHandler extends HttpServlet {
ProxyResponse proxyResponse = new ProxyResponse(); ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setStatus(ProxyResponse.Status.SUCCESS); proxyResponse.setStatus(ProxyResponse.Status.SUCCESS);
proxyResponse.setCode(HttpStatus.SC_OK); proxyResponse.setCode(HttpStatus.SC_OK);
// proxyResponse.setData(
// tokenData.get("username").textValue().replaceAll("@carbon.super", ""));
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
Map<String, Object> nodeMap = mapper.convertValue(tokenData, new TypeReference<Map<String, Object>>(){}); Map<String, Object> nodeMap = mapper.convertValue(tokenData, new TypeReference<>() {
});
nodeMap.put("username", tokenData.get("username").textValue().replaceAll("@carbon.super", "")); nodeMap.put("username", tokenData.get("username").textValue().replaceAll("@carbon.super", ""));
proxyResponse.setData(mapper.convertValue(nodeMap, JsonNode.class)); proxyResponse.setData(mapper.convertValue(nodeMap, JsonNode.class));
// tokenData = ;
HandlerUtil.handleSuccess(resp, proxyResponse); HandlerUtil.handleSuccess(resp, proxyResponse);
httpSession.setAttribute(HandlerConstants.USERNAME_WITH_DOMAIN, jTokenResultAsJsonObject.get("username").getAsString()); httpSession.setAttribute(HandlerConstants.USERNAME_WITH_DOMAIN, nodeMap.get("username").toString());
log.info("Customer login", userLogContextBuilder.setUserName(proxyResponse.getData()).setUserRegistered(true).build()); log.info("Customer login",
userLogContextBuilder.setUserName(nodeMap.get("username").toString()).setUserRegistered(true).build());
// JsonParser jsonParser = new JsonParser();
// JsonElement jTokenResult = jsonParser.parse(tokenData);
// if (jTokenResult.isJsonObject()) {
// JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
// if (!jTokenResultAsJsonObject.get("active").getAsBoolean()) {
// HandlerUtil.sendUnAuthorizeResponse(resp);
// return;
// }
// ProxyResponse proxyResponse = new ProxyResponse();
// proxyResponse.setStatus(ProxyResponse.Status.SUCCESS);
// proxyResponse.setCode(HttpStatus.SC_OK);
// proxyResponse.setData(
// jTokenResultAsJsonObject.get("username").getAsString().replaceAll("@carbon.super", ""));
// HandlerUtil.handleSuccess(resp, proxyResponse);
// httpSession.setAttribute(HandlerConstants.USERNAME_WITH_DOMAIN, jTokenResultAsJsonObject.get("username").getAsString());
// log.info("Customer login", userLogContextBuilder.setUserName(proxyResponse.getData()).setUserRegistered(true).build());
// }
} catch (IOException e) { } catch (IOException e) {
log.error("Error occurred while sending the response into the socket. ", e); log.error("Error occurred while sending the response into the socket. ", e);
} catch (JsonSyntaxException e) { } catch (JsonSyntaxException e) {

@ -21,6 +21,7 @@ package io.entgra.device.mgt.core.ui.request.interceptor.util;
import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonArray; import com.google.gson.JsonArray;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
@ -50,35 +51,25 @@ import org.apache.hc.core5.http.io.entity.BufferedHttpEntity;
import org.apache.hc.core5.http.io.entity.InputStreamEntity; import org.apache.hc.core5.http.io.entity.InputStreamEntity;
import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.ssl.SSLContextBuilder; import org.apache.hc.core5.ssl.SSLContextBuilder;
import org.apache.hc.client5.http.entity.mime.HttpMultipartMode;
import org.apache.http.Consts; import org.apache.http.Consts;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.cookie.SM; import org.apache.http.cookie.SM;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService; import io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService;
import org.xml.sax.SAXException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder; import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory; import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException; import java.io.PrintWriter;
import java.io.*;
import java.math.BigInteger; import java.math.BigInteger;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.KeyStoreException; import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.Enumeration; import java.util.*;
import java.util.List;
public class HandlerUtil { public class HandlerUtil {
@ -159,7 +150,7 @@ public class HandlerUtil {
} }
public static String getMemeType(HttpResponse response) { public static String getMemeType(HttpResponse response) {
Header contentType = response.getEntity().getContentType(); Header contentType = response.getFirstHeader("Content-Type");
if (contentType != null) { if (contentType != null) {
return contentType.getValue().split(";")[0].trim(); return contentType.getValue().split(";")[0].trim();
} }
@ -273,29 +264,9 @@ public class HandlerUtil {
resp.setStatus(proxyResponse.getCode()); resp.setStatus(proxyResponse.getCode());
resp.setContentType(ContentType.APPLICATION_JSON.getMimeType()); resp.setContentType(ContentType.APPLICATION_JSON.getMimeType());
resp.setCharacterEncoding(Consts.UTF_8.name()); resp.setCharacterEncoding(Consts.UTF_8.name());
JSONObject response = new JSONObject();
String responseData = proxyResponse.getData();
if (!StringUtils.isEmpty(responseData)) {
try {
if (responseData.startsWith("{")) {
JSONObject responseDataJsonObj = new JSONObject(responseData);
response.put("data", responseDataJsonObj);
} else if (responseData.startsWith("[")) {
JSONArray responseDataJsonArr = new JSONArray(responseData);
response.put("data", responseDataJsonArr);
} else {
log.warn("Response data is not valid json string >> " + responseData);
response.put("data", responseData);
}
} catch (JSONException e) {
log.error("Response data is not passable");
response.put("data", responseData);
}
}
try (PrintWriter writer = resp.getWriter()) { try (PrintWriter writer = resp.getWriter()) {
writer.write(response.toString()); writer.write(proxyResponse.getData().toString());
} }
} }
@ -435,13 +406,13 @@ public class HandlerUtil {
* @throws FileUploadException If unable to parse the incoming request for multipart content extraction. * @throws FileUploadException If unable to parse the incoming request for multipart content extraction.
* @throws IOException If error occurred while generating the request body. * @throws IOException If error occurred while generating the request body.
*/ */
public static void generateRequestEntity(HttpServletRequest req, HttpEntityEnclosingRequestBase proxyRequest) public static void generateRequestEntity(HttpServletRequest req, ClassicHttpRequest proxyRequest)
throws FileUploadException, IOException { throws FileUploadException, IOException {
if (ServletFileUpload.isMultipartContent(req)) { if (ServletFileUpload.isMultipartContent(req)) {
ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory()); ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
List<FileItem> fileItemList = servletFileUpload.parseRequest(req); List<FileItem> fileItemList = servletFileUpload.parseRequest(req);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); entityBuilder.setMode(HttpMultipartMode.LEGACY);
for (FileItem item : fileItemList) { for (FileItem item : fileItemList) {
if (!item.isFormField()) { if (!item.isFormField()) {
entityBuilder.addPart(item.getFieldName(), new InputStreamBody(item.getInputStream(), entityBuilder.addPart(item.getFieldName(), new InputStreamBody(item.getInputStream(),
@ -456,7 +427,7 @@ public class HandlerUtil {
if (StringUtils.isNotEmpty(req.getHeader(HttpHeaders.CONTENT_LENGTH)) || if (StringUtils.isNotEmpty(req.getHeader(HttpHeaders.CONTENT_LENGTH)) ||
StringUtils.isNotEmpty(req.getHeader(HttpHeaders.TRANSFER_ENCODING))) { StringUtils.isNotEmpty(req.getHeader(HttpHeaders.TRANSFER_ENCODING))) {
InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), InputStreamEntity entity = new InputStreamEntity(req.getInputStream(),
Long.parseLong(req.getHeader(HttpHeaders.CONTENT_LENGTH))); Long.parseLong(req.getHeader(HttpHeaders.CONTENT_LENGTH)), ContentType.parse(req.getContentType()));
proxyRequest.setEntity(new BufferedHttpEntity(entity)); proxyRequest.setEntity(new BufferedHttpEntity(entity));
} }
HandlerUtil.copyRequestHeaders(req, proxyRequest, true); HandlerUtil.copyRequestHeaders(req, proxyRequest, true);
@ -470,12 +441,12 @@ public class HandlerUtil {
* @param proxyRequest proxy request instance. * @param proxyRequest proxy request instance.
* @throws IOException If error occurred while generating the request body. * @throws IOException If error occurred while generating the request body.
*/ */
public static void generateChatRequestEntity(HttpServletRequest req, HttpEntityEnclosingRequestBase proxyRequest) public static void generateChatRequestEntity(HttpServletRequest req, ClassicHttpRequest proxyRequest)
throws IOException { throws IOException {
if (StringUtils.isNotEmpty(req.getHeader(HttpHeaders.CONTENT_LENGTH)) || if (StringUtils.isNotEmpty(req.getHeader(HttpHeaders.CONTENT_LENGTH)) ||
StringUtils.isNotEmpty(req.getHeader(HttpHeaders.TRANSFER_ENCODING))) { StringUtils.isNotEmpty(req.getHeader(HttpHeaders.TRANSFER_ENCODING))) {
InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), InputStreamEntity entity = new InputStreamEntity(req.getInputStream(),
Long.parseLong(req.getHeader(HttpHeaders.CONTENT_LENGTH))); Long.parseLong(req.getHeader(HttpHeaders.CONTENT_LENGTH)), ContentType.parse(req.getContentType()));
proxyRequest.setEntity(new BufferedHttpEntity(entity)); proxyRequest.setEntity(new BufferedHttpEntity(entity));
} }
} }
@ -490,23 +461,26 @@ public class HandlerUtil {
* @param supportedGrantTypes - supported grant types * @param supportedGrantTypes - supported grant types
* @return {@link StringEntity} of the payload to create the client application * @return {@link StringEntity} of the payload to create the client application
*/ */
public static StringEntity constructAppRegPayload(JsonArray tags, String appName, String username, String password, public static StringEntity constructAppRegPayload(ArrayNode tags, String appName, String username, String password,
String callbackUrl, JsonArray supportedGrantTypes) { String callbackUrl, ArrayList<String> supportedGrantTypes) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty(HandlerConstants.APP_NAME_KEY, appName); ObjectMapper objectMapper = new ObjectMapper();
jsonObject.addProperty(HandlerConstants.USERNAME, username); Map<String, Object> data = new HashMap<>();
jsonObject.addProperty(HandlerConstants.PASSWORD, password);
jsonObject.addProperty(HandlerConstants.IS_ALLOWED_TO_ALL_DOMAINS_KEY, "false"); data.put(HandlerConstants.APP_NAME_KEY, appName);
jsonObject.add(HandlerConstants.TAGS_KEY, tags); data.put(HandlerConstants.USERNAME, username);
data.put(HandlerConstants.PASSWORD, password);
data.put(HandlerConstants.IS_ALLOWED_TO_ALL_DOMAINS_KEY, "false");
data.put(HandlerConstants.TAGS_KEY, tags);
if (callbackUrl != null) { if (callbackUrl != null) {
jsonObject.addProperty(HandlerConstants.CALLBACK_URL_KEY, callbackUrl); data.put(HandlerConstants.CALLBACK_URL_KEY, callbackUrl);
} }
if (supportedGrantTypes != null) { if (supportedGrantTypes != null) {
jsonObject.add(HandlerConstants.GRANT_TYPE_KEY, supportedGrantTypes); data.put(HandlerConstants.GRANT_TYPE_KEY, supportedGrantTypes);
} }
String payload = jsonObject.toString();
return new StringEntity(payload, ContentType.APPLICATION_JSON); return new StringEntity(objectMapper.valueToTree(data).toString(), ContentType.APPLICATION_JSON);
} }
/*** /***
@ -516,9 +490,9 @@ public class HandlerUtil {
* @param gatewayUrl - gateway endpoint URL * @param gatewayUrl - gateway endpoint URL
* @param httpSession - current active HttpSession * @param httpSession - current active HttpSession
* @param resp - HttpServletResponse * @param resp - HttpServletResponse
* @return {@link JsonObject} of UI configurations * @return {@link JsonNode} of UI configurations
*/ */
public static JsonObject getUIConfigAndPersistInSession(String uiConfigUrl, String gatewayUrl, HttpSession httpSession, public static JsonNode getUIConfigAndPersistInSession(String uiConfigUrl, String gatewayUrl, HttpSession httpSession,
HttpServletResponse resp) throws IOException { HttpServletResponse resp) throws IOException {
HttpGet uiConfigEndpoint = new HttpGet(uiConfigUrl); HttpGet uiConfigEndpoint = new HttpGet(uiConfigUrl);
ProxyResponse uiConfigResponse = HandlerUtil.execute(uiConfigEndpoint); ProxyResponse uiConfigResponse = HandlerUtil.execute(uiConfigEndpoint);
@ -529,39 +503,28 @@ public class HandlerUtil {
HandlerUtil.handleError(resp, uiConfigResponse); HandlerUtil.handleError(resp, uiConfigResponse);
} }
if (uiConfigResponse.getData() == null) { JsonNode responseData = uiConfigResponse.getData();
if (responseData == null) {
log.error("UI config retrieval is failed, and didn't find UI configuration for App manager."); log.error("UI config retrieval is failed, and didn't find UI configuration for App manager.");
HandlerUtil.handleError(resp, null); HandlerUtil.handleError(resp, null);
} } else {
JsonParser jsonParser = new JsonParser(); httpSession.setAttribute(HandlerConstants.UI_CONFIG_KEY, responseData);
JsonElement uiConfigJsonElement = jsonParser.parse(uiConfigResponse.getData());
JsonObject uiConfigJsonObject = null;
if (uiConfigJsonElement.isJsonObject()) {
uiConfigJsonObject = uiConfigJsonElement.getAsJsonObject();
if (uiConfigJsonObject == null) {
log.error(
"Either UI config json element is not an json object or converting rom json element to json object is failed.");
HandlerUtil.handleError(resp, null);
}
httpSession.setAttribute(HandlerConstants.UI_CONFIG_KEY, uiConfigJsonObject);
httpSession.setAttribute(HandlerConstants.PLATFORM, gatewayUrl); httpSession.setAttribute(HandlerConstants.PLATFORM, gatewayUrl);
} }
return uiConfigJsonObject; return responseData;
} }
/*** /***
* Converts scopes from JsonArray to string with space separated values. * Converts scopes from JsonArray to string with space separated values.
* *
* @param scopes - scope Json Array and it is retrieved by reading UI config. * @param scopes - scope Array and it is retrieved by reading UI config.
* @return string value of the defined scopes * @return string value of the defined scopes
*/ */
public static String getScopeString(JsonArray scopes) { public static String getScopeString(JsonNode scopes) {
if (scopes != null && scopes.size() > 0) { if (scopes != null && scopes.isArray() && !scopes.isEmpty()) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
for (JsonElement scope : scopes) { for (JsonNode objNode : scopes) {
String tmpScope = scope.getAsString() + " "; builder.append(objNode).append(" ");
builder.append(tmpScope);
} }
return builder.toString(); return builder.toString();
} else { } else {
@ -569,35 +532,6 @@ public class HandlerUtil {
} }
} }
/***
* Converts xml file into string.
*
* @param xmlFile - xmlFile which needs to be converted into string.
* @return string value of the xml file.
*/
public static String xmlToString(File xmlFile) {
String stringOutput = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
OutputFormat format = new OutputFormat(doc);
StringWriter stringWriterOutput = new StringWriter();
XMLSerializer serial = new XMLSerializer(stringWriterOutput, format);
serial.serialize(doc);
stringOutput = stringWriterOutput.toString();
} catch (IOException e) {
log.error("Error occurred while sending the response into the socket. ", e);
} catch (ParserConfigurationException e) {
log.error("Error while creating the document builder.");
} catch (SAXException e) {
log.error("Error while parsing xml file.", e);
}
return stringOutput;
}
/*** /***
* Search a key from a given json string object. * Search a key from a given json string object.
* *
@ -640,11 +574,11 @@ public class HandlerUtil {
* Retry request again after refreshing the access token * Retry request again after refreshing the access token
* *
* @param req incoming {@link HttpServletRequest} * @param req incoming {@link HttpServletRequest}
* @param httpRequest subclass of {@link HttpRequestBase} related to the current request. * @param httpRequest {@link ClassicHttpRequest} related to the current request.
* @return {@link ProxyResponse} if successful and <code>null</code> if failed. * @return {@link ProxyResponse} if successful and <code>null</code> if failed.
* @throws IOException If an error occurs when try to retry the request. * @throws IOException If an error occurs when try to retry the request.
*/ */
public static ProxyResponse retryRequestWithRefreshedToken(HttpServletRequest req, HttpRequestBase httpRequest, public static ProxyResponse retryRequestWithRefreshedToken(HttpServletRequest req, ClassicHttpRequest httpRequest,
String apiEndpoint) throws IOException { String apiEndpoint) throws IOException {
ProxyResponse retryResponse = refreshToken(req, apiEndpoint); ProxyResponse retryResponse = refreshToken(req, apiEndpoint);
if (isResponseSuccessful(retryResponse)) { if (isResponseSuccessful(retryResponse)) {
@ -660,7 +594,6 @@ public class HandlerUtil {
return proxyResponse; return proxyResponse;
} }
return proxyResponse; return proxyResponse;
} }
return retryResponse; return retryResponse;
} }
@ -682,7 +615,6 @@ public class HandlerUtil {
if (session == null) { if (session == null) {
log.error("Couldn't find a session, hence it is required to login and proceed."); log.error("Couldn't find a session, hence it is required to login and proceed.");
tokenResultResponse = constructProxyResponseByErrorCode(HttpStatus.SC_UNAUTHORIZED); tokenResultResponse = constructProxyResponseByErrorCode(HttpStatus.SC_UNAUTHORIZED);
// handleError(resp, HttpStatus.SC_UNAUTHORIZED);
return tokenResultResponse; return tokenResultResponse;
} }
@ -690,23 +622,20 @@ public class HandlerUtil {
tokenResultResponse = getTokenResult(authData, keymanagerUrl); tokenResultResponse = getTokenResult(authData, keymanagerUrl);
if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
log.error("Error occurred while refreshing access token."); log.error("Error occurred while refreshing access token.");
// HandlerUtil.handleError(resp, tokenResultResponse);
return tokenResultResponse; return tokenResultResponse;
} }
JsonParser jsonParser = new JsonParser(); JsonNode tokenResponse = tokenResultResponse.getData();
JsonElement jTokenResult = jsonParser.parse(tokenResultResponse.getData()); if (tokenResponse != null) {
setNewAuthData(constructAuthDataFromTokenResult(tokenResponse, authData), session);
if (jTokenResult.isJsonObject()) {
setNewAuthData(constructAuthDataFromTokenResult(jTokenResult, authData), session);
return tokenResultResponse; return tokenResultResponse;
} }
log.error("Error Occurred in token renewal process."); log.error("Error Occurred in token renewal process.");
tokenResultResponse = constructProxyResponseByErrorCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); tokenResultResponse = constructProxyResponseByErrorCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
// handleError(resp, HttpStatus.SC_INTERNAL_SERVER_ERROR);
return tokenResultResponse; return tokenResultResponse;
} }
public static ProxyResponse getTokenResult(AuthData authData, String keymanagerUrl) throws IOException { public static ProxyResponse getTokenResult(AuthData authData, String keymanagerUrl) throws IOException {
HttpPost tokenEndpoint = new HttpPost(keymanagerUrl + HandlerConstants.OAUTH2_TOKEN_ENDPOINT); HttpPost tokenEndpoint = new HttpPost(keymanagerUrl + HandlerConstants.OAUTH2_TOKEN_ENDPOINT);
StringEntity tokenEndpointPayload = new StringEntity( StringEntity tokenEndpointPayload = new StringEntity(
@ -726,12 +655,17 @@ public class HandlerUtil {
session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, newAuthData); session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, newAuthData);
} }
public static AuthData constructAuthDataFromTokenResult(JsonElement tokenResult, AuthData authData) { /**
JsonObject jTokenResultAsJsonObject = tokenResult.getAsJsonObject(); * Construct {@link AuthData} from token response
* @param tokenResult {@link JsonNode}
* @param authData {@link AuthData} existing auth data values
* @return new {@link AuthData} object
*/
public static AuthData constructAuthDataFromTokenResult(JsonNode tokenResult, AuthData authData) {
AuthData newAuthData = new AuthData(); AuthData newAuthData = new AuthData();
newAuthData.setAccessToken(jTokenResultAsJsonObject.get("access_token").getAsString()); newAuthData.setAccessToken(tokenResult.get("access_token").textValue());
newAuthData.setRefreshToken(jTokenResultAsJsonObject.get("refresh_token").getAsString()); newAuthData.setRefreshToken(tokenResult.get("refresh_token").textValue());
newAuthData.setScope(jTokenResultAsJsonObject.get("scope").getAsString()); newAuthData.setScope(tokenResult.get("scope").textValue());
newAuthData.setClientId(authData.getClientId()); newAuthData.setClientId(authData.getClientId());
newAuthData.setClientSecret(authData.getClientSecret()); newAuthData.setClientSecret(authData.getClientSecret());
newAuthData.setEncodedClientApp(authData.getEncodedClientApp()); newAuthData.setEncodedClientApp(authData.getEncodedClientApp());
@ -748,7 +682,7 @@ public class HandlerUtil {
* This should be set to <code>false</code> when handling multipart requests as Http * This should be set to <code>false</code> when handling multipart requests as Http
* client will generate the Content-Type header automatically. * client will generate the Content-Type header automatically.
*/ */
public static void copyRequestHeaders(HttpServletRequest req, HttpRequestBase httpRequest, boolean preserveContentType) { public static void copyRequestHeaders(HttpServletRequest req, ClassicHttpRequest httpRequest, boolean preserveContentType) {
Enumeration<String> headerNames = req.getHeaderNames(); Enumeration<String> headerNames = req.getHeaderNames();
while (headerNames.hasMoreElements()) { while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement(); String headerName = headerNames.nextElement();
@ -774,18 +708,6 @@ public class HandlerUtil {
return headerValue; return headerValue;
} }
public static String getResponseString(HttpResponse response) throws IOException {
try (BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
StringBuilder responseBuilder = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
responseBuilder.append(line);
}
return responseBuilder.toString();
}
}
public static boolean isPropertyDefined(String property) { public static boolean isPropertyDefined(String property) {
return StringUtils.isEmpty(System.getProperty(property)); return StringUtils.isEmpty(System.getProperty(property));
} }

Loading…
Cancel
Save