This repository has been archived by the owner on May 31, 2022. It is now read-only.
/
JdbcClientDetailsService.java
341 lines (281 loc) · 12.3 KB
/
JdbcClientDetailsService.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/*
* Copyright 2008 Web Cohesion
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.provider.client;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.common.util.DefaultJdbcListFactory;
import org.springframework.security.oauth2.common.util.JdbcListFactory;
import org.springframework.security.oauth2.provider.ClientAlreadyExistsException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationService;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
* Basic, JDBC implementation of the client details service.
*/
public class JdbcClientDetailsService implements ClientDetailsService, ClientRegistrationService {
private static final Log logger = LogFactory.getLog(JdbcClientDetailsService.class);
private JsonMapper mapper = createJsonMapper();
private static final String CLIENT_FIELDS_FOR_UPDATE = "resource_ids, scope, "
+ "authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, "
+ "refresh_token_validity, additional_information, autoapprove";
private static final String CLIENT_FIELDS = "client_secret, " + CLIENT_FIELDS_FOR_UPDATE;
private static final String BASE_FIND_STATEMENT = "select client_id, " + CLIENT_FIELDS
+ " from oauth_client_details";
private static final String DEFAULT_FIND_STATEMENT = BASE_FIND_STATEMENT + " order by client_id";
private static final String DEFAULT_SELECT_STATEMENT = BASE_FIND_STATEMENT + " where client_id = ?";
private static final String DEFAULT_INSERT_STATEMENT = "insert into oauth_client_details (" + CLIENT_FIELDS
+ ", client_id) values (?,?,?,?,?,?,?,?,?,?,?)";
private static final String DEFAULT_UPDATE_STATEMENT = "update oauth_client_details " + "set "
+ CLIENT_FIELDS_FOR_UPDATE.replaceAll(", ", "=?, ") + "=? where client_id = ?";
private static final String DEFAULT_UPDATE_SECRET_STATEMENT = "update oauth_client_details "
+ "set client_secret = ? where client_id = ?";
private static final String DEFAULT_DELETE_STATEMENT = "delete from oauth_client_details where client_id = ?";
private RowMapper<ClientDetails> rowMapper = new ClientDetailsRowMapper();
private String deleteClientDetailsSql = DEFAULT_DELETE_STATEMENT;
private String findClientDetailsSql = DEFAULT_FIND_STATEMENT;
private String updateClientDetailsSql = DEFAULT_UPDATE_STATEMENT;
private String updateClientSecretSql = DEFAULT_UPDATE_SECRET_STATEMENT;
private String insertClientDetailsSql = DEFAULT_INSERT_STATEMENT;
private String selectClientDetailsSql = DEFAULT_SELECT_STATEMENT;
private PasswordEncoder passwordEncoder = NoOpPasswordEncoder.getInstance();
private final JdbcTemplate jdbcTemplate;
private JdbcListFactory listFactory;
public JdbcClientDetailsService(DataSource dataSource) {
Assert.notNull(dataSource, "DataSource required");
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.listFactory = new DefaultJdbcListFactory(new NamedParameterJdbcTemplate(jdbcTemplate));
}
/**
* @param passwordEncoder the password encoder to set
*/
public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
public ClientDetails loadClientByClientId(String clientId) throws InvalidClientException {
ClientDetails details;
try {
details = jdbcTemplate.queryForObject(selectClientDetailsSql, new ClientDetailsRowMapper(), clientId);
}
catch (EmptyResultDataAccessException e) {
throw new NoSuchClientException("No client with requested id: " + clientId);
}
return details;
}
public void addClientDetails(ClientDetails clientDetails) throws ClientAlreadyExistsException {
try {
jdbcTemplate.update(insertClientDetailsSql, getFields(clientDetails));
}
catch (DuplicateKeyException e) {
throw new ClientAlreadyExistsException("Client already exists: " + clientDetails.getClientId(), e);
}
}
public void updateClientDetails(ClientDetails clientDetails) throws NoSuchClientException {
int count = jdbcTemplate.update(updateClientDetailsSql, getFieldsForUpdate(clientDetails));
if (count != 1) {
throw new NoSuchClientException("No client found with id = " + clientDetails.getClientId());
}
}
public void updateClientSecret(String clientId, String secret) throws NoSuchClientException {
int count = jdbcTemplate.update(updateClientSecretSql, passwordEncoder.encode(secret), clientId);
if (count != 1) {
throw new NoSuchClientException("No client found with id = " + clientId);
}
}
public void removeClientDetails(String clientId) throws NoSuchClientException {
int count = jdbcTemplate.update(deleteClientDetailsSql, clientId);
if (count != 1) {
throw new NoSuchClientException("No client found with id = " + clientId);
}
}
public List<ClientDetails> listClientDetails() {
return listFactory.getList(findClientDetailsSql, Collections.<String, Object> emptyMap(), rowMapper);
}
private Object[] getFields(ClientDetails clientDetails) {
Object[] fieldsForUpdate = getFieldsForUpdate(clientDetails);
Object[] fields = new Object[fieldsForUpdate.length + 1];
System.arraycopy(fieldsForUpdate, 0, fields, 1, fieldsForUpdate.length);
fields[0] = clientDetails.getClientSecret() != null ? passwordEncoder.encode(clientDetails.getClientSecret())
: null;
return fields;
}
private Object[] getFieldsForUpdate(ClientDetails clientDetails) {
String json = null;
try {
json = mapper.write(clientDetails.getAdditionalInformation());
}
catch (Exception e) {
logger.warn("Could not serialize additional information: " + clientDetails, e);
}
return new Object[] {
clientDetails.getResourceIds() != null ? StringUtils.collectionToCommaDelimitedString(clientDetails
.getResourceIds()) : null,
clientDetails.getScope() != null ? StringUtils.collectionToCommaDelimitedString(clientDetails
.getScope()) : null,
clientDetails.getAuthorizedGrantTypes() != null ? StringUtils
.collectionToCommaDelimitedString(clientDetails.getAuthorizedGrantTypes()) : null,
clientDetails.getRegisteredRedirectUri() != null ? StringUtils
.collectionToCommaDelimitedString(clientDetails.getRegisteredRedirectUri()) : null,
clientDetails.getAuthorities() != null ? StringUtils.collectionToCommaDelimitedString(clientDetails
.getAuthorities()) : null, clientDetails.getAccessTokenValiditySeconds(),
clientDetails.getRefreshTokenValiditySeconds(), json, getAutoApproveScopes(clientDetails),
clientDetails.getClientId() };
}
private String getAutoApproveScopes(ClientDetails clientDetails) {
if (clientDetails.isAutoApprove("true")) {
return "true"; // all scopes autoapproved
}
Set<String> scopes = new HashSet<String>();
for (String scope : clientDetails.getScope()) {
if (clientDetails.isAutoApprove(scope)) {
scopes.add(scope);
}
}
return StringUtils.collectionToCommaDelimitedString(scopes);
}
public void setSelectClientDetailsSql(String selectClientDetailsSql) {
this.selectClientDetailsSql = selectClientDetailsSql;
}
public void setDeleteClientDetailsSql(String deleteClientDetailsSql) {
this.deleteClientDetailsSql = deleteClientDetailsSql;
}
public void setUpdateClientDetailsSql(String updateClientDetailsSql) {
this.updateClientDetailsSql = updateClientDetailsSql;
}
public void setUpdateClientSecretSql(String updateClientSecretSql) {
this.updateClientSecretSql = updateClientSecretSql;
}
public void setInsertClientDetailsSql(String insertClientDetailsSql) {
this.insertClientDetailsSql = insertClientDetailsSql;
}
public void setFindClientDetailsSql(String findClientDetailsSql) {
this.findClientDetailsSql = findClientDetailsSql;
}
/**
* @param listFactory the list factory to set
*/
public void setListFactory(JdbcListFactory listFactory) {
this.listFactory = listFactory;
}
/**
* @param rowMapper the rowMapper to set
*/
public void setRowMapper(RowMapper<ClientDetails> rowMapper) {
this.rowMapper = rowMapper;
}
/**
* Row mapper for ClientDetails.
*
* @author Dave Syer
*
*/
private static class ClientDetailsRowMapper implements RowMapper<ClientDetails> {
private JsonMapper mapper = createJsonMapper();
public ClientDetails mapRow(ResultSet rs, int rowNum) throws SQLException {
BaseClientDetails details = new BaseClientDetails(rs.getString(1), rs.getString(3), rs.getString(4),
rs.getString(5), rs.getString(7), rs.getString(6));
details.setClientSecret(rs.getString(2));
if (rs.getObject(8) != null) {
details.setAccessTokenValiditySeconds(rs.getInt(8));
}
if (rs.getObject(9) != null) {
details.setRefreshTokenValiditySeconds(rs.getInt(9));
}
String json = rs.getString(10);
if (json != null) {
try {
@SuppressWarnings("unchecked")
Map<String, Object> additionalInformation = mapper.read(json, Map.class);
details.setAdditionalInformation(additionalInformation);
}
catch (Exception e) {
logger.warn("Could not decode JSON for additional information: " + details, e);
}
}
String scopes = rs.getString(11);
if (scopes != null) {
details.setAutoApproveScopes(StringUtils.commaDelimitedListToSet(scopes));
}
return details;
}
}
interface JsonMapper {
String write(Object input) throws Exception;
<T> T read(String input, Class<T> type) throws Exception;
}
private static JsonMapper createJsonMapper() {
if (ClassUtils.isPresent("org.codehaus.jackson.map.ObjectMapper", null)) {
return new JacksonMapper();
}
else if (ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", null)) {
return new Jackson2Mapper();
}
return new NotSupportedJsonMapper();
}
private static class JacksonMapper implements JsonMapper {
private org.codehaus.jackson.map.ObjectMapper mapper = new org.codehaus.jackson.map.ObjectMapper();
@Override
public String write(Object input) throws Exception {
return mapper.writeValueAsString(input);
}
@Override
public <T> T read(String input, Class<T> type) throws Exception {
return mapper.readValue(input, type);
}
}
private static class Jackson2Mapper implements JsonMapper {
private com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
@Override
public String write(Object input) throws Exception {
return mapper.writeValueAsString(input);
}
@Override
public <T> T read(String input, Class<T> type) throws Exception {
return mapper.readValue(input, type);
}
}
private static class NotSupportedJsonMapper implements JsonMapper {
@Override
public String write(Object input) throws Exception {
throw new UnsupportedOperationException(
"Neither Jackson 1 nor 2 is available so JSON conversion cannot be done");
}
@Override
public <T> T read(String input, Class<T> type) throws Exception {
throw new UnsupportedOperationException(
"Neither Jackson 1 nor 2 is available so JSON conversion cannot be done");
}
}
}