-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
JwtHttpHandler.java
188 lines (161 loc) · 6.91 KB
/
JwtHttpHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
/*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.authentication;
import static java.util.Objects.requireNonNull;
import static org.elasticsearch.common.Strings.isNullOrEmpty;
import static org.sonar.server.authentication.CookieUtils.findCookie;
import com.google.common.collect.ImmutableMap;
import io.jsonwebtoken.Claims;
import java.util.Date;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.time.DateUtils;
import org.sonar.api.config.Settings;
import org.sonar.api.platform.Server;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.user.UserDto;
@ServerSide
public class JwtHttpHandler {
private static final String SESSION_TIMEOUT_PROPERTY = "sonar.auth.sessionTimeoutInHours";
private static final int SESSION_TIMEOUT_DEFAULT_VALUE_IN_SECONDS = 3 * 24 * 60 * 60;
private static final String JWT_COOKIE = "JWT-SESSION";
private static final String LAST_REFRESH_TIME_PARAM = "lastRefreshTime";
private static final String CSRF_JWT_PARAM = "xsrfToken";
// Time after which a user will be disconnected
private static final int SESSION_DISCONNECT_IN_SECONDS = 3 * 30 * 24 * 60 * 60;
// This refresh time is used to refresh the session
// The value must be lower than sessionTimeoutInSeconds
private static final int SESSION_REFRESH_IN_SECONDS = 5 * 60;
private final System2 system2;
private final DbClient dbClient;
private final Server server;
private final JwtSerializer jwtSerializer;
// This timeout is used to disconnect the user we he has not browse any page for a while
private final int sessionTimeoutInSeconds;
private final JwtCsrfVerifier jwtCsrfVerifier;
public JwtHttpHandler(System2 system2, DbClient dbClient, Server server, Settings settings, JwtSerializer jwtSerializer, JwtCsrfVerifier jwtCsrfVerifier) {
this.jwtSerializer = jwtSerializer;
this.server = server;
this.dbClient = dbClient;
this.system2 = system2;
this.sessionTimeoutInSeconds = getSessionTimeoutInSeconds(settings);
this.jwtCsrfVerifier = jwtCsrfVerifier;
}
public void generateToken(UserDto user, HttpServletResponse response) {
String csrfState = jwtCsrfVerifier.generateState(response, sessionTimeoutInSeconds);
String token = jwtSerializer.encode(new JwtSerializer.JwtSession(
user.getLogin(),
sessionTimeoutInSeconds,
ImmutableMap.of(
LAST_REFRESH_TIME_PARAM, system2.now(),
CSRF_JWT_PARAM, csrfState)));
response.addCookie(createCookie(JWT_COOKIE, token, sessionTimeoutInSeconds));
}
public Optional<UserDto> validateToken(HttpServletRequest request, HttpServletResponse response) {
Optional<UserDto> userDto = validate(request, response);
if (userDto.isPresent()) {
return userDto;
}
removeToken(response);
return Optional.empty();
}
private Optional<UserDto> validate(HttpServletRequest request, HttpServletResponse response) {
Optional<String> token = getTokenFromCookie(request);
if (!token.isPresent()) {
return Optional.empty();
}
return validateToken(token.get(), request, response);
}
private static Optional<String> getTokenFromCookie(HttpServletRequest request) {
Optional<Cookie> jwtCookie = findCookie(JWT_COOKIE, request);
if (!jwtCookie.isPresent()) {
return Optional.empty();
}
Cookie cookie = jwtCookie.get();
String token = cookie.getValue();
if (isNullOrEmpty(token)) {
return Optional.empty();
}
return Optional.of(token);
}
private Optional<UserDto> validateToken(String tokenEncoded, HttpServletRequest request, HttpServletResponse response) {
Optional<Claims> claims = jwtSerializer.decode(tokenEncoded);
if (!claims.isPresent()) {
return Optional.empty();
}
Date now = new Date(system2.now());
Claims token = claims.get();
if (now.after(DateUtils.addSeconds(token.getIssuedAt(), SESSION_DISCONNECT_IN_SECONDS))) {
return Optional.empty();
}
jwtCsrfVerifier.verifyState(request, (String) token.get(CSRF_JWT_PARAM));
if (now.after(DateUtils.addSeconds(getLastRefreshDate(token), SESSION_REFRESH_IN_SECONDS))) {
refreshToken(token, response);
}
Optional<UserDto> user = selectUserFromDb(token.getSubject());
if (!user.isPresent()) {
return Optional.empty();
}
return Optional.of(user.get());
}
private static Date getLastRefreshDate(Claims token) {
Long lastFreshTime = (Long) token.get(LAST_REFRESH_TIME_PARAM);
requireNonNull(lastFreshTime, "last refresh time is missing in token");
return new Date(lastFreshTime);
}
private void refreshToken(Claims token, HttpServletResponse response) {
String refreshToken = jwtSerializer.refresh(token, sessionTimeoutInSeconds);
response.addCookie(createCookie(JWT_COOKIE, refreshToken, sessionTimeoutInSeconds));
jwtCsrfVerifier.refreshState(response, (String) token.get(CSRF_JWT_PARAM), sessionTimeoutInSeconds);
}
void removeToken(HttpServletResponse response) {
response.addCookie(createCookie(JWT_COOKIE, null, 0));
jwtCsrfVerifier.removeState(response);
}
private Cookie createCookie(String name, @Nullable String value, int expirationInSeconds) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
cookie.setSecure(server.isSecured());
cookie.setHttpOnly(true);
cookie.setMaxAge(expirationInSeconds);
return cookie;
}
private Optional<UserDto> selectUserFromDb(String userLogin) {
DbSession dbSession = dbClient.openSession(false);
try {
return Optional.ofNullable(dbClient.userDao().selectActiveUserByLogin(dbSession, userLogin));
} finally {
dbClient.closeSession(dbSession);
}
}
private static int getSessionTimeoutInSeconds(Settings settings) {
int propertyFromSettings = settings.getInt(SESSION_TIMEOUT_PROPERTY);
if (propertyFromSettings > 0) {
return propertyFromSettings * 60 * 60;
}
return SESSION_TIMEOUT_DEFAULT_VALUE_IN_SECONDS;
}
}