3 * Copyright (C) 2009-2020 SonarSource SA
4 * mailto:info AT sonarsource DOT com
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 package org.sonar.server.authentication;
22 import com.google.common.collect.ImmutableSet;
24 import javax.servlet.http.HttpServletRequest;
25 import javax.servlet.http.HttpServletResponse;
26 import org.sonar.api.config.Configuration;
27 import org.sonar.api.server.ServerSide;
28 import org.sonar.api.web.ServletFilter.UrlPattern;
29 import org.sonar.server.authentication.event.AuthenticationEvent;
30 import org.sonar.server.authentication.event.AuthenticationEvent.Source;
31 import org.sonar.server.authentication.event.AuthenticationException;
32 import org.sonar.server.user.ThreadLocalUserSession;
33 import org.sonar.server.user.UserSession;
35 import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
36 import static org.apache.commons.lang.StringUtils.defaultString;
37 import static org.sonar.api.CoreProperties.CORE_FORCE_AUTHENTICATION_PROPERTY;
38 import static org.sonar.api.web.ServletFilter.UrlPattern.Builder.staticResourcePatterns;
39 import static org.sonar.server.authentication.AuthenticationError.handleAuthenticationError;
42 public class UserSessionInitializer {
45 * Key of attribute to be used for displaying user login
46 * in logs/access.log. The pattern to be configured
47 * in property sonar.web.accessLogs.pattern is "%reqAttribute{LOGIN}"
49 private static final String ACCESS_LOG_LOGIN = "LOGIN";
51 // SONAR-6546 these urls should be get from WebService
52 private static final Set<String> SKIPPED_URLS = ImmutableSet.of(
53 "/batch/index", "/batch/file",
54 "/maintenance/*", "/setup/*",
55 "/sessions/*", "/oauth2/callback/*",
56 "/api/system/db_migration_status", "/api/system/status", "/api/system/migrate_db",
57 "/api/server/version",
58 "/api/users/identity_providers", "/api/l10n/index",
59 "/api/authentication/login", "/api/authentication/logout", "/api/authentication/validate");
61 private static final Set<String> URL_USING_PASSCODE = ImmutableSet.of(
62 "/api/ce/info", "/api/ce/pause", "/api/ce/resume", "/api/system/health", "/api/system/analytics", "/api/system/migrate_es");
64 private static final UrlPattern URL_PATTERN = UrlPattern.builder()
66 .excludes(staticResourcePatterns())
67 .excludes(SKIPPED_URLS)
70 private static final UrlPattern PASSCODE_URLS = UrlPattern.builder()
71 .includes(URL_USING_PASSCODE)
74 private final Configuration config;
75 private final ThreadLocalUserSession threadLocalSession;
76 private final AuthenticationEvent authenticationEvent;
77 private final RequestAuthenticator requestAuthenticator;
79 public UserSessionInitializer(Configuration config, ThreadLocalUserSession threadLocalSession, AuthenticationEvent authenticationEvent,
80 RequestAuthenticator requestAuthenticator) {
82 this.threadLocalSession = threadLocalSession;
83 this.authenticationEvent = authenticationEvent;
84 this.requestAuthenticator = requestAuthenticator;
87 public boolean initUserSession(HttpServletRequest request, HttpServletResponse response) {
88 String path = request.getRequestURI().replaceFirst(request.getContextPath(), "");
90 // Do not set user session when url is excluded
91 if (URL_PATTERN.matches(path)) {
92 loadUserSession(request, response, PASSCODE_URLS.matches(path));
95 } catch (AuthenticationException e) {
96 authenticationEvent.loginFailure(request, e);
98 response.setStatus(HTTP_UNAUTHORIZED);
101 if (isNotLocalOrJwt(e.getSource())) {
102 // redirect to Unauthorized error page
103 handleAuthenticationError(e, request, response);
106 // Web pages should redirect to the index.html file
111 private static boolean isNotLocalOrJwt(Source source) {
112 AuthenticationEvent.Provider provider = source.getProvider();
113 return provider != AuthenticationEvent.Provider.LOCAL && provider != AuthenticationEvent.Provider.JWT;
116 private void loadUserSession(HttpServletRequest request, HttpServletResponse response, boolean urlSupportsSystemPasscode) {
117 UserSession session = requestAuthenticator.authenticate(request, response);
118 if (!session.isLoggedIn() && !urlSupportsSystemPasscode && config.getBoolean(CORE_FORCE_AUTHENTICATION_PROPERTY).orElse(false)) {
119 // authentication is required
120 throw AuthenticationException.newBuilder()
121 .setSource(Source.local(AuthenticationEvent.Method.BASIC))
122 .setMessage("User must be authenticated")
125 threadLocalSession.set(session);
126 request.setAttribute(ACCESS_LOG_LOGIN, defaultString(session.getLogin(), "-"));
129 public void removeUserSession() {
130 threadLocalSession.unload();
133 private static boolean isWsUrl(String path) {
134 return path.startsWith("/batch/") || path.startsWith("/api/");