1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.shiro.realm.jdbc;
20
21 import org.apache.shiro.authc.*;
22 import org.apache.shiro.authz.AuthorizationException;
23 import org.apache.shiro.authz.AuthorizationInfo;
24 import org.apache.shiro.authz.SimpleAuthorizationInfo;
25 import org.apache.shiro.config.ConfigurationException;
26 import org.apache.shiro.realm.AuthorizingRealm;
27 import org.apache.shiro.subject.PrincipalCollection;
28 import org.apache.shiro.util.ByteSource;
29 import org.apache.shiro.util.JdbcUtils;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 import javax.sql.DataSource;
34 import java.sql.Connection;
35 import java.sql.PreparedStatement;
36 import java.sql.ResultSet;
37 import java.sql.SQLException;
38 import java.util.Collection;
39 import java.util.LinkedHashSet;
40 import java.util.Set;
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57 public class JdbcRealm extends AuthorizingRealm {
58
59
60
61
62
63
64
65
66
67 protected static final String DEFAULT_AUTHENTICATION_QUERY = "select password from users where username = ?";
68
69
70
71
72 protected static final String DEFAULT_SALTED_AUTHENTICATION_QUERY = "select password, password_salt from users where username = ?";
73
74
75
76
77 protected static final String DEFAULT_USER_ROLES_QUERY = "select role_name from user_roles where username = ?";
78
79
80
81
82 protected static final String DEFAULT_PERMISSIONS_QUERY = "select permission from roles_permissions where role_name = ?";
83
84 private static final Logger log = LoggerFactory.getLogger(JdbcRealm.class);
85
86
87
88
89
90
91
92
93
94 public enum SaltStyle {NO_SALT, CRYPT, COLUMN, EXTERNAL};
95
96
97
98
99 protected DataSource dataSource;
100
101 protected String authenticationQuery = DEFAULT_AUTHENTICATION_QUERY;
102
103 protected String userRolesQuery = DEFAULT_USER_ROLES_QUERY;
104
105 protected String permissionsQuery = DEFAULT_PERMISSIONS_QUERY;
106
107 protected boolean permissionsLookupEnabled = false;
108
109 protected SaltStyle saltStyle = SaltStyle.NO_SALT;
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124 public void setDataSource(DataSource dataSource) {
125 this.dataSource = dataSource;
126 }
127
128
129
130
131
132
133
134
135
136
137
138 public void setAuthenticationQuery(String authenticationQuery) {
139 this.authenticationQuery = authenticationQuery;
140 }
141
142
143
144
145
146
147
148
149
150
151
152 public void setUserRolesQuery(String userRolesQuery) {
153 this.userRolesQuery = userRolesQuery;
154 }
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171 public void setPermissionsQuery(String permissionsQuery) {
172 this.permissionsQuery = permissionsQuery;
173 }
174
175
176
177
178
179
180
181
182 public void setPermissionsLookupEnabled(boolean permissionsLookupEnabled) {
183 this.permissionsLookupEnabled = permissionsLookupEnabled;
184 }
185
186
187
188
189
190
191 public void setSaltStyle(SaltStyle saltStyle) {
192 this.saltStyle = saltStyle;
193 if (saltStyle == SaltStyle.COLUMN && authenticationQuery.equals(DEFAULT_AUTHENTICATION_QUERY)) {
194 authenticationQuery = DEFAULT_SALTED_AUTHENTICATION_QUERY;
195 }
196 }
197
198
199
200
201
202 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
203
204 UsernamePasswordToken upToken = (UsernamePasswordToken) token;
205 String username = upToken.getUsername();
206
207
208 if (username == null) {
209 throw new AccountException("Null usernames are not allowed by this realm.");
210 }
211
212 Connection conn = null;
213 SimpleAuthenticationInfo info = null;
214 try {
215 conn = dataSource.getConnection();
216
217 String password = null;
218 String salt = null;
219 switch (saltStyle) {
220 case NO_SALT:
221 password = getPasswordForUser(conn, username)[0];
222 break;
223 case CRYPT:
224
225 throw new ConfigurationException("Not implemented yet");
226
227 case COLUMN:
228 String[] queryResults = getPasswordForUser(conn, username);
229 password = queryResults[0];
230 salt = queryResults[1];
231 break;
232 case EXTERNAL:
233 password = getPasswordForUser(conn, username)[0];
234 salt = getSaltForUser(username);
235 }
236
237 if (password == null) {
238 throw new UnknownAccountException("No account found for user [" + username + "]");
239 }
240
241 info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());
242
243 if (salt != null) {
244 info.setCredentialsSalt(ByteSource.Util.bytes(salt));
245 }
246
247 } catch (SQLException e) {
248 final String message = "There was a SQL error while authenticating user [" + username + "]";
249 if (log.isErrorEnabled()) {
250 log.error(message, e);
251 }
252
253
254 throw new AuthenticationException(message, e);
255 } finally {
256 JdbcUtils.closeConnection(conn);
257 }
258
259 return info;
260 }
261
262 private String[] getPasswordForUser(Connection conn, String username) throws SQLException {
263
264 String[] result;
265 boolean returningSeparatedSalt = false;
266 switch (saltStyle) {
267 case NO_SALT:
268 case CRYPT:
269 case EXTERNAL:
270 result = new String[1];
271 break;
272 default:
273 result = new String[2];
274 returningSeparatedSalt = true;
275 }
276
277 PreparedStatement ps = null;
278 ResultSet rs = null;
279 try {
280 ps = conn.prepareStatement(authenticationQuery);
281 ps.setString(1, username);
282
283
284 rs = ps.executeQuery();
285
286
287 boolean foundResult = false;
288 while (rs.next()) {
289
290
291 if (foundResult) {
292 throw new AuthenticationException("More than one user row found for user [" + username + "]. Usernames must be unique.");
293 }
294
295 result[0] = rs.getString(1);
296 if (returningSeparatedSalt) {
297 result[1] = rs.getString(2);
298 }
299
300 foundResult = true;
301 }
302 } finally {
303 JdbcUtils.closeResultSet(rs);
304 JdbcUtils.closeStatement(ps);
305 }
306
307 return result;
308 }
309
310
311
312
313
314
315
316 @Override
317 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
318
319
320 if (principals == null) {
321 throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
322 }
323
324 String username = (String) getAvailablePrincipal(principals);
325
326 Connection conn = null;
327 Set<String> roleNames = null;
328 Set<String> permissions = null;
329 try {
330 conn = dataSource.getConnection();
331
332
333 roleNames = getRoleNamesForUser(conn, username);
334 if (permissionsLookupEnabled) {
335 permissions = getPermissions(conn, username, roleNames);
336 }
337
338 } catch (SQLException e) {
339 final String message = "There was a SQL error while authorizing user [" + username + "]";
340 if (log.isErrorEnabled()) {
341 log.error(message, e);
342 }
343
344
345 throw new AuthorizationException(message, e);
346 } finally {
347 JdbcUtils.closeConnection(conn);
348 }
349
350 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
351 info.setStringPermissions(permissions);
352 return info;
353
354 }
355
356 protected Set<String> getRoleNamesForUser(Connection conn, String username) throws SQLException {
357 PreparedStatement ps = null;
358 ResultSet rs = null;
359 Set<String> roleNames = new LinkedHashSet<String>();
360 try {
361 ps = conn.prepareStatement(userRolesQuery);
362 ps.setString(1, username);
363
364
365 rs = ps.executeQuery();
366
367
368 while (rs.next()) {
369
370 String roleName = rs.getString(1);
371
372
373 if (roleName != null) {
374 roleNames.add(roleName);
375 } else {
376 if (log.isWarnEnabled()) {
377 log.warn("Null role name found while retrieving role names for user [" + username + "]");
378 }
379 }
380 }
381 } finally {
382 JdbcUtils.closeResultSet(rs);
383 JdbcUtils.closeStatement(ps);
384 }
385 return roleNames;
386 }
387
388 protected Set<String> getPermissions(Connection conn, String username, Collection<String> roleNames) throws SQLException {
389 PreparedStatement ps = null;
390 Set<String> permissions = new LinkedHashSet<String>();
391 try {
392 ps = conn.prepareStatement(permissionsQuery);
393 for (String roleName : roleNames) {
394
395 ps.setString(1, roleName);
396
397 ResultSet rs = null;
398
399 try {
400
401 rs = ps.executeQuery();
402
403
404 while (rs.next()) {
405
406 String permissionString = rs.getString(1);
407
408
409 permissions.add(permissionString);
410 }
411 } finally {
412 JdbcUtils.closeResultSet(rs);
413 }
414
415 }
416 } finally {
417 JdbcUtils.closeStatement(ps);
418 }
419
420 return permissions;
421 }
422
423 protected String getSaltForUser(String username) {
424 return username;
425 }
426
427 }