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);
98 // Authentication via ecomp portal
100 String userIdFromCookie = getUserIdFromCookie(request);
101 if (("").equals(userIdFromCookie)) {
102 // This is probably a webseal request, so missing header in request should be printed.
103 response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG);
105 userId = userIdFromCookie;
106 } catch (Exception e) {
107 response.sendError(HttpServletResponse.SC_USE_PROXY, AUTHORIZATION_ERROR_MSG);
108 log.error("Error during adding request header", e);
112 // Replace webseal header with open source header
113 mutableRequest.putHeader(Constants.USER_ID, userId);
119 // Getting identification headers from configuration.yaml
120 // (identificationHeaderFields) and setting them to new request
122 List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields();
123 for (List<String> possibleHeadersToRecieve : identificationHeaderFields) {
124 String allowedHeaderToPass = possibleHeadersToRecieve.get(0);
125 setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest);
128 // Getting optional headers from configuration.yaml
129 // (optionalHeaderFields) and setting them to new request mutableRequest
130 List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields();
131 for (List<String> possibleHeadersToRecieve : optionalHeaderFields) {
132 String allowedHeaderToPass = possibleHeadersToRecieve.get(0);
133 setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest);
136 // Print headers from original request for debug purposes
137 printHeaders(request);
139 // In case using webseal, validate all mandatory headers (identificationHeaderFields) are included in the new request (mutableRequest).
140 // Via ecomp portal do not need to check the headers.
141 boolean allHeadersExist = true;
142 if (null != request.getHeader(Constants.WEBSEAL_USER_ID_HEADER)) {
143 allHeadersExist = checkHeaders(mutableRequest);
146 if (allHeadersExist) {
147 addCookies(response, mutableRequest, getMandatoryHeaders(request));
148 addCookies(response, mutableRequest, getOptionalHeaders(request));
149 getValueFromCookie(request, Constants.HTTP_CSP_FIRSTNAME );
150 getValueFromCookie(request, Constants.HTTP_CSP_LASTNAME);
153 //addAuthCookie(response, userId, firstNameFromCookie, lastNameFromCookie);
154 RequestDispatcher rd = request.getRequestDispatcher("index.html");
155 rd.forward(mutableRequest, response);
157 response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG);
161 boolean addAuthCookie(HttpServletResponse response, String userId, String firstName, String lastName) throws IOException {
162 boolean isBuildCookieCompleted = true;
163 Cookie authCookie = null;
164 Configuration.CookieConfig confCookie =
165 ConfigurationManager.getConfigurationManager().getConfiguration().getAuthCookie();
167 //create authentication and send it to encryption
169 String encryptedCookie = "";
171 AuthenticationCookie authenticationCookie = new AuthenticationCookie(userId, firstName, lastName);
172 String cookieAsJson = RepresentationUtils.toRepresentation(authenticationCookie);
173 encryptedCookie = org.onap.sdc.security.CipherUtil.encryptPKC(cookieAsJson, confCookie.getSecurityKey());
174 } catch (Exception e) {
175 isBuildCookieCompleted=false;
176 log.error(" Cookie Encryption failed ", e);
179 authCookie = new Cookie(confCookie.getCookieName(), encryptedCookie);
180 authCookie.setPath(confCookie.getPath());
181 authCookie.setDomain(confCookie.getDomain());
182 authCookie.setHttpOnly(true);
184 // add generated cookie to response
185 if (isBuildCookieCompleted) {
186 response.addCookie(authCookie);
189 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, AUTHORIZATION_ERROR_MSG);
194 * Print all request headers to the log
198 private void printHeaders(HttpServletRequest request) {
200 if (log.isDebugEnabled()) {
201 StringBuilder builder = new StringBuilder();
202 String sessionId = "";
203 if (request.getSession() != null) {
204 String id = request.getSession().getId();
210 builder.append("Receiving request with headers:" + NEW_LINE);
211 log.debug("{}", request.getHeaderNames());
212 @SuppressWarnings("unchecked")
213 Enumeration<String> headerNames = request.getHeaderNames();
214 if (headerNames != null) {
215 while (headerNames.hasMoreElements()) {
216 String headerName = headerNames.nextElement();
217 String headerValue = request.getHeader(headerName);
218 builder.append("session " + sessionId + " header: name = " + headerName + ", value = " + headerValue + NEW_LINE);
222 log.debug(builder.toString());
228 * Add cookies (that where set in the new request headers) in the response
229 * Using DefaultHTTPUtilities Object to prevent CRLF injection in HTTP headers.
235 private void addCookies(HttpServletResponse response, HttpServletRequest request, String[] headers) {
236 for (int i = 0; i < headers.length; i++) {
237 String currHeader = headers[i];
238 String headerValue = request.getHeader(currHeader);
239 if (headerValue != null) {
240 final Cookie cookie = new Cookie(currHeader, headerValue);
241 cookie.setSecure(true);
242 response.addCookie(cookie);
248 * Get mandatory headers (identificationHeaderFields) String array, and
249 * checks that each header exists in the new request
254 private boolean checkHeaders(HttpServletRequest request) {
255 String[] mandatoryHeaders = getMandatoryHeaders(request);
257 boolean allHeadersExist = true;
258 for (int i = 0; i < mandatoryHeaders.length; i++) {
259 String headerValue = request.getHeader(mandatoryHeaders[i]);
260 if (headerValue == null) {
261 allHeadersExist = false;
265 return allHeadersExist;
269 * Get mandatory headers (identificationHeaderFields) from
270 * configuration.yaml file and return String[]
275 private String[] getMandatoryHeaders(HttpServletRequest request) {
276 Configuration configuration = getConfiguration(request);
277 List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields();
278 String[] mandatoryHeaders = new String[identificationHeaderFields.size()];
279 for (int i = 0; i < identificationHeaderFields.size(); i++) {
280 mandatoryHeaders[i] = identificationHeaderFields.get(i).get(0);
282 return mandatoryHeaders;
286 * Get optional headers (optionalHeaderFields) from configuration.yaml file
287 * and return String[]
292 private String[] getOptionalHeaders(HttpServletRequest request) {
293 Configuration configuration = getConfiguration(request);
294 List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields();
295 String[] optionalHeaders = new String[optionalHeaderFields.size()];
296 for (int i = 0; i < optionalHeaderFields.size(); i++) {
297 optionalHeaders[i] = optionalHeaderFields.get(i).get(0);
299 return optionalHeaders;
303 * Return Configuration object to read from configuration.yaml
306 * @return Configuration
308 private Configuration getConfiguration(HttpServletRequest request) {
309 ConfigurationManager configManager = (ConfigurationManager) request.getSession().getServletContext().getAttribute(org.openecomp.sdc.common.api.Constants.CONFIGURATION_MANAGER_ATTR);
310 return configManager.getConfiguration();
313 private boolean setNewHeader(List<String> possibleOldHeaders, String newHeaderToSet, HttpServletRequest oldRequest, MutableHttpServletRequest newRequest) {
314 boolean newHeaderIsSet = false;
315 for (int i = 0; i < possibleOldHeaders.size() && !newHeaderIsSet; i++) {
316 String headerValue = oldRequest.getHeader(possibleOldHeaders.get(i));
317 if (headerValue != null) {
318 newRequest.putHeader(newHeaderToSet, headerValue);
319 newHeaderIsSet = true;
322 return newHeaderIsSet;
325 private static String getUserIdFromCookie(HttpServletRequest request) throws CipherUtilException {
327 Cookie[] cookies = request.getCookies();
328 Cookie userIdcookie = null;
329 if (cookies != null) {
330 for (Cookie cookie : cookies) {
331 if (cookie.getName().equals(Constants.ECOMP_PORTAL_COOKIE)) {
332 userIdcookie = cookie;
336 if (userIdcookie != null) {
337 userId = CipherUtil.decrypt(userIdcookie.getValue());
342 private static String getValueFromCookie(HttpServletRequest request, String cookieName) {
344 Cookie[] cookies = request.getCookies();
345 Cookie valueFromCookie = null;
347 for (Cookie cookie : cookies) {
348 if (cookie.getName().endsWith(cookieName)) {
349 valueFromCookie = cookie;
352 if (valueFromCookie != null) {
353 value = valueFromCookie.getValue();