2 * ================================================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property
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 * ================================================================================*/
19 package org.openecomp.portalapp.portal.interceptor;
21 import java.nio.charset.Charset;
22 import java.util.Base64;
25 import javax.servlet.http.HttpServletRequest;
26 import javax.servlet.http.HttpServletResponse;
28 import org.openecomp.portalapp.controller.sessionmgt.SessionCommunicationController;
29 import org.openecomp.portalapp.portal.controller.BasicAuthenticationController;
30 import org.openecomp.portalapp.portal.controller.ExternalAppsRestfulController;
31 import org.openecomp.portalapp.portal.controller.SharedContextRestController;
32 import org.openecomp.portalapp.portal.controller.WebAnalyticsExtAppController;
33 import org.openecomp.portalapp.portal.domain.BasicAuthCredentials;
34 import org.openecomp.portalapp.portal.domain.EPEndpoint;
35 import org.openecomp.portalapp.portal.domain.EPUser;
36 import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
37 import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
38 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
39 import org.openecomp.portalapp.portal.service.BasicAuthenticationCredentialService;
40 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
41 import org.openecomp.portalapp.service.RemoteWebServiceCallService;
42 import org.openecomp.portalapp.service.sessionmgt.ManageService;
43 import org.openecomp.portalapp.util.EPUserUtils;
44 import org.openecomp.portalsdk.core.controller.FusionBaseController;
45 import org.openecomp.portalsdk.core.exception.UrlAccessRestrictedException;
46 import org.openecomp.portalsdk.core.interceptor.ResourceInterceptor;
47 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
48 import org.openecomp.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
49 import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
50 import org.openecomp.portalsdk.core.util.SystemProperties;
51 import org.openecomp.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
52 import org.springframework.beans.factory.annotation.Autowired;
53 import org.springframework.web.method.HandlerMethod;
55 public class PortalResourceInterceptor extends ResourceInterceptor {
56 private static final String APP_KEY = "uebkey";
58 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalResourceInterceptor.class);
61 private RemoteWebServiceCallService remoteWebServiceCallService;
64 private ManageService manageService;
67 private EPEELFLoggerAdvice epAdvice;
70 private BasicAuthenticationCredentialService basicAuthService;
72 @SuppressWarnings("unchecked")
74 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
77 if (handler instanceof HandlerMethod) {
78 HandlerMethod method = (HandlerMethod) handler;
81 * These classes provide REST endpoints used by other application
82 * servers, NOT by an end user's browser.
84 if (method.getBean() instanceof FusionBaseController) {
85 FusionBaseController controller = (FusionBaseController) method.getBean();
86 if (!controller.isAccessible()) {
88 // authorize portalApi requests by user role
89 String requestURI = request.getRequestURI();
90 if (requestURI != null) {
91 String[] uriArray = requestURI.split("/portalApi/");
92 if (uriArray.length > 1) {
93 String portalApiPath = uriArray[1];
95 Set<? extends String> roleFunctions = (Set<? extends String>) request.getSession()
96 .getAttribute(SystemProperties
97 .getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
98 Set<? extends String> allRoleFunctions = (Set<? extends String>) request.getSession()
99 .getAttribute(EPUserUtils.ALL_ROLE_FUNCTIONS);
100 // Defend against code error to avoid throwing NPE
101 if (roleFunctions == null || allRoleFunctions == null) {
102 logger.error(EELFLoggerDelegate.errorLogger,
103 "preHandle: failed to get role functions attribute(s) from session!!");
104 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInitializationError);
107 // check to see if roleFunctions of the user is in
109 // list of all role functions
110 // if not, ignore to prevent restricting every
112 // call; otherwise, if it is, then check for the
114 if (matchRoleFunctions(portalApiPath, allRoleFunctions)
115 && !matchRoleFunctions(portalApiPath, roleFunctions)) {
116 EPUser user = (EPUser) request.getSession().getAttribute(
117 SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
118 logger.error(EELFLoggerDelegate.errorLogger,
119 "preHandle: User {} not authorized for path {} ", user.getOrgUserId(),
121 EcompPortalUtils.setBadPermissions(user, response, portalApiPath);
122 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError);
131 else if (method.getBean() instanceof BasicAuthenticationController) {
132 return checkBasicAuth(request, response);
134 Object controllerObj = method.getBean();
135 if (controllerObj instanceof SessionCommunicationController
136 || controllerObj instanceof SharedContextRestController
137 || controllerObj instanceof ExternalAppsRestfulController) {
138 // check user authentication for RESTful calls
139 String secretKey = null;
141 epAdvice.loadServletRequestBasedDefaults(request, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
142 if (!remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(APP_KEY),
143 request.getHeader("username"), request.getHeader("password"))) {
144 throw new UrlAccessRestrictedException();
146 } catch (Exception e) {
147 logger.error(EELFLoggerDelegate.errorLogger, "preHandle: failed to authenticate RESTful service",
149 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
150 throw new UrlAccessRestrictedException();
154 if (controllerObj instanceof WebAnalyticsExtAppController) {
155 if (!remoteWebServiceCallService.verifyAppKeyCredential(request.getHeader(APP_KEY))) {
156 logger.error(EELFLoggerDelegate.errorLogger,
157 "preHandle: failed to verify app key for web analytics call");
158 throw new UrlAccessRestrictedException();
163 handleSessionUpdates(request);
168 * Sets the status code and sends a response. Factors code out of many
172 * HttpServletResponse
174 * HTTP status code like 404
176 * Message to send in a JSON error object
178 private void sendErrorResponse(HttpServletResponse response, final int statusCode, final String message)
180 response.setStatus(statusCode);
181 response.setContentType("application/json");
182 response.getWriter().write("{\"error\":\"" + message + "\"}");
183 response.getWriter().flush();
187 * Gets HTTP basic authentication information from the request and checks
188 * whether those credentials are authorized for the request path.
193 * HttpServletResponse
194 * @return True if the request is authorized, else false
197 private boolean checkBasicAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {
198 String uri = request.getRequestURI().toString();
199 uri = uri.substring(uri.indexOf("/", 1));
201 final String authHeader = request.getHeader("Authorization");
203 // Unauthorized access due to missing HTTP Authorization request header
204 if (authHeader == null) {
205 final String msg = "no authorization found";
206 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
207 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
211 String[] accountNamePassword = getUserNamePassword(authHeader);
212 if (accountNamePassword == null || accountNamePassword.length != 2) {
213 final String msg = "failed to get username and password from Atuhorization header";
214 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
215 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
219 BasicAuthCredentials creds;
221 creds = basicAuthService.getBasicAuthCredentialByUsernameAndPassword(accountNamePassword[0],
222 encrypted(accountNamePassword[1]));
223 } catch (Exception e) {
224 logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials", e);
225 final String msg = "Failed while getting basic authentication credential: " + e.toString();
226 sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
230 // Unauthorized access due to invalid credentials (username and
232 if (creds == null || !creds.getUsername().equals(accountNamePassword[0])) {
233 final String msg = "Unauthorized: Access denied";
234 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
235 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
239 // Unauthorized access due to inactive account
240 if (creds.getIsActive().equals("N")) {
241 final String msg = "Unauthorized: The account is inactive";
242 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
243 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
246 boolean isAllowedEp = false;
247 for (EPEndpoint ep : creds.getEndpoints()) {
248 if (ep.getName().equals(uri)) {
254 // If user doesn't specify any endpoint, allow all endpoints for that
256 if (creds.getEndpoints().size() == 0)
259 // Unauthorized access due to the invalid endpoints
261 final String msg = "Unauthorized: Endpoint access denied";
262 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
263 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
267 // Made it to the end!
271 private String[] getUserNamePassword(String authValue) {
272 String base64Credentials = authValue.substring("Basic".length()).trim();
273 String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
274 final String[] values = credentials.split(":", 2);
278 private String decrypted(String encrypted) throws Exception {
280 if (encrypted != null & encrypted.length() > 0) {
282 result = CipherUtil.decrypt(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
283 } catch (Exception e) {
284 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
291 private String encrypted(String decryptedPwd) throws Exception {
293 if (decryptedPwd != null & decryptedPwd.length() > 0) {
295 result = CipherUtil.encrypt(decryptedPwd,
296 SystemProperties.getProperty(SystemProperties.Decryption_Key));
297 } catch (Exception e) {
298 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword() failed", e);
305 private Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
306 for (String roleFunction : roleFunctions) {
307 if (portalApiPath.matches(roleFunction))
314 protected void handleSessionUpdates(HttpServletRequest request) {
315 PortalTimeoutHandler.handleSessionUpdatesNative(request, null, null, null, null, manageService);