3 * Copyright (C) 2009-2021 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_DEFAULT_VALUE;
38 import static org.sonar.api.CoreProperties.CORE_FORCE_AUTHENTICATION_PROPERTY;
39 import static org.sonar.api.web.ServletFilter.UrlPattern.Builder.staticResourcePatterns;
40 import static org.sonar.server.authentication.AuthenticationError.handleAuthenticationError;
43 public class UserSessionInitializer {
46 * Key of attribute to be used for displaying user login
47 * in logs/access.log. The pattern to be configured
48 * in property sonar.web.accessLogs.pattern is "%reqAttribute{LOGIN}"
50 private static final String ACCESS_LOG_LOGIN = "LOGIN";
52 // SONAR-6546 these urls should be get from WebService
53 private static final Set<String> SKIPPED_URLS = Set.of(
54 "/batch/index", "/batch/file",
55 "/maintenance/*", "/setup/*",
56 "/sessions/*", "/oauth2/callback/*",
57 "/api/system/db_migration_status", "/api/system/status", "/api/system/migrate_db",
58 "/api/server/version",
59 "/api/users/identity_providers", "/api/l10n/index",
60 "/api/authentication/login", "/api/authentication/logout", "/api/authentication/validate",
61 "/api/project_badges/measure", "/api/project_badges/quality_gate");
63 private static final Set<String> URL_USING_PASSCODE = Set.of(
64 "/api/ce/info", "/api/ce/pause",
65 "/api/ce/resume", "/api/system/health",
66 "/api/system/analytics", "/api/system/migrate_es",
67 "/api/system/liveness");
69 private static final UrlPattern URL_PATTERN = UrlPattern.builder()
71 .excludes(staticResourcePatterns())
72 .excludes(SKIPPED_URLS)
75 private static final UrlPattern PASSCODE_URLS = UrlPattern.builder()
76 .includes(URL_USING_PASSCODE)
79 private final Configuration config;
80 private final ThreadLocalUserSession threadLocalSession;
81 private final AuthenticationEvent authenticationEvent;
82 private final RequestAuthenticator requestAuthenticator;
84 public UserSessionInitializer(Configuration config, ThreadLocalUserSession threadLocalSession, AuthenticationEvent authenticationEvent,
85 RequestAuthenticator requestAuthenticator) {
87 this.threadLocalSession = threadLocalSession;
88 this.authenticationEvent = authenticationEvent;
89 this.requestAuthenticator = requestAuthenticator;
92 public boolean initUserSession(HttpServletRequest request, HttpServletResponse response) {
93 String path = request.getRequestURI().replaceFirst(request.getContextPath(), "");
95 // Do not set user session when url is excluded
96 if (URL_PATTERN.matches(path)) {
97 loadUserSession(request, response, PASSCODE_URLS.matches(path));
100 } catch (AuthenticationException e) {
101 authenticationEvent.loginFailure(request, e);
103 response.setStatus(HTTP_UNAUTHORIZED);
106 if (isNotLocalOrJwt(e.getSource())) {
107 // redirect to Unauthorized error page
108 handleAuthenticationError(e, request, response);
111 // Web pages should redirect to the index.html file
116 private static boolean isNotLocalOrJwt(Source source) {
117 AuthenticationEvent.Provider provider = source.getProvider();
118 return provider != AuthenticationEvent.Provider.LOCAL && provider != AuthenticationEvent.Provider.JWT;
121 private void loadUserSession(HttpServletRequest request, HttpServletResponse response, boolean urlSupportsSystemPasscode) {
122 UserSession session = requestAuthenticator.authenticate(request, response);
123 if (!session.isLoggedIn() && !urlSupportsSystemPasscode && config.getBoolean(CORE_FORCE_AUTHENTICATION_PROPERTY).orElse(CORE_FORCE_AUTHENTICATION_DEFAULT_VALUE)) {
124 // authentication is required
125 throw AuthenticationException.newBuilder()
126 .setSource(Source.local(AuthenticationEvent.Method.BASIC))
127 .setMessage("User must be authenticated")
130 threadLocalSession.set(session);
131 request.setAttribute(ACCESS_LOG_LOGIN, defaultString(session.getLogin(), "-"));
134 public void removeUserSession() {
135 threadLocalSession.unload();
138 private static boolean isWsUrl(String path) {
139 return path.startsWith("/batch/") || path.startsWith("/api/");