|
| 1 | +/* |
| 2 | + * This Source Code Form is subject to the terms of the Mozilla Public License, |
| 3 | + * v. 2.0. If a copy of the MPL was not distributed with this file, You can |
| 4 | + * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under |
| 5 | + * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. |
| 6 | + * |
| 7 | + * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS |
| 8 | + * graphic logo is a trademark of OpenMRS Inc. |
| 9 | + */ |
| 10 | +package org.openmrs.module.smartonfhir.web.filter; |
| 11 | + |
| 12 | +import javax.servlet.Filter; |
| 13 | +import javax.servlet.FilterChain; |
| 14 | +import javax.servlet.FilterConfig; |
| 15 | +import javax.servlet.ServletException; |
| 16 | +import javax.servlet.ServletRequest; |
| 17 | +import javax.servlet.ServletResponse; |
| 18 | +import javax.servlet.http.HttpServletRequest; |
| 19 | +import javax.servlet.http.HttpServletResponse; |
| 20 | +import javax.servlet.http.HttpSession; |
| 21 | + |
| 22 | +import java.io.File; |
| 23 | +import java.io.IOException; |
| 24 | +import java.io.InputStream; |
| 25 | +import java.util.ArrayList; |
| 26 | +import java.util.Arrays; |
| 27 | +import java.util.List; |
| 28 | +import java.util.regex.Matcher; |
| 29 | +import java.util.regex.Pattern; |
| 30 | +import java.util.stream.Collectors; |
| 31 | + |
| 32 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 33 | +import lombok.extern.slf4j.Slf4j; |
| 34 | +import org.apache.commons.lang.StringUtils; |
| 35 | +import org.keycloak.common.util.Base64; |
| 36 | +import org.keycloak.jose.jws.JWSInput; |
| 37 | +import org.keycloak.jose.jws.JWSInputException; |
| 38 | +import org.keycloak.jose.jws.crypto.HMACProvider; |
| 39 | +import org.keycloak.representations.JsonWebToken; |
| 40 | +import org.openmrs.api.context.Context; |
| 41 | +import org.openmrs.api.context.ContextAuthenticationException; |
| 42 | +import org.openmrs.module.smartonfhir.web.SmartSecretKey; |
| 43 | +import org.openmrs.module.smartonfhir.web.smart.SmartTokenCredentials; |
| 44 | +import org.openmrs.util.OpenmrsUtil; |
| 45 | +import org.springframework.core.io.Resource; |
| 46 | +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; |
| 47 | + |
| 48 | +@Slf4j |
| 49 | +public class AuthenticationByPassFilter implements Filter { |
| 50 | + |
| 51 | + public static final String SMART_AUTH_BYPASS = "SMART_AUTH_BYPASS"; |
| 52 | + |
| 53 | + private static final String VALID_URLS_PARAM = "validUrls"; |
| 54 | + |
| 55 | + private static final Pattern KEY_PARAM = Pattern.compile("^key=([^&]*)(?:&|$)"); |
| 56 | + |
| 57 | + private static final ObjectMapper objectMapper = new ObjectMapper(); |
| 58 | + |
| 59 | + private SmartSecretKey smartSecretKey; |
| 60 | + |
| 61 | + private List<String> validUrls = new ArrayList<>(0); |
| 62 | + |
| 63 | + @Override |
| 64 | + public void init(FilterConfig filterConfig) { |
| 65 | + String validUrlsParam = filterConfig.getInitParameter(VALID_URLS_PARAM); |
| 66 | + if (StringUtils.isNotBlank(validUrlsParam)) { |
| 67 | + validUrls = Arrays.stream(validUrlsParam.split(",")).filter(org.apache.commons.lang3.StringUtils::isNotBlank) |
| 68 | + .map(it -> { |
| 69 | + if (it.startsWith("/") || it.equals("*")) { |
| 70 | + return it; |
| 71 | + } |
| 72 | + |
| 73 | + return "/" + it; |
| 74 | + }).distinct().collect(Collectors.toList()); |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + @Override |
| 79 | + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) |
| 80 | + throws IOException, ServletException { |
| 81 | + HttpServletRequest request = (HttpServletRequest) servletRequest; |
| 82 | + HttpServletResponse response = (HttpServletResponse) servletResponse; |
| 83 | + |
| 84 | + if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) { |
| 85 | + Context.logout(); |
| 86 | + } |
| 87 | + |
| 88 | + String pathInfo = request.getRequestURI(); |
| 89 | + |
| 90 | + boolean isValidRequest = false; |
| 91 | + if (pathInfo != null) { |
| 92 | + final String thePathInfo = pathInfo.replaceFirst(request.getContextPath(), ""); |
| 93 | + isValidRequest = validUrls.stream().anyMatch(url -> { |
| 94 | + if (url.endsWith("*")) { |
| 95 | + if (url.length() < 3) { |
| 96 | + return true; |
| 97 | + } else { |
| 98 | + String urlStart = url.substring(0, url.length() - 2); |
| 99 | + return thePathInfo.startsWith(urlStart); |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + return url.equals(thePathInfo); |
| 104 | + }); |
| 105 | + } |
| 106 | + |
| 107 | + if (!isValidRequest) { |
| 108 | + HttpSession session = request.getSession(false); |
| 109 | + if (session != null && session.getAttribute(SMART_AUTH_BYPASS) != null) { |
| 110 | + session.invalidate(); |
| 111 | + Context.logout(); |
| 112 | + request.getSession(); |
| 113 | + } |
| 114 | + |
| 115 | + filterChain.doFilter(request, response); |
| 116 | + return; |
| 117 | + } |
| 118 | + |
| 119 | + if (!Context.isAuthenticated()) { |
| 120 | + final String tokenParam = request.getParameter("token"); |
| 121 | + |
| 122 | + if (tokenParam != null) { |
| 123 | + int keyPos = tokenParam.indexOf("key="); |
| 124 | + if (keyPos >= 0) { |
| 125 | + Matcher m = KEY_PARAM.matcher(tokenParam.substring(keyPos)); |
| 126 | + if (m.find()) { |
| 127 | + final String key = m.group(1); |
| 128 | + |
| 129 | + final String userToken; |
| 130 | + try { |
| 131 | + JWSInput jwsInput = new JWSInput(key); |
| 132 | + JsonWebToken webToken = jwsInput.readJsonContent(JsonWebToken.class); |
| 133 | + |
| 134 | + if (!webToken.isActive()) { |
| 135 | + log.error("Token has expired"); |
| 136 | + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not authenticated"); |
| 137 | + return; |
| 138 | + } |
| 139 | + |
| 140 | + userToken = (String) webToken.getOtherClaims().get("user"); |
| 141 | + } |
| 142 | + catch (JWSInputException e) { |
| 143 | + log.error("Error while reading JWS token", e); |
| 144 | + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not authenticated"); |
| 145 | + return; |
| 146 | + } |
| 147 | + |
| 148 | + if (userToken == null) { |
| 149 | + log.error("Could not read user entry from token"); |
| 150 | + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not authenticated"); |
| 151 | + return; |
| 152 | + } |
| 153 | + |
| 154 | + final String username; |
| 155 | + try { |
| 156 | + JWSInput jwsInput = new JWSInput(userToken); |
| 157 | + if (!HMACProvider.verify(jwsInput, Base64.decode(getSecretKey()))) { |
| 158 | + log.error("Error validating user token"); |
| 159 | + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not authenticated"); |
| 160 | + return; |
| 161 | + } |
| 162 | + |
| 163 | + JsonWebToken webToken = jwsInput.readJsonContent(JsonWebToken.class); |
| 164 | + username = webToken.getSubject(); |
| 165 | + } |
| 166 | + catch (JWSInputException e) { |
| 167 | + log.error("Error while reading user token", e); |
| 168 | + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not authenticated"); |
| 169 | + return; |
| 170 | + } |
| 171 | + |
| 172 | + try { |
| 173 | + Context.authenticate(new SmartTokenCredentials(username)); |
| 174 | + Context.getUserContext().setLocation(Context.getLocationService().getDefaultLocation()); |
| 175 | + request.getSession().setAttribute(SMART_AUTH_BYPASS, true); |
| 176 | + } |
| 177 | + catch (ContextAuthenticationException e) { |
| 178 | + log.error("Error while logging in as user {}", username, e); |
| 179 | + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Not authenticated"); |
| 180 | + return; |
| 181 | + } |
| 182 | + } |
| 183 | + } |
| 184 | + } |
| 185 | + } |
| 186 | + |
| 187 | + filterChain.doFilter(request, response); |
| 188 | + } |
| 189 | + |
| 190 | + private String getSecretKey() throws IOException { |
| 191 | + final PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); |
| 192 | + Resource resource = resolver.getResource( |
| 193 | + OpenmrsUtil.getDirectoryInApplicationDataDirectory("config") + File.separator + "smart-secret-key.json"); |
| 194 | + if (resource != null) { |
| 195 | + resource = resolver.getResource("classpath:smart-secret-key.json"); |
| 196 | + |
| 197 | + InputStream secretKeyStream = resource.getInputStream(); |
| 198 | + |
| 199 | + smartSecretKey = new SmartSecretKey(); |
| 200 | + smartSecretKey = objectMapper.readValue(secretKeyStream, SmartSecretKey.class); |
| 201 | + } |
| 202 | + |
| 203 | + return smartSecretKey.getSmartSharedSecretKey(); |
| 204 | + } |
| 205 | + |
| 206 | + @Override |
| 207 | + public void destroy() { |
| 208 | + } |
| 209 | +} |
0 commit comments