1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.shiro.samples.spring.realm;
20
21 import org.apache.shiro.authc.*;
22 import org.apache.shiro.realm.jdbc.JdbcRealm;
23 import org.apache.shiro.util.ByteSource;
24 import org.apache.shiro.util.JdbcUtils;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 import java.sql.Connection;
29 import java.sql.PreparedStatement;
30 import java.sql.ResultSet;
31 import java.sql.SQLException;
32
33
34
35
36
37 public class SaltAwareJdbcRealm extends JdbcRealm {
38
39 private static final Logger log = LoggerFactory.getLogger(SaltAwareJdbcRealm.class);
40
41 @Override
42 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
43 UsernamePasswordToken upToken = (UsernamePasswordToken) token;
44 String username = upToken.getUsername();
45
46
47 if (username == null) {
48 throw new AccountException("Null usernames are not allowed by this realm.");
49 }
50
51 Connection conn = null;
52 AuthenticationInfo info = null;
53 try {
54 conn = dataSource.getConnection();
55
56 String password = getPasswordForUser(conn, username);
57
58 if (password == null) {
59 throw new UnknownAccountException("No account found for user [" + username + "]");
60 }
61
62 SimpleAuthenticationInfo saInfo = new SimpleAuthenticationInfo(username, password, getName());
63
64
65
66
67
68
69 saInfo.setCredentialsSalt(ByteSource.Util.bytes(username));
70
71 info = saInfo;
72
73 } catch (SQLException e) {
74 final String message = "There was a SQL error while authenticating user [" + username + "]";
75 if (log.isErrorEnabled()) {
76 log.error(message, e);
77 }
78
79
80 throw new AuthenticationException(message, e);
81 } finally {
82 JdbcUtils.closeConnection(conn);
83 }
84
85 return info;
86 }
87
88 private String getPasswordForUser(Connection conn, String username) throws SQLException {
89
90 PreparedStatement ps = null;
91 ResultSet rs = null;
92 String password = null;
93 try {
94 ps = conn.prepareStatement(authenticationQuery);
95 ps.setString(1, username);
96
97
98 rs = ps.executeQuery();
99
100
101 boolean foundResult = false;
102 while (rs.next()) {
103
104
105 if (foundResult) {
106 throw new AuthenticationException("More than one user row found for user [" + username + "]. Usernames must be unique.");
107 }
108
109 password = rs.getString(1);
110
111 foundResult = true;
112 }
113 } finally {
114 JdbcUtils.closeResultSet(rs);
115 JdbcUtils.closeStatement(ps);
116 }
117
118 return password;
119 }
120
121 }