Link to home
Start Free TrialLog in
Avatar of nexchanger
nexchanger

asked on

how to authentice postgres user from java client

Hi experts,

I am trying to authenticate a user with postgres. I have created a postgres user and when I use the method below, it seems to work fine for a database installation on windows - i.e it returns a null Connection object when the authentication fails, however for a postgres installation on unix, it returns a non null Connection object even when the authentication fails. I am relying on this method to authenticate a user based on if the connection object is null or not.

Am I missing some thing trivial here. I cant understand why its behaving differently in the above cases. Any suggestions regarding this or any alternate ways of authenticating a postgres user would be appreciated.

public static Connection getConnection(String JNDIName, String username, String password) throws FrameworkException {

    Connection conn = null;
    try {
      DataSource ds = ServiceLocator.getInstance().getDatasource(JNDIName, true);

      if (username == null || (username != null && "".equals(username))) {
        //Retrieve the connection with the DS configured user/passowrd
        conn = ds.getConnection();
      }
      else {
        conn = ds.getConnection(username, password);
      }
    }
    catch (SQLException se) {
      throw new FrameworkException("Error retrieving connection for: " + JNDIName, se);
    }
    catch (ServiceLocatorException sle) {
      throw new FrameworkException("Could not retrieve a datasource for " + JNDIName, sle);
    }
    return conn;
  }
ASKER CERTIFIED SOLUTION
Avatar of earth man2
earth man2
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nexchanger
nexchanger

ASKER

Actually its a little late for my purposes, as I now changed my code to fetch it from the pg_roles/pg_shadow and do all the logic myself.
Nonetheless thanks for your help!