2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
8 * Unless otherwise specified, all software contained herein is licensed
9 * under the Apache License, Version 2.0 (the "License");
10 * you may not use this software except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * Unless otherwise specified, all documentation contained herein is licensed
22 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23 * you may not use this documentation except in compliance with the License.
24 * You may obtain a copy of the License at
26 * https://creativecommons.org/licenses/by/4.0/
28 * Unless required by applicable law or agreed to in writing, documentation
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
34 * ============LICENSE_END============================================
38 package org.onap.portalapp.portal.service;
40 import java.util.List;
42 import javax.servlet.http.HttpServletRequest;
43 import org.apache.commons.codec.binary.Base64;
44 import org.onap.portalapp.portal.domain.EPUser;
45 import org.onap.portalapp.portal.domain.MicroserviceData;
46 import org.onap.portalapp.portal.domain.MicroserviceParameter;
47 import org.onap.portalapp.portal.domain.WidgetCatalogParameter;
48 import org.onap.portalapp.portal.domain.WidgetServiceHeaders;
49 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
50 import org.onap.portalapp.portal.utils.EcompPortalUtils;
51 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
52 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
53 import org.onap.portalsdk.core.onboarding.util.KeyConstants;
54 import org.onap.portalsdk.core.onboarding.util.KeyProperties;
55 import org.onap.portalsdk.core.util.SystemProperties;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.springframework.context.annotation.EnableAspectJAutoProxy;
58 import org.springframework.http.HttpEntity;
59 import org.springframework.http.HttpHeaders;
60 import org.springframework.http.HttpMethod;
61 import org.springframework.http.MediaType;
62 import org.springframework.http.ResponseEntity;
63 import org.springframework.stereotype.Service;
64 import org.springframework.web.client.HttpClientErrorException;
65 import org.springframework.web.client.RestTemplate;
67 @Service("microserviceProxyService")
68 @EnableAspectJAutoProxy
70 public class MicroserviceProxyServiceImpl implements MicroserviceProxyService {
72 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MicroserviceProxyServiceImpl.class);
74 private static final String BASIC_AUTH = "Basic Authentication";
75 private static final String NO_AUTH = "No Authentication";
76 private static final String COOKIE_AUTH = "Cookie based Authentication";
77 private static final String QUESTION_MARK = "?";
78 private static final String ADD_MARK = "&";
81 private WidgetMService widgetMService;
83 MicroserviceService microserviceService;
85 WidgetParameterService widgetParameterService;
87 private String whatService = "widgets-service";
89 private RestTemplate template = new RestTemplate();
92 public String proxyToDestination(long serviceId, EPUser user, HttpServletRequest request) throws Exception {
93 // get the microservice object by the id
94 MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId);
95 // No such microservice available
97 // can we return a better response than null?
100 return authenticateAndRespond(data, request, composeParams(data, user));
104 public String proxyToDestinationByWidgetId(long widgetId, EPUser user, HttpServletRequest request)
106 @SuppressWarnings({ "rawtypes", "unchecked" })
107 ResponseEntity<Long> ans = (ResponseEntity<Long>) template.exchange(
108 EcompPortalUtils.widgetMsProtocol() + "://"
109 + widgetMService.getServiceLocation(whatService,
110 SystemProperties.getProperty("microservices.widget.local.port"))
111 + "/widget/microservices/widgetCatalog/parameters/" + widgetId,
112 HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), Long.class);
113 Long serviceId = ans.getBody();
114 // get the microservice object by the id
115 MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId);
116 // No such microservice available
120 List<MicroserviceParameter> params = composeParams(data, user);
121 for (MicroserviceParameter p : params) {
122 WidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(),
124 if (userValue != null)
125 p.setPara_value(userValue.getUser_value());
127 return authenticateAndRespond(data, request, params);
130 private String authenticateAndRespond(MicroserviceData data, HttpServletRequest request,
131 List<MicroserviceParameter> params) throws HttpClientErrorException, IllegalArgumentException {
132 String response = null;
133 if (data.getSecurityType().equals(NO_AUTH)) {
134 HttpEntity<String> entity = new HttpEntity<String>(headersForNoAuth());
135 String url = microserviceUrlConverter(data, params);
136 logger.debug(EELFLoggerDelegate.debugLogger,
137 "authenticateAndRespond: Before making no authentication call: {}", url);
138 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
139 logger.debug(EELFLoggerDelegate.debugLogger, "authenticateAndRespond: No authentication call response: {}",
141 } else if (data.getSecurityType().equals(BASIC_AUTH)) {
142 // encoding the username and password
143 String plainCreds = null;
145 plainCreds = data.getUsername() + ":" + decryptedPassword(data.getPassword());
146 } catch (Exception e) {
147 logger.error("authenticateAndRespond failed to decrypt password", e);
148 throw new IllegalArgumentException("Failed to decrypt password", e);
150 byte[] plainCredsBytes = plainCreds.getBytes();
151 byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
152 String base64Creds = new String(base64CredsBytes);
154 HttpEntity<String> entity = new HttpEntity<String>(headersForBasicAuth(request, base64Creds));
156 String url = microserviceUrlConverter(data, params);
158 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
159 } catch (HttpClientErrorException e) {
160 logger.error("authenticateAndRespond failed for basic security url " + url, e);
163 } else if (data.getSecurityType().equals(COOKIE_AUTH)) {
164 HttpEntity<String> entity = new HttpEntity<String>(headersForCookieAuth(request));
165 String url = microserviceUrlConverter(data, params);
167 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
168 } catch (HttpClientErrorException e) {
169 logger.error("authenticateAndRespond failed for cookie auth url " + url, e);
177 private String decryptedPassword(String encryptedPwd) throws Exception {
179 if (encryptedPwd != null && encryptedPwd.length() > 0) {
181 result = CipherUtil.decryptPKC(encryptedPwd,
182 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
183 } catch (Exception e) {
184 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
192 private String microserviceUrlConverter(MicroserviceData data, List<MicroserviceParameter> params) {
193 String url = data.getUrl();
194 for (int i = 0; i < params.size(); i++) {
196 url += QUESTION_MARK;
198 url += params.get(i).getPara_key() + "=" + params.get(i).getPara_value();
199 if (i != (params.size() - 1)) {
207 private HttpHeaders headersForNoAuth() {
208 HttpHeaders headers = new HttpHeaders();
209 headers.setContentType(MediaType.APPLICATION_JSON);
214 // TODO: why is this generically named cookie used?
215 private final static String Cookie = "Cookie";
217 private HttpHeaders headersForBasicAuth(HttpServletRequest request, String base64Creds) {
218 HttpHeaders headers = new HttpHeaders();
219 headers.add("Authorization", "Basic " + base64Creds);
220 headers.setContentType(MediaType.APPLICATION_JSON);
221 String rawCookie = request.getHeader(Cookie);
222 if (rawCookie != null)
223 headers.add(Cookie, rawCookie);
227 private HttpHeaders headersForCookieAuth(HttpServletRequest request) {
228 HttpHeaders headers = new HttpHeaders();
229 headers.setContentType(MediaType.APPLICATION_JSON);
230 String rawCookie = request.getHeader(Cookie);
231 if (rawCookie != null)
232 headers.add(Cookie, rawCookie);
236 private List<MicroserviceParameter> composeParams(MicroserviceData data, EPUser user) {
237 List<MicroserviceParameter> params = data.getParameterList();
238 MicroserviceParameter userIdParam = new MicroserviceParameter();
239 userIdParam.setPara_key("userId");
240 userIdParam.setPara_value(user.getOrgUserId());
241 params.add(userIdParam);