Skip to content

Instantly share code, notes, and snippets.

@bobbotron
Last active December 10, 2017 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bobbotron/c1d2282069a57b2b5b58541b6540de33 to your computer and use it in GitHub Desktop.
Save bobbotron/c1d2282069a57b2b5b58541b6540de33 to your computer and use it in GitHub Desktop.
Shiro Authn JDBC/JNDI example
/**
* This is a psuedo java class to demonstrate how to pull user permissions from
* a JNDI java database connection.
**/
public class ShiroAuthnLookup
{
private List<String> getPermissions(String userName) throws
SQLException
{
try (Connection c = getJNDIConnection())
{
List<String> perms = new ArrayList<>();
PreparedStatement stmt = c.prepareStatement("SELECT permission FROM permissions WHERE user_id = ?");
stmt.setString(1, userName);
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
perms.add(rs.getString(1));
}
log.debug("Returning permissions {} for {}", perms, userName);
return perms;
}
}
private Connection getJNDIConnection() throws SQLException
{
String jndiName = "jdbc/yourDbDS";
Connection result = null;
try
{
final Context initialContext = new InitialContext();
log.trace("Looking up java:comp/env");
Context dbContext = (Context) initialContext.lookup("java:comp/env");
log.trace("comp details: {}", initialContext.list("java:comp/env"));
log.trace("Looking up jdbc JNDI {}", jndiName);
DataSource dataSource = (DataSource) dbContext.lookup(jndiName);
if (dataSource != null)
{
result = dataSource.getConnection();
}
else
{
log.error("Could not lookup datasource!");
}
}
catch (NamingException ex)
{
log.error("Naming exception occurred {}", ex);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment