Merge branch 'application-mgt-new' of https://gitlab.com/tcdlpds/carbon-device-mgt into application-mgt-new

feature/appm-store/pbac
Jayasanka 6 years ago
commit e93de0b67d

@ -62,170 +62,172 @@ public class InvokerHandler extends HttpServlet {
private static String serverUrl;
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
try {
if (!validateRequest(req, resp)) {
return;
}
HttpRequestBase executor = constructExecutor(req);
if (executor == null) {
resp.sendError(HTTP_BAD_REQUEST, "Bad Request, method: " + method + " is not supported");
return;
}
String accessToken = authData.getAccessToken();
executor.setHeader("Authorization", "Bearer " + accessToken);
HttpResponse response = execute(executor);
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);
if (responseCode == HttpStatus.SC_UNAUTHORIZED && (result.contains("Access token expired") || result
.contains("Invalid input. Access token validation failed"))) {
if (!refreshToken(req, resp)) {
return;
}
response = execute(executor);
if (response == null) {
resp.sendError(HTTP_INTERNAL_ERROR, "Empty response retried for the token renewal API call.");
return;
}
responseCode = response.getStatusLine().getStatusCode();
result = retrieveResponseString(response);
}
if (responseCode != HttpStatus.SC_OK && responseCode != HttpStatus.SC_CREATED) {
resp.sendError(responseCode, "Error response retrieved for the API call.");
return;
}
try (PrintWriter writer = resp.getWriter()) {
writer.write(result);
}
} 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.
*/
private HttpRequestBase constructExecutor(HttpServletRequest req) {
String payload = req.getParameter("payload");
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);
} else if (HttpPost.METHOD_NAME.equalsIgnoreCase(method)) {
executor = new HttpPost(serverUrl + HandlerConstants.API_COMMON_CONTEXT + apiEndpoint);
StringEntity payloadEntity = new StringEntity(payload, ContentType.create(contentType));
((HttpPost) executor).setEntity(payloadEntity);
} else if (HttpPut.METHOD_NAME.equalsIgnoreCase(method)) {
executor = new HttpPut(serverUrl + HandlerConstants.API_COMMON_CONTEXT + apiEndpoint);
StringEntity payloadEntity = new StringEntity(payload, ContentType.create(contentType));
((HttpPut) executor).setEntity(payloadEntity);
} else if (HttpDelete.METHOD_NAME.equalsIgnoreCase(method)) {
executor = new HttpDelete(serverUrl + HandlerConstants.API_COMMON_CONTEXT + apiEndpoint);
} else {
return null;
}
return executor;
}
/***
*
* @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 static boolean validateRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
HttpSession session = req.getSession(false);
if (session == null) {
resp.sendError(HTTP_UNAUTHORIZED, "Unauthorized, You are not logged in. Please log in to the portal");
return false;
}
authData = (AuthData) session.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY);
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");
serverUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort();
if (apiEndpoint == null || method == null) {
resp.sendError(HTTP_BAD_REQUEST, "Bad Request, Either api-endpoint or method is empty");
return false;
}
return true;
}
/***
*
* @param req {@link HttpServletRequest}
* @param resp {@link HttpServletResponse}
* @return If successfully renew tokens, returns TRUE otherwise return FALSE
* @throws IOException If and error occurs while witting error response to client side or invoke token renewal API
*/
private static boolean refreshToken(HttpServletRequest req, HttpServletResponse resp) throws IOException {
log.debug("refreshing the token");
HttpPost tokenEndpoint = new HttpPost(
serverUrl + HandlerConstants.API_COMMON_CONTEXT + HandlerConstants.TOKEN_ENDPOINT);
HttpSession session = req.getSession(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);
tokenEndpoint.setEntity(tokenEndpointPayload);
String encodedClientApp = authData.getEncodedClientApp();
tokenEndpoint.setHeader("Authorization", "Basic " + encodedClientApp);
tokenEndpoint.setHeader("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.toString());
HttpResponse response = execute(tokenEndpoint);
if (response == null) {
resp.sendError(HTTP_INTERNAL_ERROR,
"Internal Server Error, response of the token refresh API call is null.");
return false;
} else if ((response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)) {
resp.sendError(response.getStatusLine().getStatusCode(),
"Error occured while getting new access token by using refresh token.");
return false;
}
String tokenResult = retrieveResponseString(response);
JsonParser jsonParser = new JsonParser();
JsonElement jTokenResult = jsonParser.parse(tokenResult);
if (jTokenResult.isJsonObject()) {
JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
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.setClientId(authData.getClientId());
newAuthData.setClientSecret(authData.getClientSecret());
newAuthData.setEncodedClientApp(authData.getEncodedClientApp());
newAuthData.setUsername(authData.getUsername());
authData = newAuthData;
session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, newAuthData);
return true;
}
return false;
}
// @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
// try {
// if (!validateRequest(req, resp)) {
// return;
// }
//
// HttpRequestBase executor = constructExecutor(req);
// if (executor == null) {
// resp.sendError(HTTP_BAD_REQUEST, "Bad Request, method: " + method + " is not supported");
// return;
// }
// String accessToken = authData.getAccessToken();
// executor.setHeader("Authorization", "Bearer " + accessToken);
//
// String result = execute(executor, HttpStatus.SC_OK);
//
//// unauthorized
//// 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);
//
// if (responseCode == HttpStatus.SC_UNAUTHORIZED && (result.contains("Access token expired") || result
// .contains("Invalid input. Access token validation failed"))) {
// if (!refreshToken(req, resp)) {
// return;
// }
// response = execute(executor);
// if (response == null) {
// resp.sendError(HTTP_INTERNAL_ERROR, "Empty response retried for the token renewal API call.");
// return;
// }
// responseCode = response.getStatusLine().getStatusCode();
// result = retrieveResponseString(response);
// }
// if (responseCode != HttpStatus.SC_OK && responseCode != HttpStatus.SC_CREATED) {
// resp.sendError(responseCode, "Error response retrieved for the API call.");
// return;
// }
// try (PrintWriter writer = resp.getWriter()) {
// writer.write(result);
// }
// } 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.
// */
// private HttpRequestBase constructExecutor(HttpServletRequest req) {
// String payload = req.getParameter("payload");
// 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);
// } else if (HttpPost.METHOD_NAME.equalsIgnoreCase(method)) {
// executor = new HttpPost(serverUrl + HandlerConstants.API_COMMON_CONTEXT + apiEndpoint);
// StringEntity payloadEntity = new StringEntity(payload, ContentType.create(contentType));
// ((HttpPost) executor).setEntity(payloadEntity);
// } else if (HttpPut.METHOD_NAME.equalsIgnoreCase(method)) {
// executor = new HttpPut(serverUrl + HandlerConstants.API_COMMON_CONTEXT + apiEndpoint);
// StringEntity payloadEntity = new StringEntity(payload, ContentType.create(contentType));
// ((HttpPut) executor).setEntity(payloadEntity);
// } else if (HttpDelete.METHOD_NAME.equalsIgnoreCase(method)) {
// executor = new HttpDelete(serverUrl + HandlerConstants.API_COMMON_CONTEXT + apiEndpoint);
// } else {
// return null;
// }
// return executor;
// }
//
// /***
// *
// * @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 static boolean validateRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// HttpSession session = req.getSession(false);
// if (session == null) {
// resp.sendError(HTTP_UNAUTHORIZED, "Unauthorized, You are not logged in. Please log in to the portal");
// return false;
// }
// authData = (AuthData) session.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY);
// 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");
//
// serverUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort();
// if (apiEndpoint == null || method == null) {
// resp.sendError(HTTP_BAD_REQUEST, "Bad Request, Either api-endpoint or method is empty");
// return false;
// }
// return true;
// }
//
// /***
// *
// * @param req {@link HttpServletRequest}
// * @param resp {@link HttpServletResponse}
// * @return If successfully renew tokens, returns TRUE otherwise return FALSE
// * @throws IOException If and error occurs while witting error response to client side or invoke token renewal API
// */
// private static boolean refreshToken(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// log.debug("refreshing the token");
// HttpPost tokenEndpoint = new HttpPost(
// serverUrl + HandlerConstants.API_COMMON_CONTEXT + HandlerConstants.TOKEN_ENDPOINT);
// HttpSession session = req.getSession(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);
//
// tokenEndpoint.setEntity(tokenEndpointPayload);
// String encodedClientApp = authData.getEncodedClientApp();
// tokenEndpoint.setHeader("Authorization", "Basic " + encodedClientApp);
// tokenEndpoint.setHeader("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.toString());
//
// HttpResponse response = execute(tokenEndpoint);
// if (response == null) {
// resp.sendError(HTTP_INTERNAL_ERROR,
// "Internal Server Error, response of the token refresh API call is null.");
// return false;
// } else if ((response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)) {
// resp.sendError(response.getStatusLine().getStatusCode(),
// "Error occured while getting new access token by using refresh token.");
// return false;
// }
// String tokenResult = retrieveResponseString(response);
// JsonParser jsonParser = new JsonParser();
//
// JsonElement jTokenResult = jsonParser.parse(tokenResult);
// if (jTokenResult.isJsonObject()) {
// JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
// 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.setClientId(authData.getClientId());
// newAuthData.setClientSecret(authData.getClientSecret());
// newAuthData.setEncodedClientApp(authData.getEncodedClientApp());
// newAuthData.setUsername(authData.getUsername());
// authData = newAuthData;
// session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, newAuthData);
// return true;
// }
// return false;
// }
}

@ -26,10 +26,12 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
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.exceptions.LoginException;
import org.wso2.carbon.device.application.mgt.handler.util.HandlerConstants;
@ -47,8 +49,6 @@ import java.io.IOException;
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.loadUiConfig;
import static org.wso2.carbon.device.application.mgt.handler.util.HandlerUtil.retrieveResponseString;
@MultipartConfig
@WebServlet("/login")
@ -61,6 +61,7 @@ public class LoginHandler extends HttpServlet {
private static String platform;
private static String serverUrl;
private static String uiConfigUrl;
private static JsonObject uiConfig;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
@ -79,7 +80,19 @@ public class LoginHandler extends HttpServlet {
//setting session to expiry in 5 mins
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) {
resp.sendRedirect(serverUrl + "/" + platform + HandlerConstants.DEFAULT_ERROR_CALLBACK);
return;
@ -98,11 +111,8 @@ public class LoginHandler extends HttpServlet {
.encodeToString((adminUsername + HandlerConstants.COLON + adminPwd).getBytes()));
apiRegEndpoint.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
apiRegEndpoint.setEntity(constructAppRegPayload(tags));
HttpResponse response = execute(apiRegEndpoint);
if (!evaluateResponse(response,resp, HttpStatus.SC_CREATED)){
return;
}
String clientAppResult = retrieveResponseString(response);
String clientAppResult = execute(apiRegEndpoint, HttpStatus.SC_CREATED);
if (!clientAppResult.isEmpty() && persistTokenInSession(req, resp, clientAppResult, scopes)) {
resp.sendRedirect(
@ -256,51 +266,30 @@ public class LoginHandler extends HttpServlet {
"grant_type=password&username=" + username + "&password=" + password + "&scope=" + scopeString,
ContentType.APPLICATION_FORM_URLENCODED);
tokenEndpoint.setEntity(tokenEPPayload);
HttpResponse response = execute(tokenEndpoint);
if (evaluateResponse(response, resp, HttpStatus.SC_OK)){
return retrieveResponseString(response);
}
return null;
String tokenResult = execute(tokenEndpoint, HttpStatus.SC_OK);
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 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.
* @throws LoginException If an {@link IOException} occurs when redirecting to corresponding error page.
*/
private boolean evaluateResponse(HttpResponse response, HttpServletResponse resp, int expectedStatusCode)
throws LoginException {
JsonObject uiJsonObject = loadUiConfig(uiConfigUrl);
private void handleErrorResponse(HttpServletResponse resp, String respMessage) throws LoginException {
try {
if (response == null) {
if (uiJsonObject != null) {
resp.sendRedirect(serverUrl + uiJsonObject.get(HandlerConstants.LOGIN_RESPONSE_KEY).getAsJsonObject()
resp.sendRedirect(serverUrl + uiConfig.get(HandlerConstants.LOGIN_RESPONSE_KEY).getAsJsonObject()
.get(HandlerConstants.FAILURE_CALLBACK_KEY).getAsJsonObject()
.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;
}
.get(respMessage.split(HandlerConstants.EXECUTOR_XCEPTIO_PRFIX)[0]).getAsString());
} catch (IOException 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 FAILURE_CALLBACK_KEY = "FailureCallback";
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 long TIMEOUT = 300;

@ -46,7 +46,7 @@ public class HandlerUtil {
* @return response as string
* @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;
try (CloseableHttpClient client = HttpClients.createDefault()) {
if (httpMethod instanceof HttpPost) {
@ -57,10 +57,24 @@ public class HandlerUtil {
response = client.execute(method);
}
if (response != null) {
return response;
if (response == null) {
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);
JsonParser jsonParser = new JsonParser();
HttpResponse response = execute(uiConfigEndpoint);
if (response != null && response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
String uiConfig = retrieveResponseString(response);
String uiConfig = execute(uiConfigEndpoint,HttpStatus.SC_OK);
JsonElement uiConfigJsonElement = jsonParser.parse(uiConfig);
if (uiConfigJsonElement.isJsonObject()) {
uiConfigAsJsonObject = uiConfigJsonElement.getAsJsonObject();
return uiConfigAsJsonObject;
}
}
} catch (IOException e) {
throw new LoginException("Error occured while getting UI configs. ", e);
}

Loading…
Cancel
Save