mirror of
https://repository.entgra.net/community/device-mgt-core.git
synced 2025-10-06 02:01:45 +00:00
Fix token generating for APPM and add WIP code
This commit is contained in:
parent
6c543922b4
commit
42a4196ed4
@ -62,170 +62,172 @@ public class InvokerHandler extends HttpServlet {
|
|||||||
private static String serverUrl;
|
private static String serverUrl;
|
||||||
|
|
||||||
|
|
||||||
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
|
// @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
|
||||||
try {
|
// try {
|
||||||
if (!validateRequest(req, resp)) {
|
// if (!validateRequest(req, resp)) {
|
||||||
return;
|
// return;
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
HttpRequestBase executor = constructExecutor(req);
|
// HttpRequestBase executor = constructExecutor(req);
|
||||||
if (executor == null) {
|
// if (executor == null) {
|
||||||
resp.sendError(HTTP_BAD_REQUEST, "Bad Request, method: " + method + " is not supported");
|
// resp.sendError(HTTP_BAD_REQUEST, "Bad Request, method: " + method + " is not supported");
|
||||||
return;
|
// return;
|
||||||
}
|
// }
|
||||||
String accessToken = authData.getAccessToken();
|
// String accessToken = authData.getAccessToken();
|
||||||
executor.setHeader("Authorization", "Bearer " + accessToken);
|
// executor.setHeader("Authorization", "Bearer " + accessToken);
|
||||||
|
//
|
||||||
HttpResponse response = execute(executor);
|
// String result = execute(executor, HttpStatus.SC_OK);
|
||||||
if (response == null) {
|
//
|
||||||
resp.sendError(HTTP_INTERNAL_ERROR, "Empty response retried for the API call.");
|
//// unauthorized
|
||||||
return;
|
//// if (response == null) {
|
||||||
}
|
//// resp.sendError(HTTP_INTERNAL_ERROR, "Empty response retried for the API call.");
|
||||||
|
//// return;
|
||||||
int responseCode = response.getStatusLine().getStatusCode();
|
//// }
|
||||||
String result = retrieveResponseString(response);
|
//
|
||||||
|
//// int responseCode = response.getStatusLine().getStatusCode();
|
||||||
if (responseCode == HttpStatus.SC_UNAUTHORIZED && (result.contains("Access token expired") || result
|
//// String result = retrieveResponseString(response);
|
||||||
.contains("Invalid input. Access token validation failed"))) {
|
//
|
||||||
if (!refreshToken(req, resp)) {
|
// if (responseCode == HttpStatus.SC_UNAUTHORIZED && (result.contains("Access token expired") || result
|
||||||
return;
|
// .contains("Invalid input. Access token validation failed"))) {
|
||||||
}
|
// if (!refreshToken(req, resp)) {
|
||||||
response = execute(executor);
|
// return;
|
||||||
if (response == null) {
|
// }
|
||||||
resp.sendError(HTTP_INTERNAL_ERROR, "Empty response retried for the token renewal API call.");
|
// response = execute(executor);
|
||||||
return;
|
// if (response == null) {
|
||||||
}
|
// resp.sendError(HTTP_INTERNAL_ERROR, "Empty response retried for the token renewal API call.");
|
||||||
responseCode = response.getStatusLine().getStatusCode();
|
// return;
|
||||||
result = retrieveResponseString(response);
|
// }
|
||||||
}
|
// responseCode = response.getStatusLine().getStatusCode();
|
||||||
if (responseCode != HttpStatus.SC_OK && responseCode != HttpStatus.SC_CREATED) {
|
// result = retrieveResponseString(response);
|
||||||
resp.sendError(responseCode, "Error response retrieved for the API call.");
|
// }
|
||||||
return;
|
// if (responseCode != HttpStatus.SC_OK && responseCode != HttpStatus.SC_CREATED) {
|
||||||
}
|
// resp.sendError(responseCode, "Error response retrieved for the API call.");
|
||||||
try (PrintWriter writer = resp.getWriter()) {
|
// return;
|
||||||
writer.write(result);
|
// }
|
||||||
}
|
// try (PrintWriter writer = resp.getWriter()) {
|
||||||
} catch (IOException e) {
|
// writer.write(result);
|
||||||
log.error("Error occured when processing invoke call.", e);
|
// }
|
||||||
}
|
// } catch (IOException e) {
|
||||||
}
|
// log.error("Error occured when processing invoke call.", e);
|
||||||
|
// }
|
||||||
/***
|
// }
|
||||||
*
|
//
|
||||||
* @param req {@link HttpServletRequest}
|
// /***
|
||||||
* @return {@link HttpRequestBase} if method equals to either GET, POST, PUT or DELETE otherwise returns NULL.
|
// *
|
||||||
*/
|
// * @param req {@link HttpServletRequest}
|
||||||
private HttpRequestBase constructExecutor(HttpServletRequest req) {
|
// * @return {@link HttpRequestBase} if method equals to either GET, POST, PUT or DELETE otherwise returns NULL.
|
||||||
String payload = req.getParameter("payload");
|
// */
|
||||||
String contentType = req.getParameter("content-type");
|
// private HttpRequestBase constructExecutor(HttpServletRequest req) {
|
||||||
if (contentType == null || contentType.isEmpty()) {
|
// String payload = req.getParameter("payload");
|
||||||
contentType = ContentType.APPLICATION_JSON.toString();
|
// String contentType = req.getParameter("content-type");
|
||||||
}
|
// if (contentType == null || contentType.isEmpty()) {
|
||||||
|
// contentType = ContentType.APPLICATION_JSON.toString();
|
||||||
HttpRequestBase executor;
|
// }
|
||||||
if (HttpGet.METHOD_NAME.equalsIgnoreCase(method)) {
|
//
|
||||||
executor = new HttpGet(serverUrl + HandlerConstants.API_COMMON_CONTEXT + apiEndpoint);
|
// HttpRequestBase executor;
|
||||||
} else if (HttpPost.METHOD_NAME.equalsIgnoreCase(method)) {
|
// if (HttpGet.METHOD_NAME.equalsIgnoreCase(method)) {
|
||||||
executor = new HttpPost(serverUrl + HandlerConstants.API_COMMON_CONTEXT + apiEndpoint);
|
// executor = new HttpGet(serverUrl + HandlerConstants.API_COMMON_CONTEXT + apiEndpoint);
|
||||||
StringEntity payloadEntity = new StringEntity(payload, ContentType.create(contentType));
|
// } else if (HttpPost.METHOD_NAME.equalsIgnoreCase(method)) {
|
||||||
((HttpPost) executor).setEntity(payloadEntity);
|
// executor = new HttpPost(serverUrl + HandlerConstants.API_COMMON_CONTEXT + apiEndpoint);
|
||||||
} else if (HttpPut.METHOD_NAME.equalsIgnoreCase(method)) {
|
// StringEntity payloadEntity = new StringEntity(payload, ContentType.create(contentType));
|
||||||
executor = new HttpPut(serverUrl + HandlerConstants.API_COMMON_CONTEXT + apiEndpoint);
|
// ((HttpPost) executor).setEntity(payloadEntity);
|
||||||
StringEntity payloadEntity = new StringEntity(payload, ContentType.create(contentType));
|
// } else if (HttpPut.METHOD_NAME.equalsIgnoreCase(method)) {
|
||||||
((HttpPut) executor).setEntity(payloadEntity);
|
// executor = new HttpPut(serverUrl + HandlerConstants.API_COMMON_CONTEXT + apiEndpoint);
|
||||||
} else if (HttpDelete.METHOD_NAME.equalsIgnoreCase(method)) {
|
// StringEntity payloadEntity = new StringEntity(payload, ContentType.create(contentType));
|
||||||
executor = new HttpDelete(serverUrl + HandlerConstants.API_COMMON_CONTEXT + apiEndpoint);
|
// ((HttpPut) executor).setEntity(payloadEntity);
|
||||||
} else {
|
// } else if (HttpDelete.METHOD_NAME.equalsIgnoreCase(method)) {
|
||||||
return null;
|
// executor = new HttpDelete(serverUrl + HandlerConstants.API_COMMON_CONTEXT + apiEndpoint);
|
||||||
}
|
// } else {
|
||||||
return executor;
|
// return null;
|
||||||
}
|
// }
|
||||||
|
// return executor;
|
||||||
/***
|
// }
|
||||||
*
|
//
|
||||||
* @param req {@link HttpServletRequest}
|
// /***
|
||||||
* @param resp {@link HttpServletResponse}
|
// *
|
||||||
* @return If request is a valid one, returns TRUE, otherwise return FALSE
|
// * @param req {@link HttpServletRequest}
|
||||||
* @throws IOException If and error occurs while witting error response to client side
|
// * @param resp {@link HttpServletResponse}
|
||||||
*/
|
// * @return If request is a valid one, returns TRUE, otherwise return FALSE
|
||||||
private static boolean validateRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
|
// * @throws IOException If and error occurs while witting error response to client side
|
||||||
HttpSession session = req.getSession(false);
|
// */
|
||||||
if (session == null) {
|
// private static boolean validateRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
|
||||||
resp.sendError(HTTP_UNAUTHORIZED, "Unauthorized, You are not logged in. Please log in to the portal");
|
// HttpSession session = req.getSession(false);
|
||||||
return false;
|
// if (session == null) {
|
||||||
}
|
// resp.sendError(HTTP_UNAUTHORIZED, "Unauthorized, You are not logged in. Please log in to the portal");
|
||||||
authData = (AuthData) session.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY);
|
// return false;
|
||||||
if (authData == null) {
|
// }
|
||||||
resp.sendError(HTTP_UNAUTHORIZED, "Unauthorized, Access token couldn't found in the current session");
|
// authData = (AuthData) session.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY);
|
||||||
return false;
|
// if (authData == null) {
|
||||||
}
|
// resp.sendError(HTTP_UNAUTHORIZED, "Unauthorized, Access token couldn't found in the current session");
|
||||||
|
// return false;
|
||||||
apiEndpoint = req.getParameter("api-endpoint");
|
// }
|
||||||
method = req.getParameter("method");
|
//
|
||||||
|
// apiEndpoint = req.getParameter("api-endpoint");
|
||||||
serverUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort();
|
// method = req.getParameter("method");
|
||||||
if (apiEndpoint == null || method == null) {
|
//
|
||||||
resp.sendError(HTTP_BAD_REQUEST, "Bad Request, Either api-endpoint or method is empty");
|
// serverUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort();
|
||||||
return false;
|
// if (apiEndpoint == null || method == null) {
|
||||||
}
|
// resp.sendError(HTTP_BAD_REQUEST, "Bad Request, Either api-endpoint or method is empty");
|
||||||
return true;
|
// return false;
|
||||||
}
|
// }
|
||||||
|
// return true;
|
||||||
/***
|
// }
|
||||||
*
|
//
|
||||||
* @param req {@link HttpServletRequest}
|
// /***
|
||||||
* @param resp {@link HttpServletResponse}
|
// *
|
||||||
* @return If successfully renew tokens, returns TRUE otherwise return FALSE
|
// * @param req {@link HttpServletRequest}
|
||||||
* @throws IOException If and error occurs while witting error response to client side or invoke token renewal API
|
// * @param resp {@link HttpServletResponse}
|
||||||
*/
|
// * @return If successfully renew tokens, returns TRUE otherwise return FALSE
|
||||||
private static boolean refreshToken(HttpServletRequest req, HttpServletResponse resp) throws IOException {
|
// * @throws IOException If and error occurs while witting error response to client side or invoke token renewal API
|
||||||
log.debug("refreshing the token");
|
// */
|
||||||
HttpPost tokenEndpoint = new HttpPost(
|
// private static boolean refreshToken(HttpServletRequest req, HttpServletResponse resp) throws IOException {
|
||||||
serverUrl + HandlerConstants.API_COMMON_CONTEXT + HandlerConstants.TOKEN_ENDPOINT);
|
// log.debug("refreshing the token");
|
||||||
HttpSession session = req.getSession(false);
|
// HttpPost tokenEndpoint = new HttpPost(
|
||||||
if (session == null) {
|
// serverUrl + HandlerConstants.API_COMMON_CONTEXT + HandlerConstants.TOKEN_ENDPOINT);
|
||||||
resp.sendError(HTTP_UNAUTHORIZED, "Session is expired. Please log in to the server.");
|
// HttpSession session = req.getSession(false);
|
||||||
return false;
|
// if (session == null) {
|
||||||
}
|
// resp.sendError(HTTP_UNAUTHORIZED, "Session is expired. Please log in to the server.");
|
||||||
|
// return false;
|
||||||
StringEntity tokenEndpointPayload = new StringEntity(
|
// }
|
||||||
"grant_type=refresh_token&refresh_token=" + authData.getRefreshToken() + "&scope=PRODUCTION",
|
//
|
||||||
ContentType.APPLICATION_FORM_URLENCODED);
|
// StringEntity tokenEndpointPayload = new StringEntity(
|
||||||
|
// "grant_type=refresh_token&refresh_token=" + authData.getRefreshToken() + "&scope=PRODUCTION",
|
||||||
tokenEndpoint.setEntity(tokenEndpointPayload);
|
// ContentType.APPLICATION_FORM_URLENCODED);
|
||||||
String encodedClientApp = authData.getEncodedClientApp();
|
//
|
||||||
tokenEndpoint.setHeader("Authorization", "Basic " + encodedClientApp);
|
// tokenEndpoint.setEntity(tokenEndpointPayload);
|
||||||
tokenEndpoint.setHeader("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.toString());
|
// String encodedClientApp = authData.getEncodedClientApp();
|
||||||
|
// tokenEndpoint.setHeader("Authorization", "Basic " + encodedClientApp);
|
||||||
HttpResponse response = execute(tokenEndpoint);
|
// tokenEndpoint.setHeader("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.toString());
|
||||||
if (response == null) {
|
//
|
||||||
resp.sendError(HTTP_INTERNAL_ERROR,
|
// HttpResponse response = execute(tokenEndpoint);
|
||||||
"Internal Server Error, response of the token refresh API call is null.");
|
// if (response == null) {
|
||||||
return false;
|
// resp.sendError(HTTP_INTERNAL_ERROR,
|
||||||
} else if ((response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)) {
|
// "Internal Server Error, response of the token refresh API call is null.");
|
||||||
resp.sendError(response.getStatusLine().getStatusCode(),
|
// return false;
|
||||||
"Error occured while getting new access token by using refresh token.");
|
// } else if ((response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)) {
|
||||||
return false;
|
// resp.sendError(response.getStatusLine().getStatusCode(),
|
||||||
}
|
// "Error occured while getting new access token by using refresh token.");
|
||||||
String tokenResult = retrieveResponseString(response);
|
// return false;
|
||||||
JsonParser jsonParser = new JsonParser();
|
// }
|
||||||
|
// String tokenResult = retrieveResponseString(response);
|
||||||
JsonElement jTokenResult = jsonParser.parse(tokenResult);
|
// JsonParser jsonParser = new JsonParser();
|
||||||
if (jTokenResult.isJsonObject()) {
|
//
|
||||||
JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
|
// JsonElement jTokenResult = jsonParser.parse(tokenResult);
|
||||||
AuthData newAuthData = new AuthData();
|
// if (jTokenResult.isJsonObject()) {
|
||||||
|
// JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
|
||||||
newAuthData.setAccessToken(jTokenResultAsJsonObject.get("access_token").getAsString());
|
// AuthData newAuthData = new AuthData();
|
||||||
newAuthData.setRefreshToken(jTokenResultAsJsonObject.get("refresh_token").getAsString());
|
//
|
||||||
newAuthData.setScope(jTokenResultAsJsonObject.get("scope").getAsString());
|
// newAuthData.setAccessToken(jTokenResultAsJsonObject.get("access_token").getAsString());
|
||||||
newAuthData.setClientId(authData.getClientId());
|
// newAuthData.setRefreshToken(jTokenResultAsJsonObject.get("refresh_token").getAsString());
|
||||||
newAuthData.setClientSecret(authData.getClientSecret());
|
// newAuthData.setScope(jTokenResultAsJsonObject.get("scope").getAsString());
|
||||||
newAuthData.setEncodedClientApp(authData.getEncodedClientApp());
|
// newAuthData.setClientId(authData.getClientId());
|
||||||
newAuthData.setUsername(authData.getUsername());
|
// newAuthData.setClientSecret(authData.getClientSecret());
|
||||||
authData = newAuthData;
|
// newAuthData.setEncodedClientApp(authData.getEncodedClientApp());
|
||||||
session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, newAuthData);
|
// newAuthData.setUsername(authData.getUsername());
|
||||||
return true;
|
// authData = newAuthData;
|
||||||
}
|
// session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, newAuthData);
|
||||||
return false;
|
// return true;
|
||||||
}
|
// }
|
||||||
|
// return false;
|
||||||
|
// }
|
||||||
}
|
}
|
||||||
|
|||||||
@ -26,10 +26,12 @@ import org.apache.commons.logging.Log;
|
|||||||
import org.apache.commons.logging.LogFactory;
|
import org.apache.commons.logging.LogFactory;
|
||||||
import org.apache.http.HttpResponse;
|
import org.apache.http.HttpResponse;
|
||||||
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.HttpPost;
|
||||||
import org.apache.http.entity.ContentType;
|
import org.apache.http.entity.ContentType;
|
||||||
import org.apache.http.entity.StringEntity;
|
import org.apache.http.entity.StringEntity;
|
||||||
import org.apache.http.protocol.HTTP;
|
import org.apache.http.protocol.HTTP;
|
||||||
|
import org.wso2.carbon.device.application.mgt.common.config.UIConfiguration;
|
||||||
import org.wso2.carbon.device.application.mgt.handler.beans.AuthData;
|
import org.wso2.carbon.device.application.mgt.handler.beans.AuthData;
|
||||||
import org.wso2.carbon.device.application.mgt.handler.exceptions.LoginException;
|
import org.wso2.carbon.device.application.mgt.handler.exceptions.LoginException;
|
||||||
import org.wso2.carbon.device.application.mgt.handler.util.HandlerConstants;
|
import org.wso2.carbon.device.application.mgt.handler.util.HandlerConstants;
|
||||||
@ -47,8 +49,6 @@ import java.io.IOException;
|
|||||||
import java.util.Base64;
|
import java.util.Base64;
|
||||||
|
|
||||||
import static org.wso2.carbon.device.application.mgt.handler.util.HandlerUtil.execute;
|
import static org.wso2.carbon.device.application.mgt.handler.util.HandlerUtil.execute;
|
||||||
import static org.wso2.carbon.device.application.mgt.handler.util.HandlerUtil.loadUiConfig;
|
|
||||||
import static org.wso2.carbon.device.application.mgt.handler.util.HandlerUtil.retrieveResponseString;
|
|
||||||
|
|
||||||
@MultipartConfig
|
@MultipartConfig
|
||||||
@WebServlet("/login")
|
@WebServlet("/login")
|
||||||
@ -61,6 +61,7 @@ public class LoginHandler extends HttpServlet {
|
|||||||
private static String platform;
|
private static String platform;
|
||||||
private static String serverUrl;
|
private static String serverUrl;
|
||||||
private static String uiConfigUrl;
|
private static String uiConfigUrl;
|
||||||
|
private static JsonObject uiConfig;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
|
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
|
||||||
@ -79,7 +80,19 @@ public class LoginHandler extends HttpServlet {
|
|||||||
//setting session to expiry in 5 mins
|
//setting session to expiry in 5 mins
|
||||||
httpSession.setMaxInactiveInterval(Math.toIntExact(HandlerConstants.TIMEOUT));
|
httpSession.setMaxInactiveInterval(Math.toIntExact(HandlerConstants.TIMEOUT));
|
||||||
|
|
||||||
JsonObject uiConfigAsJsonObject = loadUiConfig(uiConfigUrl);
|
HttpGet uiConfigEndpoint = new HttpGet(uiConfigUrl);
|
||||||
|
JsonParser jsonParser = new JsonParser();
|
||||||
|
String uiConfigJsonString = execute(uiConfigEndpoint,HttpStatus.SC_OK);
|
||||||
|
if (uiConfigJsonString.contains(HandlerConstants.EXECUTOR_XCEPTIO_PRFIX)){
|
||||||
|
log.error("Error occurred while getting UI configurations by invoking " + uiConfigUrl);
|
||||||
|
handleErrorResponse(resp, uiConfigJsonString);
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonElement uiConfigJsonElement = jsonParser.parse(uiConfigJsonString);
|
||||||
|
JsonObject uiConfigAsJsonObject = null ;
|
||||||
|
if (uiConfigJsonElement.isJsonObject()) {
|
||||||
|
uiConfigAsJsonObject = uiConfigJsonElement.getAsJsonObject();
|
||||||
|
}
|
||||||
if (uiConfigAsJsonObject == null) {
|
if (uiConfigAsJsonObject == null) {
|
||||||
resp.sendRedirect(serverUrl + "/" + platform + HandlerConstants.DEFAULT_ERROR_CALLBACK);
|
resp.sendRedirect(serverUrl + "/" + platform + HandlerConstants.DEFAULT_ERROR_CALLBACK);
|
||||||
return;
|
return;
|
||||||
@ -98,11 +111,8 @@ public class LoginHandler extends HttpServlet {
|
|||||||
.encodeToString((adminUsername + HandlerConstants.COLON + adminPwd).getBytes()));
|
.encodeToString((adminUsername + HandlerConstants.COLON + adminPwd).getBytes()));
|
||||||
apiRegEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
|
apiRegEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
|
||||||
apiRegEndpoint.setEntity(constructAppRegPayload(tags));
|
apiRegEndpoint.setEntity(constructAppRegPayload(tags));
|
||||||
HttpResponse response = execute(apiRegEndpoint);
|
|
||||||
if (!evaluateResponse(response,resp, HttpStatus.SC_CREATED)){
|
String clientAppResult = execute(apiRegEndpoint, HttpStatus.SC_CREATED);
|
||||||
return;
|
|
||||||
}
|
|
||||||
String clientAppResult = retrieveResponseString(response);
|
|
||||||
|
|
||||||
if (!clientAppResult.isEmpty() && persistTokenInSession(req, resp, clientAppResult, scopes)) {
|
if (!clientAppResult.isEmpty() && persistTokenInSession(req, resp, clientAppResult, scopes)) {
|
||||||
resp.sendRedirect(
|
resp.sendRedirect(
|
||||||
@ -256,51 +266,30 @@ public class LoginHandler extends HttpServlet {
|
|||||||
"grant_type=password&username=" + username + "&password=" + password + "&scope=" + scopeString,
|
"grant_type=password&username=" + username + "&password=" + password + "&scope=" + scopeString,
|
||||||
ContentType.APPLICATION_FORM_URLENCODED);
|
ContentType.APPLICATION_FORM_URLENCODED);
|
||||||
tokenEndpoint.setEntity(tokenEPPayload);
|
tokenEndpoint.setEntity(tokenEPPayload);
|
||||||
HttpResponse response = execute(tokenEndpoint);
|
|
||||||
|
|
||||||
if (evaluateResponse(response, resp, HttpStatus.SC_OK)){
|
String tokenResult = execute(tokenEndpoint, HttpStatus.SC_OK);
|
||||||
return retrieveResponseString(response);
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
|
|
||||||
|
if (tokenResult.contains(HandlerConstants.EXECUTOR_XCEPTIO_PRFIX)) {
|
||||||
|
log.error("Error occurred while getting token data by invoking " + serverUrl
|
||||||
|
+ HandlerConstants.TOKEN_ENDPOINT);
|
||||||
|
handleErrorResponse(resp, tokenResult);
|
||||||
|
}
|
||||||
|
return tokenResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
/***
|
/***
|
||||||
*
|
*
|
||||||
* @param response {@link HttpResponse}
|
|
||||||
* @param resp {@link HttpServletResponse}
|
* @param resp {@link HttpServletResponse}
|
||||||
* @param expectedStatusCode expected status code of the response
|
|
||||||
* @return If response returns expected status code, then returns True otherwise returns False after redirect to
|
|
||||||
* corresponding error page.
|
* corresponding error page.
|
||||||
* @throws LoginException If an {@link IOException} occurs when redirecting to corresponding error page.
|
* @throws LoginException If an {@link IOException} occurs when redirecting to corresponding error page.
|
||||||
*/
|
*/
|
||||||
private boolean evaluateResponse(HttpResponse response, HttpServletResponse resp, int expectedStatusCode)
|
private void handleErrorResponse(HttpServletResponse resp, String respMessage) throws LoginException {
|
||||||
throws LoginException {
|
|
||||||
JsonObject uiJsonObject = loadUiConfig(uiConfigUrl);
|
|
||||||
try {
|
try {
|
||||||
if (response == null) {
|
resp.sendRedirect(serverUrl + uiConfig.get(HandlerConstants.LOGIN_RESPONSE_KEY).getAsJsonObject()
|
||||||
if (uiJsonObject != null) {
|
.get(HandlerConstants.FAILURE_CALLBACK_KEY).getAsJsonObject()
|
||||||
resp.sendRedirect(serverUrl + uiJsonObject.get(HandlerConstants.LOGIN_RESPONSE_KEY).getAsJsonObject()
|
.get(respMessage.split(HandlerConstants.EXECUTOR_XCEPTIO_PRFIX)[0]).getAsString());
|
||||||
.get(HandlerConstants.FAILURE_CALLBACK_KEY).getAsJsonObject()
|
} catch (IOException e) {
|
||||||
.get(HandlerUtil.getStatusKey(HandlerConstants.INTERNAL_ERROR_CODE)).getAsString());
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
resp.sendRedirect(serverUrl + HandlerConstants.DEFAULT_ERROR_CALLBACK);
|
|
||||||
return false;
|
|
||||||
} else if (response.getStatusLine().getStatusCode() != expectedStatusCode) {
|
|
||||||
if (uiJsonObject != null) {
|
|
||||||
resp.sendRedirect(serverUrl + uiJsonObject.get(HandlerConstants.LOGIN_RESPONSE_KEY).getAsJsonObject()
|
|
||||||
.get(HandlerConstants.FAILURE_CALLBACK_KEY).getAsJsonObject()
|
|
||||||
.get(HandlerUtil.getStatusKey(response.getStatusLine().getStatusCode())).getAsString());
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
resp.sendRedirect(serverUrl + HandlerConstants.DEFAULT_ERROR_CALLBACK);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
} catch (IOException e){
|
|
||||||
throw new LoginException("Error occured while redirecting to corresponding error page. ", e);
|
throw new LoginException("Error occured while redirecting to corresponding error page. ", e);
|
||||||
}
|
}
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -32,6 +32,7 @@ public class HandlerConstants {
|
|||||||
public static final String LOGIN_RESPONSE_KEY = "loginResponse";
|
public static final String LOGIN_RESPONSE_KEY = "loginResponse";
|
||||||
public static final String FAILURE_CALLBACK_KEY = "FailureCallback";
|
public static final String FAILURE_CALLBACK_KEY = "FailureCallback";
|
||||||
public static final String API_COMMON_CONTEXT = "/api";
|
public static final String API_COMMON_CONTEXT = "/api";
|
||||||
|
public static final String EXECUTOR_XCEPTIO_PRFIX = "ExecutorException-";
|
||||||
|
|
||||||
public static final int INTERNAL_ERROR_CODE = 500;
|
public static final int INTERNAL_ERROR_CODE = 500;
|
||||||
public static final long TIMEOUT = 300;
|
public static final long TIMEOUT = 300;
|
||||||
|
|||||||
@ -46,7 +46,7 @@ public class HandlerUtil {
|
|||||||
* @return response as string
|
* @return response as string
|
||||||
* @throws IOException IO exception returns if error occurs when executing the httpMethod
|
* @throws IOException IO exception returns if error occurs when executing the httpMethod
|
||||||
*/
|
*/
|
||||||
public static <T> HttpResponse execute(T httpMethod) throws IOException {
|
public static <T> String execute(T httpMethod, int expectedStatusCode) throws IOException {
|
||||||
HttpResponse response = null;
|
HttpResponse response = null;
|
||||||
try (CloseableHttpClient client = HttpClients.createDefault()) {
|
try (CloseableHttpClient client = HttpClients.createDefault()) {
|
||||||
if (httpMethod instanceof HttpPost) {
|
if (httpMethod instanceof HttpPost) {
|
||||||
@ -57,10 +57,24 @@ public class HandlerUtil {
|
|||||||
response = client.execute(method);
|
response = client.execute(method);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (response != null) {
|
if (response == null) {
|
||||||
return response;
|
return HandlerConstants.EXECUTOR_XCEPTIO_PRFIX + getStatusKey(HandlerConstants.INTERNAL_ERROR_CODE);
|
||||||
|
} else {
|
||||||
|
int statusCode = response.getStatusLine().getStatusCode();
|
||||||
|
if ( statusCode != expectedStatusCode) {
|
||||||
|
return HandlerConstants.EXECUTOR_XCEPTIO_PRFIX + getStatusKey(statusCode);
|
||||||
|
} else {
|
||||||
|
try (BufferedReader rd = new BufferedReader(
|
||||||
|
new InputStreamReader(response.getEntity().getContent()))) {
|
||||||
|
StringBuilder result = new StringBuilder();
|
||||||
|
String line;
|
||||||
|
while ((line = rd.readLine()) != null) {
|
||||||
|
result.append(line);
|
||||||
|
}
|
||||||
|
return result.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -138,15 +152,14 @@ public class HandlerUtil {
|
|||||||
}
|
}
|
||||||
HttpGet uiConfigEndpoint = new HttpGet(uiConfigUrl);
|
HttpGet uiConfigEndpoint = new HttpGet(uiConfigUrl);
|
||||||
JsonParser jsonParser = new JsonParser();
|
JsonParser jsonParser = new JsonParser();
|
||||||
HttpResponse response = execute(uiConfigEndpoint);
|
String uiConfig = execute(uiConfigEndpoint,HttpStatus.SC_OK);
|
||||||
if (response != null && response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
|
|
||||||
String uiConfig = retrieveResponseString(response);
|
JsonElement uiConfigJsonElement = jsonParser.parse(uiConfig);
|
||||||
JsonElement uiConfigJsonElement = jsonParser.parse(uiConfig);
|
if (uiConfigJsonElement.isJsonObject()) {
|
||||||
if (uiConfigJsonElement.isJsonObject()) {
|
uiConfigAsJsonObject = uiConfigJsonElement.getAsJsonObject();
|
||||||
uiConfigAsJsonObject = uiConfigJsonElement.getAsJsonObject();
|
return uiConfigAsJsonObject;
|
||||||
return uiConfigAsJsonObject;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
throw new LoginException("Error occured while getting UI configs. ", e);
|
throw new LoginException("Error occured while getting UI configs. ", e);
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user