--create a user that you want to use the database as:
create role neil;
--create the user for the web server to connect as:
create role webgui noinherit login password 's3cr3t';
--let webgui set role to neil:
grant neil to webgui; --this looks backwards but is correct.
webgui
er nu i neil
gruppe, så webgui
kan kalde set role neil
. Dog webgui
arvede ikke neil
s tilladelser.
Log ind som webgui senere:
psql -d some_database -U webgui
(enter s3cr3t as password)
set role neil;
webgui
behøver ikke superuser
tilladelse til dette.
Du vil set role
i begyndelsen af en databasesession og nulstil den i slutningen af sessionen. I en web-app svarer det til, at man henholdsvis får en forbindelse fra sin databaseforbindelsespulje og frigiver den. Her er et eksempel, der bruger Tomcats forbindelsespulje og Spring Security:
public class SetRoleJdbcInterceptor extends JdbcInterceptor {
@Override
public void reset(ConnectionPool connectionPool, PooledConnection pooledConnection) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication != null) {
try {
/*
use OWASP's ESAPI to encode the username to avoid SQL Injection. Can't use parameters with SET ROLE. Need to write PG codec.
Or use a whitelist-map approach
*/
String username = ESAPI.encoder().encodeForSQL(MY_CODEC, authentication.getName());
Statement statement = pooledConnection.getConnection().createStatement();
statement.execute("set role \"" + username + "\"");
statement.close();
} catch(SQLException exp){
throw new RuntimeException(exp);
}
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("close".equals(method.getName())){
Statement statement = ((Connection)proxy).createStatement();
statement.execute("reset role");
statement.close();
}
return super.invoke(proxy, method, args);
}
}