X-Git-Url: https://gerrit.o-ran-sc.org/r/gitweb?a=blobdiff_plain;f=dashboard%2Fwebapp-backend%2Fsrc%2Fmain%2Fjava%2Forg%2Foransc%2Fric%2Fportal%2Fdashboard%2Fportalapi%2FPortalAuthenticationFilter.java;h=711761a4b73750481d12d55db57891b58615f674;hb=592ce20ec359928373de2e7f06214c8f8ad73c20;hp=4b6de91449711ce45a4d2116e64393243ff5b8c7;hpb=7a4a590fb0ebf8772169625cdda327da43c79c6d;p=nonrtric.git diff --git a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/PortalAuthenticationFilter.java b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/PortalAuthenticationFilter.java index 4b6de914..711761a4 100644 --- a/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/PortalAuthenticationFilter.java +++ b/dashboard/webapp-backend/src/main/java/org/oransc/ric/portal/dashboard/portalapi/PortalAuthenticationFilter.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -71,211 +71,211 @@ import org.springframework.security.web.authentication.preauth.PreAuthenticatedA * Portal knows where to forward the request to once the Portal Session is * created and EPService cookie is set. * - * + * * TODO: What about sessions? Will this be stateless? - * + * * This filter uses no annotations to avoid Spring's automatic registration, * which add this filter in the chain in the wrong order. */ public class PortalAuthenticationFilter implements Filter { - private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); + private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); - // Unfortunately not all file names are defined as constants - private static final String[] securityPropertyFiles = { KeyProperties.PROPERTY_FILE_NAME, - PortalApiProperties.PROPERTY_FILE_NAME, DefaultSecurityConfiguration.DEFAULT_RESOURCE_FILE, - "validation.properties" }; + // Unfortunately not all file names are defined as constants + private static final String[] securityPropertyFiles = + {KeyProperties.PROPERTY_FILE_NAME, PortalApiProperties.PROPERTY_FILE_NAME, + DefaultSecurityConfiguration.DEFAULT_RESOURCE_FILE, "validation.properties"}; - public static final String REDIRECT_URL_KEY = "redirectUrl"; + public static final String REDIRECT_URL_KEY = "redirectUrl"; - private final boolean enforcePortalSecurity; - private final PortalAuthManager authManager; + private final boolean enforcePortalSecurity; + private final PortalAuthManager authManager; - private final DashboardUserManager userManager; + private final DashboardUserManager userManager; - public PortalAuthenticationFilter(boolean portalSecurity, PortalAuthManager authManager, - DashboardUserManager userManager) { - this.enforcePortalSecurity = portalSecurity; - this.authManager = authManager; - this.userManager = userManager; - if (portalSecurity) { - // Throw if security is requested and prerequisites are not met - for (String pf : securityPropertyFiles) { - InputStream in = MethodHandles.lookup().lookupClass().getClassLoader().getResourceAsStream(pf); - if (in == null) { - String msg = "Failed to find property file on classpath: " + pf; - logger.error(msg); - throw new RuntimeException(msg); - } else { - try { - in.close(); - } catch (IOException ex) { - logger.warn("Failed to close stream", ex); - } - } - } - } - } + public PortalAuthenticationFilter(boolean portalSecurity, PortalAuthManager authManager, + DashboardUserManager userManager) { + this.enforcePortalSecurity = portalSecurity; + this.authManager = authManager; + this.userManager = userManager; + if (portalSecurity) { + // Throw if security is requested and prerequisites are not met + for (String pf : securityPropertyFiles) { + InputStream in = MethodHandles.lookup().lookupClass().getClassLoader().getResourceAsStream(pf); + if (in == null) { + String msg = "Failed to find property file on classpath: " + pf; + logger.error(msg); + throw new RuntimeException(msg); + } else { + try { + in.close(); + } catch (IOException ex) { + logger.warn("Failed to close stream", ex); + } + } + } + } + } - @Override - public void init(FilterConfig filterConfig) throws ServletException { - // complain loudly if this key property is missing - String url = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL); - logger.debug("init: Portal redirect URL {}", url); - if (url == null) - logger.error( - "init: Failed to find property in portal.properties: " + PortalApiConstants.ECOMP_REDIRECT_URL); - } + @Override + public void init(FilterConfig filterConfig) throws ServletException { + // complain loudly if this key property is missing + String url = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL); + logger.debug("init: Portal redirect URL {}", url); + if (url == null) + logger + .error("init: Failed to find property in portal.properties: " + PortalApiConstants.ECOMP_REDIRECT_URL); + } - @Override - public void destroy() { - // No resources to release - } + @Override + public void destroy() { + // No resources to release + } - /** - * Requests for pages ignored in the web security config do not hit this filter. - */ - @Override - public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) - throws IOException, ServletException { - if (enforcePortalSecurity) - doFilterEPSDKFW(req, res, chain); - else - doFilterMockUserAdminRole(req, res, chain); - } + /** + * Requests for pages ignored in the web security config do not hit this filter. + */ + @Override + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) + throws IOException, ServletException { + if (enforcePortalSecurity) + doFilterEPSDKFW(req, res, chain); + else + doFilterMockUserAdminRole(req, res, chain); + } - /* - * Populates security context with a mock user in the admin role. - * - */ - private void doFilterMockUserAdminRole(ServletRequest req, ServletResponse res, FilterChain chain) - throws IOException, ServletException { - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - if (auth == null || auth.getAuthorities().isEmpty()) { - if (logger.isDebugEnabled()) { - logger.debug("doFilter adding auth to request URI {}", - (req instanceof HttpServletRequest) ? ((HttpServletRequest) req).getRequestURL() : req); - } - EcompRole admin = new EcompRole(); - admin.setId(1L); - admin.setName(DashboardConstants.ROLE_ADMIN); - HashSet roles = new HashSet<>(); - roles.add(admin); - EcompUser user = new EcompUser(); - user.setLoginId("fakeLoginId"); - user.setRoles(roles); - user.setActive(true); - EcompUserDetails userDetails = new EcompUserDetails(user); - PreAuthenticatedAuthenticationToken authToken = new PreAuthenticatedAuthenticationToken(userDetails, - "fakeCredentials", userDetails.getAuthorities()); - SecurityContextHolder.getContext().setAuthentication(authToken); - } else { - logger.debug("doFilter: authorities {}", auth.getAuthorities()); - } - chain.doFilter(req, res); - } + /* + * Populates security context with a mock user in the admin role. + * + */ + private void doFilterMockUserAdminRole(ServletRequest req, ServletResponse res, FilterChain chain) + throws IOException, ServletException { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth == null || auth.getAuthorities().isEmpty()) { + if (logger.isDebugEnabled()) { + logger.debug("doFilter adding auth to request URI {}", + (req instanceof HttpServletRequest) ? ((HttpServletRequest) req).getRequestURL() : req); + } + EcompRole admin = new EcompRole(); + admin.setId(1L); + admin.setName(DashboardConstants.ROLE_ADMIN); + HashSet roles = new HashSet<>(); + roles.add(admin); + EcompUser user = new EcompUser(); + user.setLoginId("fakeLoginId"); + user.setRoles(roles); + user.setActive(true); + EcompUserDetails userDetails = new EcompUserDetails(user); + PreAuthenticatedAuthenticationToken authToken = + new PreAuthenticatedAuthenticationToken(userDetails, "fakeCredentials", userDetails.getAuthorities()); + SecurityContextHolder.getContext().setAuthentication(authToken); + } else { + logger.debug("doFilter: authorities {}", auth.getAuthorities()); + } + chain.doFilter(req, res); + } - /* - * Checks for valid cookies and allows request to be served if found; redirects - * to Portal otherwise. - */ - private void doFilterEPSDKFW(ServletRequest req, ServletResponse res, FilterChain chain) - throws IOException, ServletException { - HttpServletRequest request = (HttpServletRequest) req; - HttpServletResponse response = (HttpServletResponse) res; - if (logger.isTraceEnabled()) - logger.trace("doFilter: req {}", request.getRequestURI()); - // Need to authenticate the request - final String userId = authManager.validateEcompSso(request); - final EcompUser ecompUser = (userId == null ? null : userManager.getUser(userId)); - if (userId == null || ecompUser == null) { - logger.debug("doFilter: unauthorized user requests URI {}, serving login page", request.getRequestURI()); - StringBuffer sb = request.getRequestURL(); - sb.append(request.getQueryString() == null ? "" : "?" + request.getQueryString()); - String body = generateLoginRedirectPage(sb.toString()); - response.setContentType(MediaType.TEXT_HTML_VALUE); - response.getWriter().print(body); - response.getWriter().flush(); - } else { - EcompUserDetails userDetails = new EcompUserDetails(ecompUser); - // Using portal session as credentials is a hack - PreAuthenticatedAuthenticationToken authToken = new PreAuthenticatedAuthenticationToken(userDetails, - getPortalSessionId(request), userDetails.getAuthorities()); - SecurityContextHolder.getContext().setAuthentication(authToken); - // Pass request back down the filter chain - chain.doFilter(request, response); - } - } + /* + * Checks for valid cookies and allows request to be served if found; redirects + * to Portal otherwise. + */ + private void doFilterEPSDKFW(ServletRequest req, ServletResponse res, FilterChain chain) + throws IOException, ServletException { + HttpServletRequest request = (HttpServletRequest) req; + HttpServletResponse response = (HttpServletResponse) res; + if (logger.isTraceEnabled()) + logger.trace("doFilter: req {}", request.getRequestURI()); + // Need to authenticate the request + final String userId = authManager.validateEcompSso(request); + final EcompUser ecompUser = (userId == null ? null : userManager.getUser(userId)); + if (userId == null || ecompUser == null) { + logger.debug("doFilter: unauthorized user requests URI {}, serving login page", request.getRequestURI()); + StringBuffer sb = request.getRequestURL(); + sb.append(request.getQueryString() == null ? "" : "?" + request.getQueryString()); + String body = generateLoginRedirectPage(sb.toString()); + response.setContentType(MediaType.TEXT_HTML_VALUE); + response.getWriter().print(body); + response.getWriter().flush(); + } else { + EcompUserDetails userDetails = new EcompUserDetails(ecompUser); + // Using portal session as credentials is a hack + PreAuthenticatedAuthenticationToken authToken = new PreAuthenticatedAuthenticationToken(userDetails, + getPortalSessionId(request), userDetails.getAuthorities()); + SecurityContextHolder.getContext().setAuthentication(authToken); + // Pass request back down the filter chain + chain.doFilter(request, response); + } + } - /** - * Generates a page with text only, absolutely no references to any webapp - * resources, so this can be served to an unauthenticated user without - * triggering a new authentication attempt. The page has a link to the Portal - * URL from configuration, with a return URL that is the original request. - * - * @param appUrl - * Original requested URL - * @return HTML - * @throws UnsupportedEncodingException - * On error - */ - private static String generateLoginRedirectPage(String appUrl) throws UnsupportedEncodingException { - String encodedAppUrl = URLEncoder.encode(appUrl, "UTF-8"); - String portalBaseUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL); - String redirectUrl = portalBaseUrl + "?" + PortalAuthenticationFilter.REDIRECT_URL_KEY + "=" + encodedAppUrl; - String aHref = ""; - // If only Java had "here" documents. - String body = String.join(// - System.getProperty("line.separator"), // - "", // - "", // - "RIC Dashboard", // - "", // - "", // - "", // - "

RIC Dashboard

", // - "

Please log in.

", // - "

", // - aHref, "Click here to authenticate at the ONAP Portal", // - "

", // - "", // - ""); - return body; - } + /** + * Generates a page with text only, absolutely no references to any webapp + * resources, so this can be served to an unauthenticated user without + * triggering a new authentication attempt. The page has a link to the Portal + * URL from configuration, with a return URL that is the original request. + * + * @param appUrl + * Original requested URL + * @return HTML + * @throws UnsupportedEncodingException + * On error + */ + private static String generateLoginRedirectPage(String appUrl) throws UnsupportedEncodingException { + String encodedAppUrl = URLEncoder.encode(appUrl, "UTF-8"); + String portalBaseUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL); + String redirectUrl = portalBaseUrl + "?" + PortalAuthenticationFilter.REDIRECT_URL_KEY + "=" + encodedAppUrl; + String aHref = ""; + // If only Java had "here" documents. + String body = String.join(// + System.getProperty("line.separator"), // + "", // + "", // + "RIC Dashboard", // + "", // + "", // + "", // + "

RIC Dashboard

", // + "

Please log in.

", // + "

", // + aHref, "Click here to authenticate at the ONAP Portal", // + "

", // + "", // + ""); + return body; + } - /** - * Searches the request for a cookie with the specified name. - * - * @param request - * HttpServletRequest - * @param cookieName - * Cookie name - * @return Cookie, or null if not found. - */ - private Cookie getCookie(HttpServletRequest request, String cookieName) { - Cookie[] cookies = request.getCookies(); - if (cookies != null) - for (Cookie cookie : cookies) - if (cookie.getName().equals(cookieName)) - return cookie; - return null; - } + /** + * Searches the request for a cookie with the specified name. + * + * @param request + * HttpServletRequest + * @param cookieName + * Cookie name + * @return Cookie, or null if not found. + */ + private Cookie getCookie(HttpServletRequest request, String cookieName) { + Cookie[] cookies = request.getCookies(); + if (cookies != null) + for (Cookie cookie : cookies) + if (cookie.getName().equals(cookieName)) + return cookie; + return null; + } - /** - * Gets the ECOMP Portal service cookie value. - * - * @param request - * @return Cookie value, or null if not found. - */ - private String getPortalSessionId(HttpServletRequest request) { - Cookie ep = getCookie(request, PortalApiConstants.EP_SERVICE); - if (ep == null) - return null; - return ep.getValue(); - } + /** + * Gets the ECOMP Portal service cookie value. + * + * @param request + * @return Cookie value, or null if not found. + */ + private String getPortalSessionId(HttpServletRequest request) { + Cookie ep = getCookie(request, PortalApiConstants.EP_SERVICE); + if (ep == null) + return null; + return ep.getValue(); + } }