What is the right approach for passing authentication information to a datasource? This is needed in order to obtain a database connection using the user authentication information. The database connection is expected to be obtained for each call to getConnection() method of the DataSource. Currently, I am using a SecurityContext to get the AuthenticationToken, however, using a ThreadLocal was suggested on http://stackoverflow.com/questions/8...urce-in-spring

Here is the code for using the security context:

Code:
public class CustomAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
	public Authentication attemptAuthentication(){

		CustomAuthenticationToken result = new CustomAuthenticationToken(
				username, password, database, authorities);
		
		return result;
	}
}

public class CustomDataSource extends DriverManagerDataSource{
	
	protected Connection getConnectionFromDriverManager(String url,
			Properties props) throws SQLException {
		
		// option 1 using the security context
		SecurityContext securityContext = SecurityContextHolder.getContext();
		Authentication authentication = securityContext.getAuthentication();
		if (authentication != null){
			Object principal = authentication.getPrincipal();
			Object credentials = authentication.getCredentials();
			Connection conn = getConn(principal, credentials);
			return conn;
		}
		return null;
	}
}
and here is the code for using a ThreadLocal:

Code:
public interface WebUtils{
    public static final ThreadLocal<AuthInfo> authInfo = new ThreadLocal<AuthInfo>();
}

public class CustomAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
	public Authentication attemptAuthentication(){

		CustomAuthenticationToken result = new CustomAuthenticationToken(
				username, "", database, authorities);
		
		AuthInfo info = new AuthInfo();
		info.setName(username);
		info.setPass(password);
		
		WebAttributes.authInfo.set(info);
		
		return result;
	}
}

public class CustomDataSource extends DriverManagerDataSource{
	
	protected Connection getConnectionFromDriverManager(String url,
			Properties props) throws SQLException {
		
		// option 1 using ThreadLocal
		AuthInfo info = WebAttributes.authInfo.get();
		Connection conn = getConnFromAuthInfo(info);
		return conn;

	}
}