3 * Copyright (C) 2009-2024 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.base.Splitter;
23 import java.util.Collections;
24 import java.util.Date;
25 import java.util.EnumSet;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.Locale;
30 import java.util.Optional;
31 import javax.annotation.CheckForNull;
32 import org.sonar.api.Startable;
33 import org.sonar.api.config.Configuration;
34 import org.sonar.api.server.authentication.Display;
35 import org.sonar.api.server.authentication.IdentityProvider;
36 import org.sonar.api.server.authentication.UserIdentity;
37 import org.sonar.api.server.http.HttpRequest;
38 import org.sonar.api.server.http.HttpResponse;
39 import org.sonar.api.utils.System2;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.sonar.db.user.UserDto;
43 import org.sonar.process.ProcessProperties;
44 import org.sonar.server.authentication.event.AuthenticationEvent;
45 import org.sonar.server.authentication.event.AuthenticationEvent.Source;
46 import org.sonar.server.authentication.event.AuthenticationException;
47 import org.sonar.server.exceptions.BadRequestException;
49 import static org.apache.commons.lang.time.DateUtils.addMinutes;
50 import static org.sonar.process.ProcessProperties.Property.SONAR_WEB_SSO_EMAIL_HEADER;
51 import static org.sonar.process.ProcessProperties.Property.SONAR_WEB_SSO_ENABLE;
52 import static org.sonar.process.ProcessProperties.Property.SONAR_WEB_SSO_GROUPS_HEADER;
53 import static org.sonar.process.ProcessProperties.Property.SONAR_WEB_SSO_LOGIN_HEADER;
54 import static org.sonar.process.ProcessProperties.Property.SONAR_WEB_SSO_NAME_HEADER;
55 import static org.sonar.process.ProcessProperties.Property.SONAR_WEB_SSO_REFRESH_INTERVAL_IN_MINUTES;
56 import static org.sonar.server.user.ExternalIdentity.SQ_AUTHORITY;
59 * Authentication based on the HTTP request headers. The front proxy
60 * is responsible for validating user identity.
62 public class HttpHeadersAuthentication implements Startable {
64 private static final Logger LOG = LoggerFactory.getLogger(HttpHeadersAuthentication.class);
66 private static final Splitter COMA_SPLITTER = Splitter.on(",").trimResults().omitEmptyStrings();
68 private static final String LAST_REFRESH_TIME_TOKEN_PARAM = "ssoLastRefreshTime";
70 private static final EnumSet<ProcessProperties.Property> PROPERTIES = EnumSet.of(
71 SONAR_WEB_SSO_LOGIN_HEADER,
72 SONAR_WEB_SSO_NAME_HEADER,
73 SONAR_WEB_SSO_EMAIL_HEADER,
74 SONAR_WEB_SSO_GROUPS_HEADER,
75 SONAR_WEB_SSO_REFRESH_INTERVAL_IN_MINUTES);
77 private final System2 system2;
78 private final Configuration config;
79 private final UserRegistrar userRegistrar;
80 private final JwtHttpHandler jwtHttpHandler;
81 private final AuthenticationEvent authenticationEvent;
82 private final Map<String, String> settingsByKey = new HashMap<>();
84 private boolean enabled = false;
86 public HttpHeadersAuthentication(System2 system2, Configuration config, UserRegistrar userRegistrar,
87 JwtHttpHandler jwtHttpHandler, AuthenticationEvent authenticationEvent) {
88 this.system2 = system2;
90 this.userRegistrar = userRegistrar;
91 this.jwtHttpHandler = jwtHttpHandler;
92 this.authenticationEvent = authenticationEvent;
97 if (config.getBoolean(SONAR_WEB_SSO_ENABLE.getKey()).orElse(false)) {
98 LOG.info("HTTP headers authentication enabled");
100 PROPERTIES.forEach(entry -> settingsByKey.put(entry.getKey(), config.get(entry.getKey()).orElse(entry.getDefaultValue())));
109 public Optional<UserDto> authenticate(HttpRequest request, HttpResponse response) {
111 return doAuthenticate(request, response);
112 } catch (BadRequestException e) {
113 throw AuthenticationException.newBuilder()
114 .setSource(Source.sso())
115 .setMessage(e.getMessage())
120 private Optional<UserDto> doAuthenticate(HttpRequest request, HttpResponse response) {
122 return Optional.empty();
124 Map<String, String> headerValuesByNames = getHeaders(request);
125 String login = getHeaderValue(headerValuesByNames, SONAR_WEB_SSO_LOGIN_HEADER.getKey());
127 return Optional.empty();
129 Optional<UserDto> user = getUserFromToken(request, response);
130 if (user.isPresent() && login.equals(user.get().getLogin())) {
134 UserDto userDto = doAuthenticate(headerValuesByNames, login);
135 jwtHttpHandler.generateToken(userDto, Map.of(LAST_REFRESH_TIME_TOKEN_PARAM, system2.now()), request, response);
136 authenticationEvent.loginSuccess(request, userDto.getLogin(), Source.sso());
137 return Optional.of(userDto);
140 private Optional<UserDto> getUserFromToken(HttpRequest request, HttpResponse response) {
141 Optional<JwtHttpHandler.Token> token = jwtHttpHandler.getToken(request, response);
142 if (token.isEmpty()) {
143 return Optional.empty();
145 Date now = new Date(system2.now());
146 int refreshIntervalInMinutes = Integer.parseInt(settingsByKey.get(SONAR_WEB_SSO_REFRESH_INTERVAL_IN_MINUTES.getKey()));
147 Long lastFreshTime = (Long) token.get().getProperties().get(LAST_REFRESH_TIME_TOKEN_PARAM);
148 if (lastFreshTime == null || now.after(addMinutes(new Date(lastFreshTime), refreshIntervalInMinutes))) {
149 return Optional.empty();
151 return Optional.of(token.get().getUserDto());
154 private UserDto doAuthenticate(Map<String, String> headerValuesByNames, String login) {
155 String name = getHeaderValue(headerValuesByNames, SONAR_WEB_SSO_NAME_HEADER.getKey());
156 String email = getHeaderValue(headerValuesByNames, SONAR_WEB_SSO_EMAIL_HEADER.getKey());
157 UserIdentity.Builder userIdentityBuilder = UserIdentity.builder()
158 .setName(name == null ? login : name)
160 .setProviderLogin(login);
161 if (hasHeader(headerValuesByNames, SONAR_WEB_SSO_GROUPS_HEADER.getKey())) {
162 String groupsValue = getHeaderValue(headerValuesByNames, SONAR_WEB_SSO_GROUPS_HEADER.getKey());
163 userIdentityBuilder.setGroups(groupsValue == null ? Collections.emptySet() : new HashSet<>(COMA_SPLITTER.splitToList(groupsValue)));
165 return userRegistrar.register(
166 UserRegistration.builder()
167 .setUserIdentity(userIdentityBuilder.build())
168 .setProvider(new SsoIdentityProvider())
169 .setSource(Source.sso())
174 private String getHeaderValue(Map<String, String> headerValuesByNames, String settingKey) {
175 return headerValuesByNames.get(settingsByKey.get(settingKey).toLowerCase(Locale.ENGLISH));
178 private static Map<String, String> getHeaders(HttpRequest request) {
179 Map<String, String> headers = new HashMap<>();
180 Collections.list(request.getHeaderNames()).forEach(header -> headers.put(header.toLowerCase(Locale.ENGLISH), request.getHeader(header)));
184 private boolean hasHeader(Map<String, String> headerValuesByNames, String settingKey) {
185 return headerValuesByNames.containsKey(settingsByKey.get(settingKey).toLowerCase(Locale.ENGLISH));
188 private static class SsoIdentityProvider implements IdentityProvider {
190 public String getKey() {
195 public String getName() {
200 public Display getDisplay() {
205 public boolean isEnabled() {
210 public boolean allowsUsersToSignUp() {