2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.fe.servlets;
23 import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
24 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
25 import org.onap.sdc.security.AuthenticationCookie;
26 import org.onap.sdc.security.RepresentationUtils;
27 import org.openecomp.sdc.common.impl.MutableHttpServletRequest;
28 import org.openecomp.sdc.common.log.wrappers.Logger;
29 import org.openecomp.sdc.fe.Constants;
30 import org.openecomp.sdc.fe.config.Configuration;
31 import org.openecomp.sdc.fe.config.ConfigurationManager;
32 import org.openecomp.sdc.fe.config.FeEcompErrorManager;
34 import javax.servlet.RequestDispatcher;
35 import javax.servlet.ServletException;
36 import javax.servlet.http.Cookie;
37 import javax.servlet.http.HttpServlet;
38 import javax.servlet.http.HttpServletRequest;
39 import javax.servlet.http.HttpServletResponse;
40 import javax.ws.rs.GET;
41 import javax.ws.rs.Path;
42 import javax.ws.rs.core.Context;
43 import java.io.IOException;
44 import java.util.Enumeration;
45 import java.util.List;
48 * Root resource (exposed at "/" path)
51 public class PortalServlet extends HttpServlet {
53 private static Logger log = Logger.getLogger(PortalServlet.class.getName());
54 private static final long serialVersionUID = 1L;
56 public static final String MISSING_HEADERS_MSG = "Missing Headers In Request";
57 private static final String AUTHORIZATION_ERROR_MSG = "Autherization error";
58 private static final String NEW_LINE = System.getProperty("line.separator");
62 * Entry point from ECOMP portal
67 public void doGet(@Context final HttpServletRequest request, @Context final HttpServletResponse response) {
69 addRequestHeadersUsingWebseal(request, response);
70 } catch (Exception e) {
71 FeEcompErrorManager.getInstance().logFePortalServletError("Portal Servlet");
72 log.error("Error during getting portal page", e);
77 * Building new HTTP request and setting headers for the request The request
78 * will dispatch to index.html
82 * @throws ServletException
85 private void addRequestHeadersUsingWebseal(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
87 response.setContentType("text/html");
89 // Create new request object to dispatch
90 MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request);
92 // Get configuration object (reads data from configuration.yaml)
93 Configuration configuration = getConfiguration(request);
95 // Check if we got header from webseal
96 String userId = request.getHeader(Constants.WEBSEAL_USER_ID_HEADER);
97 String firstNameFromCookie = "";
98 String lastNameFromCookie = "";
100 // Authentication via ecomp portal
102 String userIdFromCookie = getUserIdFromCookie(request);
103 if (("").equals(userIdFromCookie)) {
104 // This is probably a webseal request, so missing header in request should be printed.
105 response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG);
107 userId = userIdFromCookie;
108 } catch (Exception e) {
109 response.sendError(HttpServletResponse.SC_USE_PROXY, AUTHORIZATION_ERROR_MSG);
110 log.error("Error during adding request header", e);
114 // Replace webseal header with open source header
115 mutableRequest.putHeader(Constants.USER_ID, userId);
121 // Getting identification headers from configuration.yaml
122 // (identificationHeaderFields) and setting them to new request
124 List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields();
125 for (List<String> possibleHeadersToRecieve : identificationHeaderFields) {
126 String allowedHeaderToPass = possibleHeadersToRecieve.get(0);
127 setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest);
130 // Getting optional headers from configuration.yaml
131 // (optionalHeaderFields) and setting them to new request mutableRequest
132 List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields();
133 for (List<String> possibleHeadersToRecieve : optionalHeaderFields) {
134 String allowedHeaderToPass = possibleHeadersToRecieve.get(0);
135 setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest);
138 // Print headers from original request for debug purposes
139 printHeaders(request);
141 // In case using webseal, validate all mandatory headers (identificationHeaderFields) are included in the new request (mutableRequest).
142 // Via ecomp portal do not need to check the headers.
143 boolean allHeadersExist = true;
144 if (null != request.getHeader(Constants.WEBSEAL_USER_ID_HEADER)) {
145 allHeadersExist = checkHeaders(mutableRequest);
148 if (allHeadersExist) {
149 addCookies(response, mutableRequest, getMandatoryHeaders(request));
150 addCookies(response, mutableRequest, getOptionalHeaders(request));
151 firstNameFromCookie = getValueFromCookie(request, Constants.HTTP_CSP_FIRSTNAME );
152 lastNameFromCookie = getValueFromCookie(request, Constants.HTTP_CSP_LASTNAME);
154 addAuthCookie(response, userId, firstNameFromCookie, lastNameFromCookie);
155 RequestDispatcher rd = request.getRequestDispatcher("index.html");
156 rd.forward(mutableRequest, response);
158 response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG);
162 boolean addAuthCookie(HttpServletResponse response, String userId, String firstName, String lastName) throws IOException {
163 boolean isBuildCookieCompleted = true;
164 AuthenticationCookie authenticationCookie = null;
165 Cookie authCookie = null;
166 Configuration.CookieConfig confCookie =
167 ConfigurationManager.getConfigurationManager().getConfiguration().getAuthCookie();
169 //create authentication and send it to encryption
171 String encryptedCookie = "";
173 authenticationCookie = new AuthenticationCookie(userId, firstName, lastName);
174 String cookieAsJson = RepresentationUtils.toRepresentation(authenticationCookie);
175 encryptedCookie = org.onap.sdc.security.CipherUtil.encryptPKC(cookieAsJson, confCookie.getSecurityKey());
176 } catch (Exception e) {
177 isBuildCookieCompleted=false;
178 log.error(" Cookie Encryption failed ", e);
181 authCookie = new Cookie(confCookie.getCookieName(), encryptedCookie);
182 authCookie.setPath(confCookie.getPath());
183 authCookie.setDomain(confCookie.getDomain());
184 authCookie.setHttpOnly(true);
186 // add generated cookie to response
187 if (isBuildCookieCompleted) {
188 response.addCookie(authCookie);
191 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, AUTHORIZATION_ERROR_MSG);
196 * Print all request headers to the log
200 private void printHeaders(HttpServletRequest request) {
202 if (log.isDebugEnabled()) {
203 StringBuilder builder = new StringBuilder();
204 String sessionId = "";
205 if (request.getSession() != null) {
206 String id = request.getSession().getId();
212 builder.append("Receiving request with headers:" + NEW_LINE);
213 log.debug("{}", request.getHeaderNames());
214 @SuppressWarnings("unchecked")
215 Enumeration<String> headerNames = request.getHeaderNames();
216 if (headerNames != null) {
217 while (headerNames.hasMoreElements()) {
218 String headerName = headerNames.nextElement();
219 String headerValue = request.getHeader(headerName);
220 builder.append("session " + sessionId + " header: name = " + headerName + ", value = " + headerValue + NEW_LINE);
224 log.debug(builder.toString());
230 * Add cookies (that where set in the new request headers) in the response
231 * Using DefaultHTTPUtilities Object to prevent CRLF injection in HTTP headers.
237 private void addCookies(HttpServletResponse response, HttpServletRequest request, String[] headers) {
238 for (int i = 0; i < headers.length; i++) {
239 String currHeader = headers[i];
240 String headerValue = request.getHeader(currHeader);
241 if (headerValue != null) {
242 final Cookie cookie = new Cookie(currHeader, headerValue);
243 cookie.setSecure(true);
244 response.addCookie(cookie);
250 * Get mandatory headers (identificationHeaderFields) String array, and
251 * checks that each header exists in the new request
256 private boolean checkHeaders(HttpServletRequest request) {
257 String[] mandatoryHeaders = getMandatoryHeaders(request);
259 boolean allHeadersExist = true;
260 for (int i = 0; i < mandatoryHeaders.length; i++) {
261 String headerValue = request.getHeader(mandatoryHeaders[i]);
262 if (headerValue == null) {
263 allHeadersExist = false;
267 return allHeadersExist;
271 * Get mandatory headers (identificationHeaderFields) from
272 * configuration.yaml file and return String[]
277 private String[] getMandatoryHeaders(HttpServletRequest request) {
278 Configuration configuration = getConfiguration(request);
279 List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields();
280 String[] mandatoryHeaders = new String[identificationHeaderFields.size()];
281 for (int i = 0; i < identificationHeaderFields.size(); i++) {
282 mandatoryHeaders[i] = identificationHeaderFields.get(i).get(0);
284 return mandatoryHeaders;
288 * Get optional headers (optionalHeaderFields) from configuration.yaml file
289 * and return String[]
294 private String[] getOptionalHeaders(HttpServletRequest request) {
295 Configuration configuration = getConfiguration(request);
296 List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields();
297 String[] optionalHeaders = new String[optionalHeaderFields.size()];
298 for (int i = 0; i < optionalHeaderFields.size(); i++) {
299 optionalHeaders[i] = optionalHeaderFields.get(i).get(0);
301 return optionalHeaders;
305 * Return Configuration object to read from configuration.yaml
308 * @return Configuration
310 private Configuration getConfiguration(HttpServletRequest request) {
311 ConfigurationManager configManager = (ConfigurationManager) request.getSession().getServletContext().getAttribute(org.openecomp.sdc.common.api.Constants.CONFIGURATION_MANAGER_ATTR);
312 return configManager.getConfiguration();
315 private boolean setNewHeader(List<String> possibleOldHeaders, String newHeaderToSet, HttpServletRequest oldRequest, MutableHttpServletRequest newRequest) {
316 boolean newHeaderIsSet = false;
317 for (int i = 0; i < possibleOldHeaders.size() && !newHeaderIsSet; i++) {
318 String headerValue = oldRequest.getHeader(possibleOldHeaders.get(i));
319 if (headerValue != null) {
320 newRequest.putHeader(newHeaderToSet, headerValue);
321 newHeaderIsSet = true;
324 return newHeaderIsSet;
327 private static String getUserIdFromCookie(HttpServletRequest request) throws CipherUtilException {
329 Cookie[] cookies = request.getCookies();
330 Cookie userIdcookie = null;
331 if (cookies != null) {
332 for (Cookie cookie : cookies) {
333 if (cookie.getName().equals(Constants.ECOMP_PORTAL_COOKIE)) {
334 userIdcookie = cookie;
338 if (userIdcookie != null) {
339 userId = CipherUtil.decrypt(userIdcookie.getValue());
344 private static String getValueFromCookie(HttpServletRequest request, String cookieName) {
346 Cookie[] cookies = request.getCookies();
347 Cookie valueFromCookie = null;
349 for (Cookie cookie : cookies) {
350 if (cookie.getName().endsWith(cookieName)) {
351 valueFromCookie = cookie;
354 if (valueFromCookie != null) {
355 value = valueFromCookie.getValue();