Skip to content

Commit 50cc36d

Browse files
Add support JdbcOneTimeTokenService
Closes gh-15735
1 parent 9ba2435 commit 50cc36d

File tree

6 files changed

+542
-1
lines changed

6 files changed

+542
-1
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* Copyright 2002-2024 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.security.aot.hint;
18+
19+
import org.springframework.aot.hint.RuntimeHints;
20+
import org.springframework.aot.hint.RuntimeHintsRegistrar;
21+
import org.springframework.jdbc.core.JdbcOperations;
22+
import org.springframework.security.authentication.ott.OneTimeToken;
23+
import org.springframework.security.authentication.ott.OneTimeTokenService;
24+
25+
/**
26+
*
27+
* A JDBC implementation of an {@link OneTimeTokenService} that uses a
28+
* {@link JdbcOperations} for {@link OneTimeToken} persistence.
29+
*
30+
* @author Max Batischev
31+
* @since 6.4
32+
*/
33+
class OneTimeTokenRuntimeHints implements RuntimeHintsRegistrar {
34+
35+
@Override
36+
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
37+
hints.resources().registerPattern("org/springframework/security/core/ott/jdbc/one-time-tokens-schema.sql");
38+
}
39+
40+
}
Lines changed: 239 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,239 @@
1+
/*
2+
* Copyright 2002-2024 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.security.authentication.ott;
18+
19+
import java.sql.ResultSet;
20+
import java.sql.SQLException;
21+
import java.sql.Timestamp;
22+
import java.sql.Types;
23+
import java.time.Clock;
24+
import java.time.Instant;
25+
import java.util.ArrayList;
26+
import java.util.List;
27+
import java.util.UUID;
28+
import java.util.function.Function;
29+
30+
import org.apache.commons.logging.Log;
31+
import org.apache.commons.logging.LogFactory;
32+
33+
import org.springframework.jdbc.core.ArgumentPreparedStatementSetter;
34+
import org.springframework.jdbc.core.JdbcOperations;
35+
import org.springframework.jdbc.core.PreparedStatementSetter;
36+
import org.springframework.jdbc.core.RowMapper;
37+
import org.springframework.jdbc.core.SqlParameterValue;
38+
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
39+
import org.springframework.scheduling.support.CronTrigger;
40+
import org.springframework.util.Assert;
41+
import org.springframework.util.CollectionUtils;
42+
import org.springframework.util.StringUtils;
43+
44+
/**
45+
*
46+
* A JDBC implementation of an {@link OneTimeTokenService} that uses a
47+
* {@link JdbcOperations} for {@link OneTimeToken} persistence.
48+
*
49+
* <p>
50+
* <b>NOTE:</b> This {@code JdbcOneTimeTokenService} depends on the table definition
51+
* described in
52+
* "classpath:org/springframework/security/core/ott/jdbc/one-time-tokens-schema.sql" and
53+
* therefore MUST be defined in the database schema.
54+
*
55+
* @author Max Batischev
56+
* @since 6.4
57+
*/
58+
public final class JdbcOneTimeTokenService implements OneTimeTokenService {
59+
60+
private final Log logger = LogFactory.getLog(getClass());
61+
62+
private final JdbcOperations jdbcOperations;
63+
64+
private Function<OneTimeToken, List<SqlParameterValue>> oneTimeTokenParametersMapper = new OneTimeTokenParametersMapper();
65+
66+
private RowMapper<OneTimeToken> oneTimeTokenRowMapper = new OneTimeTokenRowMapper();
67+
68+
private Clock clock = Clock.systemUTC();
69+
70+
private ThreadPoolTaskScheduler taskScheduler;
71+
72+
private static final String DEFAULT_CLEANUP_CRON = "0 * * * * *";
73+
74+
private static final String TABLE_NAME = "one_time_tokens";
75+
76+
// @formatter:off
77+
private static final String COLUMN_NAMES = "token_value, "
78+
+ "username, "
79+
+ "expires_at";
80+
// @formatter:on
81+
82+
// @formatter:off
83+
private static final String SAVE_AUTHORIZED_CLIENT_SQL = "INSERT INTO " + TABLE_NAME
84+
+ " (" + COLUMN_NAMES + ") VALUES (?, ?, ?)";
85+
// @formatter:on
86+
87+
private static final String FILTER = "token_value = ?";
88+
89+
private static final String DELETE_ONE_TIME_TOKEN_SQL = "DELETE FROM " + TABLE_NAME + " WHERE " + FILTER;
90+
91+
// @formatter:off
92+
private static final String SELECT_ONE_TIME_TOKEN_SQL = "SELECT " + COLUMN_NAMES
93+
+ " FROM " + TABLE_NAME
94+
+ " WHERE " + FILTER;
95+
// @formatter:on
96+
97+
// @formatter:off
98+
private static final String DELETE_SESSIONS_BY_EXPIRY_TIME_QUERY = "DELETE FROM "
99+
+ TABLE_NAME
100+
+ " WHERE expires_at < ?";
101+
// @formatter:on
102+
103+
/**
104+
* Constructs a {@code JdbcOneTimeTokenService} using the provide parameters.
105+
* @param jdbcOperations the JDBC operations
106+
* @param cleanupCron cleanup cron expression
107+
*/
108+
public JdbcOneTimeTokenService(JdbcOperations jdbcOperations, String cleanupCron) {
109+
Assert.isTrue(StringUtils.hasText(cleanupCron), "cleanupCron cannot be null orr empty");
110+
Assert.notNull(jdbcOperations, "jdbcOperations cannot be null");
111+
this.jdbcOperations = jdbcOperations;
112+
this.taskScheduler = createTaskScheduler(cleanupCron);
113+
}
114+
115+
/**
116+
* Constructs a {@code JdbcOneTimeTokenService} using the provide parameters.
117+
* @param jdbcOperations the JDBC operations
118+
*/
119+
public JdbcOneTimeTokenService(JdbcOperations jdbcOperations) {
120+
Assert.notNull(jdbcOperations, "jdbcOperations cannot be null");
121+
this.jdbcOperations = jdbcOperations;
122+
this.taskScheduler = createTaskScheduler(DEFAULT_CLEANUP_CRON);
123+
}
124+
125+
@Override
126+
public OneTimeToken generate(GenerateOneTimeTokenRequest request) {
127+
Assert.notNull(request, "generateOneTimeTokenRequest cannot be null");
128+
String token = UUID.randomUUID().toString();
129+
Instant fiveMinutesFromNow = this.clock.instant().plusSeconds(300);
130+
OneTimeToken oneTimeToken = new DefaultOneTimeToken(token, request.getUsername(), fiveMinutesFromNow);
131+
insertOneTimeToken(oneTimeToken);
132+
return oneTimeToken;
133+
}
134+
135+
private void insertOneTimeToken(OneTimeToken oneTimeToken) {
136+
List<SqlParameterValue> parameters = this.oneTimeTokenParametersMapper.apply(oneTimeToken);
137+
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters.toArray());
138+
this.jdbcOperations.update(SAVE_AUTHORIZED_CLIENT_SQL, pss);
139+
}
140+
141+
@Override
142+
public OneTimeToken consume(OneTimeTokenAuthenticationToken authenticationToken) {
143+
Assert.notNull(authenticationToken, "authenticationToken cannot be null");
144+
145+
List<OneTimeToken> tokens = selectOneTimeToken(authenticationToken);
146+
if (CollectionUtils.isEmpty(tokens)) {
147+
return null;
148+
}
149+
OneTimeToken token = tokens.get(0);
150+
deleteOneTimeToken(token);
151+
if (isExpired(token)) {
152+
return null;
153+
}
154+
return token;
155+
}
156+
157+
private boolean isExpired(OneTimeToken ott) {
158+
return this.clock.instant().isAfter(ott.getExpiresAt());
159+
}
160+
161+
private List<OneTimeToken> selectOneTimeToken(OneTimeTokenAuthenticationToken authenticationToken) {
162+
List<SqlParameterValue> parameters = List
163+
.of(new SqlParameterValue(Types.VARCHAR, authenticationToken.getTokenValue()));
164+
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters.toArray());
165+
return this.jdbcOperations.query(SELECT_ONE_TIME_TOKEN_SQL, pss, this.oneTimeTokenRowMapper);
166+
}
167+
168+
private void deleteOneTimeToken(OneTimeToken oneTimeToken) {
169+
List<SqlParameterValue> parameters = List
170+
.of(new SqlParameterValue(Types.VARCHAR, oneTimeToken.getTokenValue()));
171+
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters.toArray());
172+
this.jdbcOperations.update(DELETE_ONE_TIME_TOKEN_SQL, pss);
173+
}
174+
175+
private ThreadPoolTaskScheduler createTaskScheduler(String cleanupCron) {
176+
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
177+
taskScheduler.setThreadNamePrefix("spring-one-time-tokens-");
178+
taskScheduler.initialize();
179+
taskScheduler.schedule(this::cleanUpExpiredTokens, new CronTrigger(cleanupCron));
180+
return taskScheduler;
181+
}
182+
183+
public void cleanUpExpiredTokens() {
184+
List<SqlParameterValue> parameters = List.of(new SqlParameterValue(Types.TIMESTAMP, Instant.now()));
185+
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters.toArray());
186+
int deletedCount = this.jdbcOperations.update(DELETE_SESSIONS_BY_EXPIRY_TIME_QUERY, pss);
187+
this.logger.debug("Cleaned up " + deletedCount + " expired tokens");
188+
}
189+
190+
/**
191+
* Sets the {@link Clock} used when generating one-time token and checking token
192+
* expiry.
193+
* @param clock the clock
194+
*/
195+
public void setClock(Clock clock) {
196+
Assert.notNull(clock, "clock cannot be null");
197+
this.clock = clock;
198+
}
199+
200+
/**
201+
* The default {@code Function} that maps {@link OneTimeToken} to a {@code List} of
202+
* {@link SqlParameterValue}.
203+
*
204+
* @author Max Batischev
205+
* @since 6.4
206+
*/
207+
public static class OneTimeTokenParametersMapper implements Function<OneTimeToken, List<SqlParameterValue>> {
208+
209+
@Override
210+
public List<SqlParameterValue> apply(OneTimeToken oneTimeToken) {
211+
List<SqlParameterValue> parameters = new ArrayList<>();
212+
parameters.add(new SqlParameterValue(Types.VARCHAR, oneTimeToken.getTokenValue()));
213+
parameters.add(new SqlParameterValue(Types.VARCHAR, oneTimeToken.getUsername()));
214+
parameters.add(new SqlParameterValue(Types.TIMESTAMP, Timestamp.from(oneTimeToken.getExpiresAt())));
215+
return parameters;
216+
}
217+
218+
}
219+
220+
/**
221+
* The default {@link RowMapper} that maps the current row in
222+
* {@code java.sql.ResultSet} to {@link OneTimeToken}.
223+
*
224+
* @author Max Batischev
225+
* @since 6.4
226+
*/
227+
public static class OneTimeTokenRowMapper implements RowMapper<OneTimeToken> {
228+
229+
@Override
230+
public OneTimeToken mapRow(ResultSet rs, int rowNum) throws SQLException {
231+
String tokenValue = rs.getString("token_value");
232+
String userName = rs.getString("username");
233+
Instant expiresAt = rs.getTimestamp("expires_at").toInstant();
234+
return new DefaultOneTimeToken(tokenValue, userName, expiresAt);
235+
}
236+
237+
}
238+
239+
}
Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
org.springframework.aot.hint.RuntimeHintsRegistrar=\
2-
org.springframework.security.aot.hint.CoreSecurityRuntimeHints
2+
org.springframework.security.aot.hint.CoreSecurityRuntimeHints,\
3+
org.springframework.security.aot.hint.OneTimeTokenRuntimeHints
4+
35
org.springframework.beans.factory.aot.BeanFactoryInitializationAotProcessor=\
46
org.springframework.security.aot.hint.SecurityHintsAotProcessor
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
create table one_time_tokens(
2+
token_value varchar(36) not null primary key,
3+
username varchar_ignorecase(50) not null,
4+
expires_at timestamp not null
5+
);
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
* Copyright 2002-2024 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.security.aot.hint;
18+
19+
import java.util.stream.Stream;
20+
21+
import org.junit.jupiter.api.BeforeEach;
22+
import org.junit.jupiter.params.ParameterizedTest;
23+
import org.junit.jupiter.params.provider.MethodSource;
24+
25+
import org.springframework.aot.hint.RuntimeHints;
26+
import org.springframework.aot.hint.RuntimeHintsRegistrar;
27+
import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
28+
import org.springframework.core.io.support.SpringFactoriesLoader;
29+
import org.springframework.util.ClassUtils;
30+
31+
import static org.assertj.core.api.Assertions.assertThat;
32+
33+
/**
34+
* Tests for {@link OneTimeTokenRuntimeHints}
35+
*
36+
* @author Max Batischev
37+
*/
38+
class OneTimeTokenRuntimeHintsTests {
39+
40+
private final RuntimeHints hints = new RuntimeHints();
41+
42+
@BeforeEach
43+
void setup() {
44+
SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories")
45+
.load(RuntimeHintsRegistrar.class)
46+
.forEach((registrar) -> registrar.registerHints(this.hints, ClassUtils.getDefaultClassLoader()));
47+
}
48+
49+
@ParameterizedTest
50+
@MethodSource("getOneTimeTokensSqlFiles")
51+
void oneTimeTokensSqlFilesHasHints(String schemaFile) {
52+
assertThat(RuntimeHintsPredicates.resource().forResource(schemaFile)).accepts(this.hints);
53+
}
54+
55+
private static Stream<String> getOneTimeTokensSqlFiles() {
56+
return Stream.of("org/springframework/security/core/ott/jdbc/one-time-tokens-schema.sql");
57+
}
58+
59+
}

0 commit comments

Comments
 (0)