Add Default Token Handling Servlet

revert-70ac1926
tcdlpds@gmail.com 5 years ago
parent 3d38bd5570
commit e0eb4316f4

@ -0,0 +1,139 @@
/* Copyright (c) 2020, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.ui.request.interceptor;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.entgra.ui.request.interceptor.beans.AuthData;
import io.entgra.ui.request.interceptor.util.HandlerConstants;
import io.entgra.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.HttpGet;
import org.apache.http.entity.ContentType;
import org.wso2.carbon.device.application.mgt.common.ProxyResponse;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@MultipartConfig
@WebServlet(
name = "DefaultTokenHandlerServlet",
description = "This servlet intercepts the api requests initiated from the user interface to get the default "
+ "token",
urlPatterns = { "/default-credentials/*" }
)
public class DefaultTokenHandler extends HttpServlet {
private static final Log log = LogFactory.getLog(DefaultTokenHandler.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
try {
HttpSession httpSession = req.getSession(false);
if (httpSession != null) {
AuthData authData = (AuthData) httpSession.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY);
if (authData == null) {
HandlerUtil.sendUnAuthorizeResponse(resp);
return;
}
AuthData defaultAuthData = (AuthData) httpSession
.getAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY);
if (defaultAuthData != null) {
HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultAuthData.getAccessToken()));
return;
}
String clientId = authData.getClientId();
String clientSecret = authData.getClientSecret();
String iotsCorePort = System.getProperty("iot.core.https.port");
if (HandlerConstants.HTTP_PROTOCOL.equals(req.getScheme())) {
iotsCorePort = System.getProperty("iot.core.http.port");
}
String tokenUrl =
req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty("iot.core.host")
+ HandlerConstants.COLON + iotsCorePort + "/api/device-mgt/v1.0/devices" + clientId
+ HandlerConstants.SCHEME_SEPARATOR + clientSecret + HandlerConstants.SCHEME_SEPARATOR
+ "default-token";
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)) {
log.error("Error occurred while invoking the API to get default token data.");
HandlerUtil.handleError(resp, tokenResultResponse);
return;
}
String 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);
String defaultToken = jTokenResultAsJsonObject.get("access_token").getAsString();
newDefaultAuthData.setAccessToken(defaultToken);
newDefaultAuthData.setRefreshToken(jTokenResultAsJsonObject.get("refresh_token").getAsString());
newDefaultAuthData.setScope(jTokenResultAsJsonObject.get("scope").getAsString());
httpSession.setAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY, newDefaultAuthData);
HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultToken));
}
} else {
HandlerUtil.sendUnAuthorizeResponse(resp);
}
} catch (IOException e) {
log.error("Error occurred when processing GET request to get default token.", e);
}
}
/**
* Get Success Proxy Response
* @param responseString Response String
* @return {@link ProxyResponse}
*/
private ProxyResponse constructSuccessProxyResponse (String responseString) {
ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_OK);
proxyResponse.setData(responseString);
return proxyResponse;
}
}

@ -72,7 +72,6 @@ public class LoginHandler extends HttpServlet {
httpSession.setMaxInactiveInterval(Math.toIntExact(HandlerConstants.TIMEOUT));
HttpGet uiConfigEndpoint = new HttpGet(uiConfigUrl);
JsonParser jsonParser = new JsonParser();
ProxyResponse uiConfigResponse = HandlerUtil.execute(uiConfigEndpoint);
String executorResponse = uiConfigResponse.getExecutorResponse();
if (!StringUtils.isEmpty(executorResponse) && executorResponse
@ -88,6 +87,7 @@ public class LoginHandler extends HttpServlet {
HandlerUtil.handleError(resp, null);
return;
}
JsonParser jsonParser = new JsonParser();
JsonElement uiConfigJsonElement = jsonParser.parse(uiConfigResponse.getData());
JsonObject uiConfigJsonObject = null;
if (uiConfigJsonElement.isJsonObject()) {

@ -56,13 +56,13 @@ public class UserHandler extends HttpServlet {
+ HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme());
HttpSession httpSession = req.getSession(false);
if (httpSession == null) {
sendUnAuthorizeResponse(resp);
HandlerUtil.sendUnAuthorizeResponse(resp);
return;
}
AuthData authData = (AuthData) httpSession.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY);
if (authData == null) {
sendUnAuthorizeResponse(resp);
HandlerUtil.sendUnAuthorizeResponse(resp);
return;
}
@ -91,7 +91,7 @@ public class UserHandler extends HttpServlet {
if (jTokenResult.isJsonObject()) {
JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject();
if (!jTokenResultAsJsonObject.get("active").getAsBoolean()) {
sendUnAuthorizeResponse(resp);
HandlerUtil.sendUnAuthorizeResponse(resp);
return;
}
ProxyResponse proxyResponse = new ProxyResponse();
@ -106,18 +106,4 @@ public class UserHandler extends HttpServlet {
log.error("Error occurred while parsing the response. ", e);
}
}
/**
* Send UnAuthorized Response to the user
*
* @param resp HttpServletResponse object
*/
private void sendUnAuthorizeResponse(HttpServletResponse resp)
throws IOException {
ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_UNAUTHORIZED);
proxyResponse.setExecutorResponse(
HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + HandlerUtil.getStatusKey(HttpStatus.SC_UNAUTHORIZED));
HandlerUtil.handleError(resp, proxyResponse);
}
}

@ -30,6 +30,7 @@ public class HandlerConstants {
public static final String TAGS_KEY = "tags";
public static final String APP_NAME_KEY = "applicationName";
public static final String SESSION_AUTH_DATA_KEY = "authInfo";
public static final String SESSION_DEFAULT_AUTH_DATA_KEY = "defaultAuthInfo";
public static final String UI_CONFIG_KEY = "ui-config";
public static final String PLATFORM = "platform";
public static final String USERNAME = "username";

@ -19,7 +19,6 @@
package io.entgra.ui.request.interceptor.util;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -35,9 +34,7 @@ import org.json.JSONException;
import org.json.JSONObject;
import org.wso2.carbon.device.application.mgt.common.ProxyResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@ -232,4 +229,17 @@ public class HandlerUtil {
}
}
/**
* Send UnAuthorized Response to the user
*
* @param resp HttpServletResponse object
*/
public static void sendUnAuthorizeResponse(HttpServletResponse resp)
throws IOException {
ProxyResponse proxyResponse = new ProxyResponse();
proxyResponse.setCode(HttpStatus.SC_UNAUTHORIZED);
proxyResponse.setExecutorResponse(
HandlerConstants.EXECUTOR_EXCEPTION_PREFIX + HandlerUtil.getStatusKey(HttpStatus.SC_UNAUTHORIZED));
handleError(resp, proxyResponse);
}
}

Loading…
Cancel
Save