2 * ========================LICENSE_START=================================
5 * Copyright (C) 2019 AT&T Intellectual Property and Nokia
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.model.EcompUserDetails;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.springframework.http.MediaType;
48 import org.springframework.security.core.Authentication;
49 import org.springframework.security.core.context.SecurityContextHolder;
50 import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
53 * This filter checks every request for the cookie set by the ONAP Portal single
54 * sign on process. The possible paths and actions:
56 * <LI>User starts at an app page via a bookmark. No Portal cookie is set.
57 * Redirect there to get one; then continue as below.
58 * <LI>User starts at Portal and goes to app. Alternately, the user's session
59 * times out and the user hits refresh. The Portal cookie is set, but there is
60 * no valid session. Create one and publish info.
61 * <LI>User has valid Portal cookie and session. Reset the max idle in that
67 * <LI>While redirecting, the cookie "redirectUrl" should also be set so that
68 * Portal knows where to forward the request to once the Portal Session is
69 * created and EPService cookie is set.
72 * TODO: What about sessions? Will this be stateless?
74 * This filter uses no annotations to avoid Spring's automatic registration,
75 * which add this filter in the chain in the wrong order.
77 public class PortalAuthenticationFilter implements Filter {
79 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
81 // Unfortunately these names are not available as constants
82 private static final String[] securityPropertyFiles = { "ESAPI.properties", "key.properties", "portal.properties",
83 "validation.properties" };
85 public static final String REDIRECT_URL_KEY = "redirectUrl";
87 private final boolean enforcePortalSecurity;
88 private final PortalAuthManager authManager;
90 private final DashboardUserManager userManager;
92 public PortalAuthenticationFilter(boolean portalSecurity, PortalAuthManager authManager,
93 DashboardUserManager userManager) {
94 this.enforcePortalSecurity = portalSecurity;
95 this.authManager = authManager;
96 this.userManager = userManager;
98 // Throw if security is requested and prerequisites are not met
99 for (String pf : securityPropertyFiles) {
100 InputStream in = MethodHandles.lookup().lookupClass().getClassLoader().getResourceAsStream(pf);
102 String msg = "Failed to find property file on classpath: " + pf;
104 throw new RuntimeException(msg);
108 } catch (IOException ex) {
109 logger.warn("Failed to close stream", ex);
117 public void init(FilterConfig filterConfig) throws ServletException {
118 // complain loudly if this key property is missing
119 String url = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
120 logger.debug("init: Portal redirect URL {}", url);
123 "init: Failed to find property in portal.properties: " + PortalApiConstants.ECOMP_REDIRECT_URL);
127 public void destroy() {
128 // No resources to release
132 * Requests for pages ignored in the web security config do not hit this filter.
135 public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
136 throws IOException, ServletException {
137 if (enforcePortalSecurity)
138 doFilterEPSDKFW(req, res, chain);
140 doFilterMockUserAdminRole(req, res, chain);
144 * Populates security context with a mock user in the admin role.
147 private void doFilterMockUserAdminRole(ServletRequest req, ServletResponse res, FilterChain chain)
148 throws IOException, ServletException {
149 Authentication auth = SecurityContextHolder.getContext().getAuthentication();
150 if (auth == null || auth.getAuthorities().isEmpty()) {
151 if (logger.isDebugEnabled()) {
152 logger.debug("doFilter adding auth to request URI {}",
153 (req instanceof HttpServletRequest) ? ((HttpServletRequest) req).getRequestURL() : req);
155 EcompRole admin = new EcompRole();
157 admin.setName(DashboardConstants.ROLE_ADMIN);
158 HashSet<EcompRole> roles = new HashSet<>();
160 EcompUser user = new EcompUser();
161 user.setLoginId("fakeLoginId");
162 user.setRoles(roles);
163 user.setActive(true);
164 EcompUserDetails userDetails = new EcompUserDetails(user);
165 PreAuthenticatedAuthenticationToken authToken = new PreAuthenticatedAuthenticationToken(userDetails,
166 "fakeCredentials", userDetails.getAuthorities());
167 SecurityContextHolder.getContext().setAuthentication(authToken);
169 logger.debug("doFilter: authorities {}", auth.getAuthorities());
171 chain.doFilter(req, res);
175 * Checks for valid cookies and allows request to be served if found; redirects
176 * to Portal otherwise.
178 private void doFilterEPSDKFW(ServletRequest req, ServletResponse res, FilterChain chain)
179 throws IOException, ServletException {
180 HttpServletRequest request = (HttpServletRequest) req;
181 HttpServletResponse response = (HttpServletResponse) res;
182 if (logger.isTraceEnabled())
183 logger.trace("doFilter: req {}", request.getRequestURI());
184 // Need to authenticate the request
185 final String userId = authManager.validateEcompSso(request);
186 final EcompUser ecompUser = (userId == null ? null : userManager.getUser(userId));
187 if (userId == null || ecompUser == null) {
188 logger.debug("doFilter: unauthorized user requests URI {}, serving login page", request.getRequestURI());
189 StringBuffer sb = request.getRequestURL();
190 sb.append(request.getQueryString() == null ? "" : "?" + request.getQueryString());
191 String body = generateLoginRedirectPage(sb.toString());
192 response.setContentType(MediaType.TEXT_HTML_VALUE);
193 response.getWriter().print(body);
194 response.getWriter().flush();
196 EcompUserDetails userDetails = new EcompUserDetails(ecompUser);
197 // Using portal session as credentials is a hack
198 PreAuthenticatedAuthenticationToken authToken = new PreAuthenticatedAuthenticationToken(userDetails,
199 getPortalSessionId(request), userDetails.getAuthorities());
200 SecurityContextHolder.getContext().setAuthentication(authToken);
201 // Pass request back down the filter chain
202 chain.doFilter(request, response);
207 * Generates a page with text only, absolutely no references to any webapp
208 * resources, so this can be served to an unauthenticated user without
209 * triggering a new authentication attempt. The page has a link to the Portal
210 * URL from configuration, with a return URL that is the original request.
213 * Original requested URL
215 * @throws UnsupportedEncodingException
218 private static String generateLoginRedirectPage(String appUrl) throws UnsupportedEncodingException {
219 String encodedAppUrl = URLEncoder.encode(appUrl, "UTF-8");
220 String portalBaseUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL);
221 String redirectUrl = portalBaseUrl + "?" + PortalAuthenticationFilter.REDIRECT_URL_KEY + "=" + encodedAppUrl;
222 String aHref = "<a href=\"" + redirectUrl + "\">";
223 // If only Java had "here" documents.
224 String body = String.join(//
225 System.getProperty("line.separator"), //
228 "<title>RIC Dashboard</title>", //
231 " font-family: Helvetica, Arial, sans-serif;", //
236 "<h2>RIC Dashboard</h2>", //
237 "<h4>Please log in.</h4>", //
239 aHref, "Click here to authenticate at the ONAP Portal</a>", //
247 * Searches the request for a cookie with the specified name.
253 * @return Cookie, or null if not found.
255 private Cookie getCookie(HttpServletRequest request, String cookieName) {
256 Cookie[] cookies = request.getCookies();
258 for (Cookie cookie : cookies)
259 if (cookie.getName().equals(cookieName))
265 * Gets the ECOMP Portal service cookie value.
268 * @return Cookie value, or null if not found.
270 private String getPortalSessionId(HttpServletRequest request) {
271 Cookie ep = getCookie(request, PortalApiConstants.EP_SERVICE);
274 return ep.getValue();