Advertisement
Guest User

Untitled

a guest
Apr 16th, 2016
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.67 KB | None | 0 0
  1. public class JdbcRealm extends AuthorizingRealm implements Serializable
  2. {
  3. @Resource(name = "jdbc/DefaultDB")
  4. private DataSource dataSource;
  5.  
  6. protected static final String DEFAULT_AUTHENTICATION_QUERY = "select passwd from user where username = ?";
  7. protected static final String DEFAULT_SALTED_AUTHENTICATION_QUERY = "select passwd, passwd_salt from user where username = ?";
  8. protected static final String DEFAULT_USER_ROLES_QUERY = "select role_name from user_roles where username = ?";
  9. protected static final String DEFAULT_PERMISSIONS_QUERY = "select permission from roles_permissions where role_name = ?";
  10. private static final Logger log = LoggerFactory.getLogger(JdbcRealm.class);
  11.  
  12. public enum SaltStyle
  13. {
  14. NO_SALT, CRYPT, COLUMN, EXTERNAL
  15. };
  16.  
  17. protected String authenticationQuery = DEFAULT_AUTHENTICATION_QUERY;
  18. protected String userRolesQuery = DEFAULT_USER_ROLES_QUERY;
  19. protected String permissionsQuery = DEFAULT_PERMISSIONS_QUERY;
  20. protected boolean permissionsLookupEnabled = false;
  21.  
  22. protected SaltStyle saltStyle = SaltStyle.NO_SALT;
  23.  
  24. public void setDataSource(DataSource dataSource)
  25. {
  26. this.dataSource = dataSource;
  27. }
  28.  
  29. public void setAuthenticationQuery(String authenticationQuery)
  30. {
  31. this.authenticationQuery = authenticationQuery;
  32. }
  33.  
  34. public void setUserRolesQuery(String userRolesQuery)
  35. {
  36. this.userRolesQuery = userRolesQuery;
  37. }
  38.  
  39. public void setPermissionsQuery(String permissionsQuery)
  40. {
  41. this.permissionsQuery = permissionsQuery;
  42. }
  43.  
  44. public void setPermissionsLookupEnabled(boolean permissionsLookupEnabled)
  45. {
  46. this.permissionsLookupEnabled = permissionsLookupEnabled;
  47. }
  48.  
  49. public void setSaltStyle(SaltStyle saltStyle)
  50. {
  51. this.saltStyle = saltStyle;
  52. if (saltStyle == SaltStyle.COLUMN && authenticationQuery.equals(DEFAULT_AUTHENTICATION_QUERY))
  53. {
  54. authenticationQuery = DEFAULT_SALTED_AUTHENTICATION_QUERY;
  55. }
  56. }
  57.  
  58. @Override
  59. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException
  60. {
  61. UsernamePasswordToken upToken = (UsernamePasswordToken) token;
  62. String username = upToken.getUsername();
  63. // Null username is invalid
  64. if (username == null)
  65. {
  66. throw new AccountException("Null usernames are not allowed by this realm.");
  67. }
  68. Connection conn = null;
  69. SimpleAuthenticationInfo info = null;
  70. try
  71. {
  72. conn = dataSource.getConnection();
  73. String password = null;
  74. String salt = null;
  75. switch (saltStyle)
  76. {
  77. case NO_SALT:
  78. password = getPasswordForUser(conn, username)[0];
  79. break;
  80. case CRYPT:
  81. // TODO: separate password and hash from getPasswordForUser[0]
  82. throw new ConfigurationException("Not implemented yet");
  83. //break;
  84. case COLUMN:
  85. String[] queryResults = getPasswordForUser(conn, username);
  86. password = queryResults[0];
  87. salt = queryResults[1];
  88. break;
  89. case EXTERNAL:
  90. password = getPasswordForUser(conn, username)[0];
  91. salt = getSaltForUser(username);
  92. }
  93. if (password == null)
  94. {
  95. throw new UnknownAccountException("No account found for user [" + username + "]");
  96. }
  97. info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());
  98.  
  99. if (salt != null)
  100. {
  101. info.setCredentialsSalt(ByteSource.Util.bytes(salt));
  102. }
  103. }
  104. catch (SQLException e)
  105. {
  106. final String message = "There was a SQL error while authenticating user [" + username + "]";
  107. if (log.isErrorEnabled())
  108. {
  109. log.error(message, e);
  110. }
  111. // Rethrow any SQL errors as an authentication exception
  112. throw new AuthenticationException(message, e);
  113. }
  114. finally
  115. {
  116. JdbcUtils.closeConnection(conn);
  117. }
  118. return info;
  119. }
  120.  
  121. private String[] getPasswordForUser(Connection conn, String username) throws SQLException
  122. {
  123. String[] result;
  124. boolean returningSeparatedSalt = false;
  125. switch (saltStyle)
  126. {
  127. case NO_SALT:
  128. case CRYPT:
  129. case EXTERNAL:
  130. result = new String[1];
  131. break;
  132. default:
  133. result = new String[2];
  134. returningSeparatedSalt = true;
  135. }
  136.  
  137. PreparedStatement ps = null;
  138. ResultSet rs = null;
  139. try
  140. {
  141. ps = conn.prepareStatement(authenticationQuery);
  142. ps.setString(1, username);
  143. // Execute query
  144. rs = ps.executeQuery();
  145. // Loop over results - although we are only expecting one result, since usernames should be unique
  146. boolean foundResult = false;
  147. while (rs.next())
  148. {
  149. // Check to ensure only one row is processed
  150. if (foundResult)
  151. {
  152. throw new AuthenticationException("More than one user row found for user [" + username + "]. Usernames must be unique.");
  153. }
  154. result[0] = rs.getString(1);
  155. if (returningSeparatedSalt)
  156. {
  157. result[1] = rs.getString(2);
  158. }
  159. foundResult = true;
  160. }
  161. }
  162. finally
  163. {
  164. JdbcUtils.closeResultSet(rs);
  165. JdbcUtils.closeStatement(ps);
  166. }
  167. return result;
  168. }
  169.  
  170. @Override
  171. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals)
  172. {
  173. //null usernames are invalid
  174. if (principals == null)
  175. {
  176. throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
  177. }
  178. String username = (String) getAvailablePrincipal(principals);
  179. Connection conn = null;
  180. Set<String> roleNames = null;
  181. Set<String> permissions = null;
  182. try
  183. {
  184. conn = dataSource.getConnection();
  185. // Retrieve roles and permissions from database
  186. roleNames = getRoleNamesForUser(conn, username);
  187. if (permissionsLookupEnabled)
  188. {
  189. permissions = getPermissions(conn, username, roleNames);
  190. }
  191. }
  192. catch (SQLException e)
  193. {
  194. final String message = "There was a SQL error while authorizing user [" + username + "]";
  195. if (log.isErrorEnabled())
  196. {
  197. log.error(message, e);
  198. }
  199. // Rethrow any SQL errors as an authorization exception
  200. throw new AuthorizationException(message, e);
  201. }
  202. finally
  203. {
  204. JdbcUtils.closeConnection(conn);
  205. }
  206. SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
  207. info.setStringPermissions(permissions);
  208. return info;
  209. }
  210.  
  211. protected Set<String> getRoleNamesForUser(Connection conn, String username) throws SQLException
  212. {
  213. PreparedStatement ps = null;
  214. ResultSet rs = null;
  215. Set<String> roleNames = new LinkedHashSet<String>();
  216. try
  217. {
  218. ps = conn.prepareStatement(userRolesQuery);
  219. ps.setString(1, username);
  220. // Execute query
  221. rs = ps.executeQuery();
  222. // Loop over results and add each returned role to a set
  223. while (rs.next())
  224. {
  225. String roleName = rs.getString(1);
  226. // Add the role to the list of names if it isn't null
  227. if (roleName != null)
  228. {
  229. roleNames.add(roleName);
  230. }
  231. else
  232. {
  233. if (log.isWarnEnabled())
  234. {
  235. log.warn("Null role name found while retrieving role names for user [" + username + "]");
  236. }
  237. }
  238. }
  239. }
  240. finally
  241. {
  242. JdbcUtils.closeResultSet(rs);
  243. JdbcUtils.closeStatement(ps);
  244. }
  245. return roleNames;
  246. }
  247.  
  248. protected Set<String> getPermissions(Connection conn, String username, Collection<String> roleNames) throws SQLException
  249. {
  250. PreparedStatement ps = null;
  251. Set<String> permissions = new LinkedHashSet<>();
  252. try
  253. {
  254. ps = conn.prepareStatement(permissionsQuery);
  255. for (String roleName : roleNames)
  256. {
  257. ps.setString(1, roleName);
  258. ResultSet rs = null;
  259. try
  260. {
  261. // Execute query
  262. rs = ps.executeQuery();
  263. // Loop over results and add each returned role to a set
  264. while (rs.next())
  265. {
  266. String permissionString = rs.getString(1);
  267. // Add the permission to the set of permissions
  268. permissions.add(permissionString);
  269. }
  270. }
  271. finally
  272. {
  273. JdbcUtils.closeResultSet(rs);
  274. }
  275. }
  276. }
  277. finally
  278. {
  279. JdbcUtils.closeStatement(ps);
  280. }
  281. return permissions;
  282. }
  283.  
  284. protected String getSaltForUser(String username)
  285. {
  286. return username;
  287. }
  288. }
  289.  
  290. conn = dataSource.getConnection();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement