mirror of
https://repository.entgra.net/community/device-mgt-core.git
synced 2025-10-06 02:01:45 +00:00
Fix compilation issues in user handler
This commit is contained in:
parent
db3555f59e
commit
66eac3c744
@ -18,21 +18,20 @@
|
||||
|
||||
package io.entgra.device.mgt.core.ui.request.interceptor;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
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.util.HandlerConstants;
|
||||
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
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.client.methods.HttpGet;
|
||||
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 javax.servlet.annotation.MultipartConfig;
|
||||
@ -42,11 +41,13 @@ import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
|
||||
@MultipartConfig
|
||||
@WebServlet("/default-oauth2-credentials")
|
||||
public class DefaultOauth2TokenHandler extends HttpServlet {
|
||||
private static final Log log = LogFactory.getLog(DefaultTokenHandler.class);
|
||||
private static final long serialVersionUID = 2254408216447549205L;
|
||||
|
||||
|
||||
@Override
|
||||
@ -80,17 +81,16 @@ public class DefaultOauth2TokenHandler extends HttpServlet {
|
||||
}
|
||||
}
|
||||
|
||||
String iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR
|
||||
+ System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR)
|
||||
+ HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme());
|
||||
String tokenUrl = iotsCoreUrl + "/api/device-mgt/v1.0/devices/" + clientId
|
||||
+ "/" + clientSecret + "/default-token" + scopeString;
|
||||
ClassicHttpRequest defaultTokenRequest =
|
||||
ClassicRequestBuilder.get(req.getScheme() + HandlerConstants.SCHEME_SEPARATOR
|
||||
+ System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR)
|
||||
+ HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme())
|
||||
+ "/api/device-mgt/v1.0/devices/" + clientId + HandlerConstants.URI_SEPARATOR
|
||||
+ clientSecret + "/default-token" + scopeString)
|
||||
.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.BEARER + authData.getAccessToken())
|
||||
.build();
|
||||
|
||||
HttpGet defaultTokenRequest = new HttpGet(tokenUrl);
|
||||
defaultTokenRequest
|
||||
.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken());
|
||||
defaultTokenRequest
|
||||
.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString());
|
||||
ProxyResponse tokenResultResponse = HandlerUtil.execute(defaultTokenRequest);
|
||||
|
||||
if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
|
||||
@ -98,29 +98,24 @@ public class DefaultOauth2TokenHandler extends HttpServlet {
|
||||
HandlerUtil.handleError(resp, tokenResultResponse);
|
||||
return;
|
||||
}
|
||||
String tokenResult = tokenResultResponse.getData();
|
||||
JsonNode tokenResult = tokenResultResponse.getData();
|
||||
if (tokenResult == null) {
|
||||
log.error("Invalid default token response is received.");
|
||||
HandlerUtil.handleError(resp, tokenResultResponse);
|
||||
return;
|
||||
}
|
||||
|
||||
JsonParser jsonParser = new JsonParser();
|
||||
JsonElement jTokenResult = jsonParser.parse(tokenResult);
|
||||
if (jTokenResult.isJsonObject()) {
|
||||
JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
|
||||
AuthData newDefaultAuthData = new AuthData();
|
||||
newDefaultAuthData.setClientId(clientId);
|
||||
newDefaultAuthData.setClientSecret(clientSecret);
|
||||
AuthData newDefaultAuthData = new AuthData();
|
||||
newDefaultAuthData.setClientId(clientId);
|
||||
newDefaultAuthData.setClientSecret(clientSecret);
|
||||
|
||||
String defaultToken = jTokenResultAsJsonObject.get("accessToken").getAsString();
|
||||
newDefaultAuthData.setAccessToken(defaultToken);
|
||||
newDefaultAuthData.setRefreshToken(jTokenResultAsJsonObject.get("refreshToken").getAsString());
|
||||
newDefaultAuthData.setScope(jTokenResultAsJsonObject.get("scopes").getAsString());
|
||||
httpSession.setAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY, newDefaultAuthData);
|
||||
String defaultToken = tokenResult.get("accessToken").asText();
|
||||
newDefaultAuthData.setAccessToken(defaultToken);
|
||||
newDefaultAuthData.setRefreshToken(tokenResult.get("refreshToken").asText());
|
||||
newDefaultAuthData.setScope(tokenResult.get("scopes").asText());
|
||||
httpSession.setAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY, newDefaultAuthData);
|
||||
|
||||
HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultToken));
|
||||
}
|
||||
HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultToken));
|
||||
} else {
|
||||
HandlerUtil.sendUnAuthorizeResponse(resp);
|
||||
}
|
||||
@ -152,19 +147,19 @@ public class DefaultOauth2TokenHandler extends HttpServlet {
|
||||
ub3.setHost(System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR));
|
||||
ub3.setPort(Integer.parseInt(System.getProperty(HandlerConstants.IOT_GATEWAY_WEBSOCKET_WS_PORT_ENV_VAR)));
|
||||
|
||||
JsonObject responseJsonObj = new JsonObject();
|
||||
responseJsonObj.addProperty("default-access-token", defaultAccessToken);
|
||||
responseJsonObj.addProperty("remote-session-base-url", ub.toString());
|
||||
responseJsonObj.addProperty("secured-websocket-gateway-url", ub2.toString());
|
||||
responseJsonObj.addProperty("unsecured-websocket-gateway-url", ub3.toString());
|
||||
|
||||
Gson gson = new Gson();
|
||||
String payload = gson.toJson(responseJsonObj);
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
JsonNode node = JsonNodeFactory.instance.objectNode();
|
||||
Map<String, Object> nodeMap = mapper.convertValue(node, new TypeReference<>() {
|
||||
});
|
||||
nodeMap.put("default-access-token", defaultAccessToken);
|
||||
nodeMap.put("remote-session-base-url", ub.toString());
|
||||
nodeMap.put("secured-websocket-gateway-url", ub2.toString());
|
||||
nodeMap.put("unsecured-websocket-gateway-url", ub3.toString());
|
||||
|
||||
ProxyResponse proxyResponse = new ProxyResponse();
|
||||
proxyResponse.setCode(HttpStatus.SC_OK);
|
||||
proxyResponse.setStatus(ProxyResponse.Status.SUCCESS);
|
||||
proxyResponse.setData(payload);
|
||||
proxyResponse.setData(mapper.convertValue(nodeMap, JsonNode.class));
|
||||
return proxyResponse;
|
||||
}
|
||||
}
|
||||
|
||||
@ -18,8 +18,10 @@
|
||||
|
||||
package io.entgra.device.mgt.core.ui.request.interceptor;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonObject;
|
||||
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.ProxyResponse;
|
||||
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants;
|
||||
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.HttpSession;
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
|
||||
@MultipartConfig
|
||||
@WebServlet("/default-credentials")
|
||||
public class DefaultTokenHandler extends HttpServlet {
|
||||
private static final Log log = LogFactory.getLog(DefaultTokenHandler.class);
|
||||
private static final long serialVersionUID = 6356346497117534430L;
|
||||
|
||||
|
||||
@Override
|
||||
@ -110,19 +114,19 @@ public class DefaultTokenHandler extends HttpServlet {
|
||||
ub3.setHost(System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR));
|
||||
ub3.setPort(Integer.parseInt(System.getProperty(HandlerConstants.IOT_GATEWAY_WEBSOCKET_WS_PORT_ENV_VAR)));
|
||||
|
||||
JsonObject responseJsonObj = new JsonObject();
|
||||
responseJsonObj.addProperty("default-access-token", defaultAccessToken);
|
||||
responseJsonObj.addProperty("remote-session-base-url", ub.toString());
|
||||
responseJsonObj.addProperty("secured-websocket-gateway-url", ub2.toString());
|
||||
responseJsonObj.addProperty("unsecured-websocket-gateway-url", ub3.toString());
|
||||
|
||||
Gson gson = new Gson();
|
||||
String payload = gson.toJson(responseJsonObj);
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
JsonNode node = JsonNodeFactory.instance.objectNode();
|
||||
Map<String, Object> nodeMap = mapper.convertValue(node, new TypeReference<>() {
|
||||
});
|
||||
nodeMap.put("default-access-token", defaultAccessToken);
|
||||
nodeMap.put("remote-session-base-url", ub.toString());
|
||||
nodeMap.put("secured-websocket-gateway-url", ub2.toString());
|
||||
nodeMap.put("unsecured-websocket-gateway-url", ub3.toString());
|
||||
|
||||
ProxyResponse proxyResponse = new ProxyResponse();
|
||||
proxyResponse.setCode(HttpStatus.SC_OK);
|
||||
proxyResponse.setStatus(ProxyResponse.Status.SUCCESS);
|
||||
proxyResponse.setData(payload);
|
||||
proxyResponse.setData(mapper.convertValue(nodeMap, JsonNode.class));
|
||||
return proxyResponse;
|
||||
}
|
||||
}
|
||||
|
||||
@ -18,17 +18,15 @@
|
||||
|
||||
package io.entgra.device.mgt.core.ui.request.interceptor;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants;
|
||||
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil;
|
||||
import org.apache.commons.logging.Log;
|
||||
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.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.WebServlet;
|
||||
@ -48,89 +46,94 @@ import java.io.IOException;
|
||||
)
|
||||
public class HubspotHandler extends HttpServlet {
|
||||
|
||||
private static final Log log = LogFactory.getLog(HubspotHandler.class);
|
||||
private HttpSession httpSession;
|
||||
private static String hubspotEndpoint;
|
||||
private static String chatConfig;
|
||||
private JsonObject uiConfigJsonObject;
|
||||
private static String gatewayUrl;
|
||||
private static String iotsCoreUrl;
|
||||
private static final Log log = LogFactory.getLog(HubspotHandler.class);
|
||||
private HttpSession httpSession;
|
||||
private static String hubspotEndpoint;
|
||||
private static String chatConfig;
|
||||
private JsonNode uiConfigJsonObject;
|
||||
private static String gatewayUrl;
|
||||
private static String iotsCoreUrl;
|
||||
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
|
||||
try {
|
||||
if (validateRequest(req, resp)) {
|
||||
HttpPost postRequest = new HttpPost(HandlerUtil.generateBackendRequestURL(req, hubspotEndpoint));
|
||||
HandlerUtil.generateChatRequestEntity(req, postRequest);
|
||||
postRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
|
||||
postRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig);
|
||||
ProxyResponse proxyResponse = HandlerUtil.execute(postRequest);
|
||||
HandlerUtil.handleSuccess(resp, proxyResponse);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Error occurred when processing POST request.", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
|
||||
try {
|
||||
if (validateRequest(req, resp)) {
|
||||
HttpGet getRequest = new HttpGet(HandlerUtil.generateBackendRequestURL(req,hubspotEndpoint));
|
||||
getRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
|
||||
getRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig);
|
||||
ProxyResponse proxyResponse = HandlerUtil.execute(getRequest);
|
||||
HandlerUtil.handleSuccess(resp, proxyResponse);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Error occurred when processing GET request.", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doDelete(HttpServletRequest req, HttpServletResponse resp){
|
||||
try{
|
||||
if(validateRequest(req, resp)){
|
||||
HttpDelete deleteRequest = new HttpDelete(HandlerUtil.generateBackendRequestURL(req,hubspotEndpoint));
|
||||
deleteRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
|
||||
deleteRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + chatConfig);
|
||||
ProxyResponse proxyResponse = HandlerUtil.execute(deleteRequest);
|
||||
HandlerUtil.handleSuccess(resp, proxyResponse);
|
||||
}
|
||||
} catch (IOException e){
|
||||
log.error("Error occurred when processing DELETE request.", e);
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
|
||||
try {
|
||||
if (validateRequest(req, resp)) {
|
||||
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.handleSuccess(resp, HandlerUtil.execute(postRequest));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Error occurred when processing POST request.", e);
|
||||
}
|
||||
}
|
||||
|
||||
/***
|
||||
* Validates the hubspot's incoming request.
|
||||
*
|
||||
* @param req {@link HttpServletRequest}
|
||||
* @param resp {@link HttpServletResponse}
|
||||
* @return If request is a valid one, returns TRUE, otherwise return FALSE
|
||||
* @throws IOException If and error occurs while witting error response to client side
|
||||
*/
|
||||
private boolean validateRequest(HttpServletRequest req, HttpServletResponse resp)
|
||||
throws IOException {
|
||||
httpSession = req.getSession(false);
|
||||
if (httpSession == null) {
|
||||
log.error("Unauthorized, You are not logged in. Please log in to the portal");
|
||||
HandlerUtil.handleError(resp, HttpStatus.SC_UNAUTHORIZED);
|
||||
return false;
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
|
||||
try {
|
||||
if (validateRequest(req, resp)) {
|
||||
ClassicHttpRequest getRequest =
|
||||
ClassicRequestBuilder.get(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.handleSuccess(resp, HandlerUtil.execute(getRequest));
|
||||
}
|
||||
if (req.getMethod() == null) {
|
||||
log.error("Bad Request, Request method is empty");
|
||||
HandlerUtil.handleError(resp, HttpStatus.SC_BAD_REQUEST);
|
||||
return false;
|
||||
}
|
||||
gatewayUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR)
|
||||
+ HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme());
|
||||
iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR)
|
||||
+ HandlerConstants.COLON + HandlerUtil.getCorePort(req.getScheme());
|
||||
String uiConfigUrl = iotsCoreUrl + HandlerConstants.UI_CONFIG_ENDPOINT;
|
||||
uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, resp);
|
||||
chatConfig = uiConfigJsonObject.get("hubspotChat").getAsJsonObject().get("accessToken").getAsString();
|
||||
hubspotEndpoint = HandlerConstants.HTTPS_PROTOCOL + HandlerConstants.SCHEME_SEPARATOR + HandlerConstants.HUBSPOT_CHAT_URL;
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
log.error("Error occurred when processing GET request.", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) {
|
||||
try {
|
||||
if (validateRequest(req, resp)) {
|
||||
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.AUTHORIZATION, HandlerConstants.BEARER + chatConfig);
|
||||
HandlerUtil.handleSuccess(resp, HandlerUtil.execute(deleteRequest));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Error occurred when processing DELETE request.", e);
|
||||
}
|
||||
}
|
||||
|
||||
/***
|
||||
* Validates the hubspot's incoming request.
|
||||
*
|
||||
* @param req {@link HttpServletRequest}
|
||||
* @param resp {@link HttpServletResponse}
|
||||
* @return If request is a valid one, returns TRUE, otherwise return FALSE
|
||||
* @throws IOException If and error occurs while witting error response to client side
|
||||
*/
|
||||
private boolean validateRequest(HttpServletRequest req, HttpServletResponse resp)
|
||||
throws IOException {
|
||||
httpSession = req.getSession(false);
|
||||
if (httpSession == null) {
|
||||
log.error("Unauthorized, You are not logged in. Please log in to the portal");
|
||||
HandlerUtil.handleError(resp, HttpStatus.SC_UNAUTHORIZED);
|
||||
return false;
|
||||
}
|
||||
if (req.getMethod() == null) {
|
||||
log.error("Bad Request, Request method is empty");
|
||||
HandlerUtil.handleError(resp, HttpStatus.SC_BAD_REQUEST);
|
||||
return false;
|
||||
}
|
||||
gatewayUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR)
|
||||
+ HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme());
|
||||
iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR)
|
||||
+ HandlerConstants.COLON + HandlerUtil.getCorePort(req.getScheme());
|
||||
String uiConfigUrl = iotsCoreUrl + HandlerConstants.UI_CONFIG_ENDPOINT;
|
||||
uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, httpSession, resp);
|
||||
chatConfig = uiConfigJsonObject.get("hubspotChat").get("accessToken").textValue();
|
||||
hubspotEndpoint = HandlerConstants.HTTPS_PROTOCOL + HandlerConstants.SCHEME_SEPARATOR + HandlerConstants.HUBSPOT_CHAT_URL;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@ -18,6 +18,7 @@
|
||||
|
||||
package io.entgra.device.mgt.core.ui.request.interceptor;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
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.ProxyResponse;
|
||||
@ -68,7 +69,8 @@ public class LoginHandler extends HttpServlet {
|
||||
}
|
||||
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 scopes = uiConfigJsonObject.get("scopes").getAsJsonArray();
|
||||
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.
|
||||
* @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);
|
||||
tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + encodedClientApp);
|
||||
tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString());
|
||||
|
||||
@ -18,15 +18,17 @@
|
||||
|
||||
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.ProxyResponse;
|
||||
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants;
|
||||
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.MultipartConfig;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
@ -34,12 +36,15 @@ import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
|
||||
@MultipartConfig
|
||||
@WebServlet("/login-user/scopes")
|
||||
public class PermissionScopeHandler extends HttpServlet {
|
||||
private static final long serialVersionUID = 976006906915355611L;
|
||||
|
||||
@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);
|
||||
if (httpSession == null) {
|
||||
HandlerUtil.sendUnAuthorizeResponse(resp);
|
||||
@ -54,11 +59,15 @@ public class PermissionScopeHandler extends HttpServlet {
|
||||
|
||||
if (!StringUtils.isEmpty(authData.getScope())) {
|
||||
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.setStatus(ProxyResponse.Status.SUCCESS);
|
||||
proxyResponse.setData(jsonObject.toString());
|
||||
proxyResponse.setData(mapper.convertValue(nodeMap, JsonNode.class));
|
||||
HandlerUtil.handleSuccess(resp, proxyResponse);
|
||||
return;
|
||||
}
|
||||
|
||||
@ -18,20 +18,18 @@
|
||||
|
||||
package io.entgra.device.mgt.core.ui.request.interceptor;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
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.util.HandlerConstants;
|
||||
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.HttpHeaders;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.entity.ContentType;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.hc.core5.http.ClassicHttpRequest;
|
||||
import org.apache.hc.core5.http.ContentType;
|
||||
import org.apache.hc.core5.http.HttpStatus;
|
||||
import org.apache.hc.core5.http.io.entity.StringEntity;
|
||||
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
|
||||
|
||||
import javax.servlet.annotation.MultipartConfig;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
@ -75,33 +73,35 @@ public class SsoLoginCallbackHandler extends HttpServlet {
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
StringEntity tokenEPPayload = new StringEntity(
|
||||
"grant_type=" + HandlerConstants.CODE_GRANT_TYPE + "&code=" + code + "&scope=" + scope +
|
||||
"&redirect_uri=" + loginCallbackUrl,
|
||||
ContentType.APPLICATION_FORM_URLENCODED);
|
||||
tokenEndpoint.setEntity(tokenEPPayload);
|
||||
ProxyResponse tokenResultResponse = HandlerUtil.execute(tokenEndpoint);
|
||||
|
||||
JsonParser jsonParser = new JsonParser();
|
||||
JsonElement jTokenResult = jsonParser.parse(tokenResultResponse.getData());
|
||||
if (jTokenResult.isJsonObject()) {
|
||||
JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
|
||||
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);
|
||||
JsonNode jsonNode = tokenResultResponse.getData();
|
||||
|
||||
if (jsonNode != null) {
|
||||
AuthData authData = new AuthData();
|
||||
authData.setClientId(session.getAttribute("clientId").toString());
|
||||
authData.setClientSecret(session.getAttribute("clientSecret").toString());
|
||||
authData.setEncodedClientApp(session.getAttribute("encodedClientApp").toString());
|
||||
authData.setAccessToken(jTokenResultAsJsonObject.get("access_token").getAsString());
|
||||
authData.setRefreshToken(jTokenResultAsJsonObject.get("refresh_token").getAsString());
|
||||
authData.setScope(jTokenResultAsJsonObject.get("scope").getAsString());
|
||||
authData.setAccessToken(jsonNode.get("access_token").textValue());
|
||||
authData.setRefreshToken(jsonNode.get("refresh_token").textValue());
|
||||
authData.setScope(jsonNode.get("scope").textValue());
|
||||
session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, authData);
|
||||
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;
|
||||
|
||||
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.cache.LoginCache;
|
||||
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.util.HandlerConstants;
|
||||
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.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.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.NodeList;
|
||||
import org.xml.sax.InputSource;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import javax.servlet.annotation.MultipartConfig;
|
||||
@ -54,30 +46,25 @@ import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.StringReader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@MultipartConfig
|
||||
@WebServlet("/ssoLogin")
|
||||
public class SsoLoginHandler extends HttpServlet {
|
||||
private static final Log log = LogFactory.getLog(SsoLoginHandler.class);
|
||||
private static final long serialVersionUID = 5594017767311123453L;
|
||||
|
||||
private static String adminUsername;
|
||||
private static String adminPassword;
|
||||
private static String gatewayUrl;
|
||||
private static String iotsCoreUrl;
|
||||
private static String apiMgtUrl;
|
||||
private static String keyManagerUrl;
|
||||
private static String iotSCoreUrl;
|
||||
private static int sessionTimeOut;
|
||||
private static String encodedAdminCredentials;
|
||||
private static String encodedClientApp;
|
||||
private static String applicationId;
|
||||
private static String applicationName;
|
||||
private static String baseContextPath;
|
||||
|
||||
private JsonObject uiConfigJsonObject;
|
||||
private JsonNode uiConfigJsonObject;
|
||||
private HttpSession httpSession;
|
||||
private LoginCache loginCache;
|
||||
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)
|
||||
+ 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());
|
||||
apiMgtUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_APIM_HOST_ENV_VAR)
|
||||
+ HandlerConstants.COLON + HandlerUtil.getAPIManagerPort(req.getScheme());
|
||||
keyManagerUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_KM_HOST_ENV_VAR)
|
||||
String keyManagerUrl =
|
||||
req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_KM_HOST_ENV_VAR)
|
||||
+ HandlerConstants.COLON + HandlerUtil.getKeyManagerPort(req.getScheme());
|
||||
|
||||
// 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);
|
||||
|
||||
// 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();
|
||||
JsonArray scopesSsoJson = uiConfigJsonObject.get("scopes").getAsJsonArray();
|
||||
String scopesSsoString = HandlerUtil.getScopeString(scopesSsoJson);
|
||||
String loginCallbackUrl = iotsCoreUrl + baseContextPath + HandlerConstants.SSO_LOGIN_CALLBACK;
|
||||
|
||||
JsonNode scopeJsonNode = uiConfigJsonObject.get("scopes");
|
||||
String scopesSsoString = HandlerUtil.getScopeString(scopeJsonNode);
|
||||
String loginCallbackUrl = iotSCoreUrl + baseContextPath + HandlerConstants.SSO_LOGIN_CALLBACK;
|
||||
persistAuthSessionData(req, oAuthApp.getClientId(), oAuthApp.getClientSecret(),
|
||||
oAuthApp.getEncodedClientApp(), scopesSsoString, state);
|
||||
resp.sendRedirect(keyManagerUrl + HandlerConstants.AUTHORIZATION_ENDPOINT +
|
||||
@ -134,8 +121,6 @@ public class SsoLoginHandler extends HttpServlet {
|
||||
"&redirect_uri=" + loginCallbackUrl);
|
||||
} catch (IOException 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) {
|
||||
log.error("Error while creating the document builder.");
|
||||
} catch (SAXException e) {
|
||||
@ -154,34 +139,32 @@ public class SsoLoginHandler extends HttpServlet {
|
||||
*/
|
||||
private void dynamicClientRegistration(HttpServletRequest req, HttpServletResponse resp) throws LoginException {
|
||||
try {
|
||||
JsonArray tags = uiConfigJsonObject.get("appRegistration").getAsJsonObject().get("tags").getAsJsonArray();
|
||||
JsonArray scopes = uiConfigJsonObject.get("scopes").getAsJsonArray();
|
||||
ArrayNode tags = (ArrayNode) uiConfigJsonObject.get("appRegistration").get("tags");
|
||||
JsonNode scopes = uiConfigJsonObject.get("scopes");
|
||||
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
|
||||
HttpPost apiRegEndpoint = new HttpPost(gatewayUrl + HandlerConstants.APP_REG_ENDPOINT);
|
||||
encodedAdminCredentials = Base64.getEncoder()
|
||||
String encodedAdminCredentials = Base64.getEncoder()
|
||||
.encodeToString((adminUsername + HandlerConstants.COLON + adminPassword).getBytes());
|
||||
apiRegEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC +
|
||||
encodedAdminCredentials);
|
||||
apiRegEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
|
||||
apiRegEndpoint.setEntity(HandlerUtil.constructAppRegPayload(tags, applicationName, adminUsername, adminPassword,
|
||||
callbackUrl, supportedGrantTypes));
|
||||
ClassicHttpRequest apiRegEndpoint = ClassicRequestBuilder.post(gatewayUrl + HandlerConstants.APP_REG_ENDPOINT)
|
||||
.setEntity(HandlerUtil.constructAppRegPayload(tags, applicationName, adminUsername, adminPassword,
|
||||
callbackUrl, constructAppGrantTypeUpdateArray()))
|
||||
.setHeader(org.apache.hc.core5.http.HttpHeaders.CONTENT_TYPE,
|
||||
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);
|
||||
|
||||
if (clientAppResponse.getCode() == HttpStatus.SC_CREATED) {
|
||||
JsonParser jsonParser = new JsonParser();
|
||||
JsonElement jClientAppResult = jsonParser.parse(clientAppResponse.getData());
|
||||
String clientId = null;
|
||||
String clientSecret = null;
|
||||
JsonNode jsonNode = clientAppResponse.getData();
|
||||
|
||||
if (jClientAppResult.isJsonObject()) {
|
||||
JsonObject jClientAppResultAsJsonObject = jClientAppResult.getAsJsonObject();
|
||||
clientId = jClientAppResultAsJsonObject.get("client_id").getAsString();
|
||||
clientSecret = jClientAppResultAsJsonObject.get("client_secret").getAsString();
|
||||
if (jsonNode != null) {
|
||||
clientId = jsonNode.get("client_id").textValue();
|
||||
clientSecret = jsonNode.get("client_secret").textValue();
|
||||
encodedClientApp = Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes());
|
||||
String scopesString = HandlerUtil.getScopeString(scopes);
|
||||
persistAuthSessionData(req, clientId, clientSecret, encodedClientApp, scopesString, state);
|
||||
@ -206,8 +189,6 @@ public class SsoLoginHandler extends HttpServlet {
|
||||
}
|
||||
} catch (IOException 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();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Persist the Auth data inside the session
|
||||
*
|
||||
@ -253,64 +233,14 @@ public class SsoLoginHandler extends HttpServlet {
|
||||
/***
|
||||
* 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() {
|
||||
JsonArray jsonArray = new JsonArray();
|
||||
|
||||
private ArrayList<String> constructAppGrantTypeUpdateArray() {
|
||||
ArrayList<String> jsonArray = new ArrayList<>();
|
||||
jsonArray.add(HandlerConstants.CODE_GRANT_TYPE);
|
||||
jsonArray.add(HandlerConstants.REFRESH_TOKEN_GRANT_TYPE);
|
||||
jsonArray.add(HandlerConstants.PASSWORD_GRANT_TYPE);
|
||||
jsonArray.add(HandlerConstants.JWT_BEARER_GRANT_TYPE);
|
||||
|
||||
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;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonFactory;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
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 io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager;
|
||||
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.HandlerUtil;
|
||||
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
|
||||
import org.apache.hc.core5.http.*;
|
||||
import org.apache.hc.core5.http.io.entity.HttpEntities;
|
||||
import org.apache.hc.core5.http.ClassicHttpRequest;
|
||||
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.message.BasicNameValuePair;
|
||||
|
||||
@ -63,7 +62,7 @@ public class UserHandler extends HttpServlet {
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
|
||||
try {
|
||||
String keymanagerUrl =
|
||||
String keyManagerUrl =
|
||||
req.getScheme() + HandlerConstants.SCHEME_SEPARATOR +
|
||||
System.getProperty(HandlerConstants.IOT_KM_HOST_ENV_VAR)
|
||||
+ HandlerConstants.COLON + HandlerUtil.getKeyManagerPort(req.getScheme());
|
||||
@ -80,39 +79,24 @@ public class UserHandler extends HttpServlet {
|
||||
}
|
||||
|
||||
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();
|
||||
String adminUsername = dmc.getKeyManagerConfigurations().getAdminUsername();
|
||||
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> nameValuePairs = new ArrayList<>();
|
||||
nameValuePairs.add(new BasicNameValuePair("token", accessToken));
|
||||
|
||||
List<NameValuePair> nvps = new ArrayList<>();
|
||||
nvps.add(new BasicNameValuePair("token", accessToken));
|
||||
// nvps.add(new BasicNameValuePair("password", "secret"));
|
||||
|
||||
ClassicHttpRequest httpPost = ClassicRequestBuilder.post(keymanagerUrl + HandlerConstants.INTROSPECT_ENDPOINT)
|
||||
.setEntity(new UrlEncodedFormEntity(nvps))
|
||||
ClassicHttpRequest introspectCall = ClassicRequestBuilder.post(keyManagerUrl + HandlerConstants.INTROSPECT_ENDPOINT)
|
||||
.setEntity(new UrlEncodedFormEntity(nameValuePairs))
|
||||
.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString())
|
||||
.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder().encodeToString((adminUsername + HandlerConstants.COLON + adminPassword).getBytes()))
|
||||
.build();
|
||||
|
||||
|
||||
ProxyResponse tokenStatus = HandlerUtil.execute(httpPost);
|
||||
|
||||
ProxyResponse tokenStatus = HandlerUtil.execute(introspectCall);
|
||||
if (tokenStatus.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
|
||||
if (tokenStatus.getCode() == HttpStatus.SC_UNAUTHORIZED) {
|
||||
tokenStatus = HandlerUtil.retryRequestWithRefreshedToken(req, tokenEndpoint, keymanagerUrl);
|
||||
if(!HandlerUtil.isResponseSuccessful(tokenStatus)) {
|
||||
tokenStatus = HandlerUtil.retryRequestWithRefreshedToken(req, introspectCall, keyManagerUrl);
|
||||
if (!HandlerUtil.isResponseSuccessful(tokenStatus)) {
|
||||
HandlerUtil.handleError(resp, tokenStatus);
|
||||
return;
|
||||
}
|
||||
@ -136,38 +120,17 @@ public class UserHandler extends HttpServlet {
|
||||
ProxyResponse proxyResponse = new ProxyResponse();
|
||||
proxyResponse.setStatus(ProxyResponse.Status.SUCCESS);
|
||||
proxyResponse.setCode(HttpStatus.SC_OK);
|
||||
// proxyResponse.setData(
|
||||
// tokenData.get("username").textValue().replaceAll("@carbon.super", ""));
|
||||
|
||||
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", ""));
|
||||
proxyResponse.setData(mapper.convertValue(nodeMap, JsonNode.class));
|
||||
// tokenData = ;
|
||||
|
||||
|
||||
|
||||
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());
|
||||
|
||||
// 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());
|
||||
// }
|
||||
httpSession.setAttribute(HandlerConstants.USERNAME_WITH_DOMAIN, nodeMap.get("username").toString());
|
||||
log.info("Customer login",
|
||||
userLogContextBuilder.setUserName(nodeMap.get("username").toString()).setUserRegistered(true).build());
|
||||
} catch (IOException e) {
|
||||
log.error("Error occurred while sending the response into the socket. ", 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.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonArray;
|
||||
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.StringEntity;
|
||||
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.client.methods.HttpEntityEnclosingRequestBase;
|
||||
import org.apache.http.client.methods.HttpRequestBase;
|
||||
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 org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
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.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import java.io.*;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.PrintWriter;
|
||||
import java.math.BigInteger;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
import java.util.*;
|
||||
|
||||
public class HandlerUtil {
|
||||
|
||||
@ -159,7 +150,7 @@ public class HandlerUtil {
|
||||
}
|
||||
|
||||
public static String getMemeType(HttpResponse response) {
|
||||
Header contentType = response.getEntity().getContentType();
|
||||
Header contentType = response.getFirstHeader("Content-Type");
|
||||
if (contentType != null) {
|
||||
return contentType.getValue().split(";")[0].trim();
|
||||
}
|
||||
@ -273,29 +264,9 @@ public class HandlerUtil {
|
||||
resp.setStatus(proxyResponse.getCode());
|
||||
resp.setContentType(ContentType.APPLICATION_JSON.getMimeType());
|
||||
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()) {
|
||||
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 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 {
|
||||
if (ServletFileUpload.isMultipartContent(req)) {
|
||||
ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
|
||||
List<FileItem> fileItemList = servletFileUpload.parseRequest(req);
|
||||
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
|
||||
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
|
||||
entityBuilder.setMode(HttpMultipartMode.LEGACY);
|
||||
for (FileItem item : fileItemList) {
|
||||
if (!item.isFormField()) {
|
||||
entityBuilder.addPart(item.getFieldName(), new InputStreamBody(item.getInputStream(),
|
||||
@ -456,7 +427,7 @@ public class HandlerUtil {
|
||||
if (StringUtils.isNotEmpty(req.getHeader(HttpHeaders.CONTENT_LENGTH)) ||
|
||||
StringUtils.isNotEmpty(req.getHeader(HttpHeaders.TRANSFER_ENCODING))) {
|
||||
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));
|
||||
}
|
||||
HandlerUtil.copyRequestHeaders(req, proxyRequest, true);
|
||||
@ -470,12 +441,12 @@ public class HandlerUtil {
|
||||
* @param proxyRequest proxy request instance.
|
||||
* @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 {
|
||||
if (StringUtils.isNotEmpty(req.getHeader(HttpHeaders.CONTENT_LENGTH)) ||
|
||||
StringUtils.isNotEmpty(req.getHeader(HttpHeaders.TRANSFER_ENCODING))) {
|
||||
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));
|
||||
}
|
||||
}
|
||||
@ -490,23 +461,26 @@ public class HandlerUtil {
|
||||
* @param supportedGrantTypes - supported grant types
|
||||
* @return {@link StringEntity} of the payload to create the client application
|
||||
*/
|
||||
public static StringEntity constructAppRegPayload(JsonArray tags, String appName, String username, String password,
|
||||
String callbackUrl, JsonArray supportedGrantTypes) {
|
||||
JsonObject jsonObject = new JsonObject();
|
||||
jsonObject.addProperty(HandlerConstants.APP_NAME_KEY, appName);
|
||||
jsonObject.addProperty(HandlerConstants.USERNAME, username);
|
||||
jsonObject.addProperty(HandlerConstants.PASSWORD, password);
|
||||
jsonObject.addProperty(HandlerConstants.IS_ALLOWED_TO_ALL_DOMAINS_KEY, "false");
|
||||
jsonObject.add(HandlerConstants.TAGS_KEY, tags);
|
||||
public static StringEntity constructAppRegPayload(ArrayNode tags, String appName, String username, String password,
|
||||
String callbackUrl, ArrayList<String> supportedGrantTypes) {
|
||||
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
|
||||
data.put(HandlerConstants.APP_NAME_KEY, appName);
|
||||
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) {
|
||||
jsonObject.addProperty(HandlerConstants.CALLBACK_URL_KEY, callbackUrl);
|
||||
data.put(HandlerConstants.CALLBACK_URL_KEY, callbackUrl);
|
||||
}
|
||||
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 httpSession - current active HttpSession
|
||||
* @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 {
|
||||
HttpGet uiConfigEndpoint = new HttpGet(uiConfigUrl);
|
||||
ProxyResponse uiConfigResponse = HandlerUtil.execute(uiConfigEndpoint);
|
||||
@ -529,39 +503,28 @@ public class HandlerUtil {
|
||||
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.");
|
||||
HandlerUtil.handleError(resp, null);
|
||||
}
|
||||
JsonParser jsonParser = new JsonParser();
|
||||
|
||||
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);
|
||||
} else {
|
||||
httpSession.setAttribute(HandlerConstants.UI_CONFIG_KEY, responseData);
|
||||
httpSession.setAttribute(HandlerConstants.PLATFORM, gatewayUrl);
|
||||
}
|
||||
return uiConfigJsonObject;
|
||||
return responseData;
|
||||
}
|
||||
|
||||
/***
|
||||
* 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
|
||||
*/
|
||||
public static String getScopeString(JsonArray scopes) {
|
||||
if (scopes != null && scopes.size() > 0) {
|
||||
public static String getScopeString(JsonNode scopes) {
|
||||
if (scopes != null && scopes.isArray() && !scopes.isEmpty()) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (JsonElement scope : scopes) {
|
||||
String tmpScope = scope.getAsString() + " ";
|
||||
builder.append(tmpScope);
|
||||
for (JsonNode objNode : scopes) {
|
||||
builder.append(objNode).append(" ");
|
||||
}
|
||||
return builder.toString();
|
||||
} 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.
|
||||
*
|
||||
@ -640,11 +574,11 @@ public class HandlerUtil {
|
||||
* Retry request again after refreshing the access token
|
||||
*
|
||||
* @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.
|
||||
* @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 {
|
||||
ProxyResponse retryResponse = refreshToken(req, apiEndpoint);
|
||||
if (isResponseSuccessful(retryResponse)) {
|
||||
@ -660,7 +594,6 @@ public class HandlerUtil {
|
||||
return proxyResponse;
|
||||
}
|
||||
return proxyResponse;
|
||||
|
||||
}
|
||||
return retryResponse;
|
||||
}
|
||||
@ -682,7 +615,6 @@ public class HandlerUtil {
|
||||
if (session == null) {
|
||||
log.error("Couldn't find a session, hence it is required to login and proceed.");
|
||||
tokenResultResponse = constructProxyResponseByErrorCode(HttpStatus.SC_UNAUTHORIZED);
|
||||
// handleError(resp, HttpStatus.SC_UNAUTHORIZED);
|
||||
return tokenResultResponse;
|
||||
}
|
||||
|
||||
@ -690,23 +622,20 @@ public class HandlerUtil {
|
||||
tokenResultResponse = getTokenResult(authData, keymanagerUrl);
|
||||
if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) {
|
||||
log.error("Error occurred while refreshing access token.");
|
||||
// HandlerUtil.handleError(resp, tokenResultResponse);
|
||||
return tokenResultResponse;
|
||||
}
|
||||
|
||||
JsonParser jsonParser = new JsonParser();
|
||||
JsonElement jTokenResult = jsonParser.parse(tokenResultResponse.getData());
|
||||
|
||||
if (jTokenResult.isJsonObject()) {
|
||||
setNewAuthData(constructAuthDataFromTokenResult(jTokenResult, authData), session);
|
||||
JsonNode tokenResponse = tokenResultResponse.getData();
|
||||
if (tokenResponse != null) {
|
||||
setNewAuthData(constructAuthDataFromTokenResult(tokenResponse, authData), session);
|
||||
return tokenResultResponse;
|
||||
}
|
||||
|
||||
log.error("Error Occurred in token renewal process.");
|
||||
tokenResultResponse = constructProxyResponseByErrorCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
|
||||
// handleError(resp, HttpStatus.SC_INTERNAL_SERVER_ERROR);
|
||||
return tokenResultResponse;
|
||||
}
|
||||
|
||||
public static ProxyResponse getTokenResult(AuthData authData, String keymanagerUrl) throws IOException {
|
||||
HttpPost tokenEndpoint = new HttpPost(keymanagerUrl + HandlerConstants.OAUTH2_TOKEN_ENDPOINT);
|
||||
StringEntity tokenEndpointPayload = new StringEntity(
|
||||
@ -726,12 +655,17 @@ public class HandlerUtil {
|
||||
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();
|
||||
newAuthData.setAccessToken(jTokenResultAsJsonObject.get("access_token").getAsString());
|
||||
newAuthData.setRefreshToken(jTokenResultAsJsonObject.get("refresh_token").getAsString());
|
||||
newAuthData.setScope(jTokenResultAsJsonObject.get("scope").getAsString());
|
||||
newAuthData.setAccessToken(tokenResult.get("access_token").textValue());
|
||||
newAuthData.setRefreshToken(tokenResult.get("refresh_token").textValue());
|
||||
newAuthData.setScope(tokenResult.get("scope").textValue());
|
||||
newAuthData.setClientId(authData.getClientId());
|
||||
newAuthData.setClientSecret(authData.getClientSecret());
|
||||
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
|
||||
* 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();
|
||||
while (headerNames.hasMoreElements()) {
|
||||
String headerName = headerNames.nextElement();
|
||||
@ -774,18 +708,6 @@ public class HandlerUtil {
|
||||
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) {
|
||||
return StringUtils.isEmpty(System.getProperty(property));
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user