2 * ========================LICENSE_START=================================
5 * Copyright (C) 2019 AT&T Intellectual Property
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===================================
20 package org.oransc.ric.portal.dashboard.portalapi;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.UnsupportedEncodingException;
25 import java.lang.invoke.MethodHandles;
26 import java.net.URLEncoder;
27 import java.util.HashSet;
29 import javax.servlet.Filter;
30 import javax.servlet.FilterChain;
31 import javax.servlet.FilterConfig;
32 import javax.servlet.ServletException;
33 import javax.servlet.ServletRequest;
34 import javax.servlet.ServletResponse;
35 import javax.servlet.http.Cookie;
36 import javax.servlet.http.HttpServletRequest;
37 import javax.servlet.http.HttpServletResponse;
39 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
40 import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
41 import org.onap.portalsdk.core.restful.domain.EcompRole;
42 import org.onap.portalsdk.core.restful.domain.EcompUser;
43 import org.oransc.ric.portal.dashboard.DashboardConstants;
44 import org.oransc.ric.portal.dashboard.DashboardUserManager;
45 import org.oransc.ric.portal.dashboard.model.EcompUserDetails;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.springframework.http.MediaType;
49 import org.springframework.security.core.Authentication;
50 import org.springframework.security.core.context.SecurityContextHolder;
51 import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
54 * This filter checks every request for the cookie set by the ONAP Portal single
55 * sign on process. The possible paths and actions:
57 * <LI>User starts at an app page via a bookmark. No Portal cookie is set.
58 * Redirect there to get one; then continue as below.
59 * <LI>User starts at Portal and goes to app. Alternately, the user's session
60 * times out and the user hits refresh. The Portal cookie is set, but there is
61 * no valid session. Create one and publish info.
62 * <LI>User has valid Portal cookie and session. Reset the max idle in that
68 * <LI>While redirecting, the cookie "redirectUrl" should also be set so that
69 * Portal knows where to forward the request to once the Portal Session is
70 * created and EPService cookie is set.
73 * TODO: What about sessions? Will this be stateless?
75 * This filter uses no annotations to avoid Spring's automatic registration,
76 * which add this filter in the chain in the wrong order.
78 public class PortalAuthenticationFilter implements Filter {
80 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
82 // Unfortunately these names are not available as constants
83 private static final String[] securityPropertyFiles = { "ESAPI.properties", "key.properties", "portal.properties",
84 "validation.properties" };
86 public static final String REDIRECT_URL_KEY = "redirectUrl";
88 private final boolean enforcePortalSecurity;
89 private final PortalAuthManager authManager;
91 private final DashboardUserManager userManager;
93 public PortalAuthenticationFilter(boolean portalSecurity, PortalAuthManager authManager,
94 DashboardUserManager userManager) {
95 this.enforcePortalSecurity = portalSecurity;
96 this.authManager = authManager;
97 this.userManager = userManager;
99 // Throw if security is requested and prerequisites are not met
100 for (String pf : securityPropertyFiles) {
101 InputStream in = MethodHandles.lookup().lookupClass().getClassLoader().getResourceAsStream(pf);
103 String msg = "Failed to find property file on classpath: " + pf;
105 throw new RuntimeException(msg);
109 } catch (IOException ex) {
110 logger.warn("Failed to close stream", ex);
118 public void init(FilterConfig filterConfig) throws ServletException {
119 // complain loudly if this key property is missing
120 String url = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
121 logger.debug("init: Portal redirect URL {}", url);
124 "init: Failed to find property in portal.properties: " + PortalApiConstants.ECOMP_REDIRECT_URL);
128 public void destroy() {
129 // No resources to release
133 * Requests for pages ignored in the web security config do not hit this filter.
136 public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
137 throws IOException, ServletException {
138 if (enforcePortalSecurity)
139 doFilterEPSDKFW(req, res, chain);
141 doFilterMockUserAdminRole(req, res, chain);
145 * Populates security context with a mock user in the admin role.
148 private void doFilterMockUserAdminRole(ServletRequest req, ServletResponse res, FilterChain chain)
149 throws IOException, ServletException {
150 Authentication auth = SecurityContextHolder.getContext().getAuthentication();
151 if (auth == null || auth.getAuthorities().isEmpty()) {
152 if (logger.isDebugEnabled()) {
153 logger.debug("doFilter adding auth to request URI {}",
154 (req instanceof HttpServletRequest) ? ((HttpServletRequest) req).getRequestURL() : req);
156 EcompRole admin = new EcompRole();
158 admin.setName(DashboardConstants.ROLE_ADMIN);
159 HashSet<EcompRole> roles = new HashSet<>();
161 EcompUser user = new EcompUser();
162 user.setLoginId("fakeLoginId");
163 user.setRoles(roles);
164 user.setActive(true);
165 EcompUserDetails userDetails = new EcompUserDetails(user);
166 PreAuthenticatedAuthenticationToken authToken = new PreAuthenticatedAuthenticationToken(userDetails,
167 "fakeCredentials", userDetails.getAuthorities());
168 SecurityContextHolder.getContext().setAuthentication(authToken);
170 logger.debug("doFilter: authorities {}", auth.getAuthorities());
172 chain.doFilter(req, res);
176 * Checks for valid cookies and allows request to be served if found; redirects
177 * to Portal otherwise.
179 private void doFilterEPSDKFW(ServletRequest req, ServletResponse res, FilterChain chain)
180 throws IOException, ServletException {
181 HttpServletRequest request = (HttpServletRequest) req;
182 HttpServletResponse response = (HttpServletResponse) res;
183 if (logger.isTraceEnabled())
184 logger.trace("doFilter: req {}", request.getRequestURI());
185 // Need to authenticate the request
186 final String userId = authManager.validateEcompSso(request);
187 final EcompUser ecompUser = (userId == null ? null : userManager.getUser(userId));
188 if (userId == null || ecompUser == null) {
189 logger.debug("doFilter: unauthorized user requests URI {}, serving login page", request.getRequestURI());
190 StringBuffer sb = request.getRequestURL();
191 sb.append(request.getQueryString() == null ? "" : "?" + request.getQueryString());
192 String body = generateLoginRedirectPage(sb.toString());
193 response.setContentType(MediaType.TEXT_HTML_VALUE);
194 response.getWriter().print(body);
195 response.getWriter().flush();
197 EcompUserDetails userDetails = new EcompUserDetails(ecompUser);
198 // Using portal session as credentials is a hack
199 PreAuthenticatedAuthenticationToken authToken = new PreAuthenticatedAuthenticationToken(userDetails,
200 getPortalSessionId(request), userDetails.getAuthorities());
201 SecurityContextHolder.getContext().setAuthentication(authToken);
202 // Pass request back down the filter chain
203 chain.doFilter(request, response);
208 * Generates a page with text only, absolutely no references to any webapp
209 * resources, so this can be served to an unauthenticated user without
210 * triggering a new authentication attempt. The page has a link to the Portal
211 * URL from configuration, with a return URL that is the original request.
214 * Original requested URL
216 * @throws UnsupportedEncodingException
219 private static String generateLoginRedirectPage(String appUrl) throws UnsupportedEncodingException {
220 String encodedAppUrl = URLEncoder.encode(appUrl, "UTF-8");
221 String portalBaseUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
222 String redirectUrl = portalBaseUrl + "?" + PortalAuthenticationFilter.REDIRECT_URL_KEY + "=" + encodedAppUrl;
223 String aHref = "<a href=\"" + redirectUrl + "\">";
224 // If only Java had "here" documents.
225 String body = String.join(//
226 System.getProperty("line.separator"), //
229 "<title>RIC Dashboard</title>", //
232 " font-family: Helvetica, Arial, sans-serif;", //
237 "<h2>RIC Dashboard</h2>", //
238 "<h4>Please log in.</h4>", //
240 aHref, "Click here to authenticate at the ONAP Portal</a>", //
248 * Searches the request for a cookie with the specified name.
254 * @return Cookie, or null if not found.
256 private Cookie getCookie(HttpServletRequest request, String cookieName) {
257 Cookie[] cookies = request.getCookies();
259 for (Cookie cookie : cookies)
260 if (cookie.getName().equals(cookieName))
266 * Gets the ECOMP Portal service cookie value.
269 * @return Cookie value, or null if not found.
271 private String getPortalSessionId(HttpServletRequest request) {
272 Cookie ep = getCookie(request, PortalApiConstants.EP_SERVICE);
275 return ep.getValue();