--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 अब neil में है समूह, इसलिए webgui कॉल कर सकते हैं set role neil . हालांकि, webgui neil का वारिस नहीं हुआ की अनुमतियाँ।
बाद में, webgui के रूप में लॉगिन करें:
psql -d some_database -U webgui
(enter s3cr3t as password)
set role neil;
webgui जरूरत नहीं है superuser इसके लिए अनुमति।
आप set role करना चाहते हैं डेटाबेस सत्र की शुरुआत में और सत्र के अंत में इसे रीसेट करें। एक वेब ऐप में, यह आपके डेटाबेस कनेक्शन पूल से कनेक्शन प्राप्त करने और इसे क्रमशः जारी करने से मेल खाता है। यहां टॉमकैट के कनेक्शन पूल और स्प्रिंग सिक्योरिटी का उपयोग करते हुए एक उदाहरण दिया गया है:
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);
}
}