We are creating portal to write select statement for end user. As this is expected to use externally, we are allowing to use only SELECT query.
How can we restrict only SELECT query execution using jdbcTemplate?
We are creating portal to write select statement for end user. As this is expected to use externally, we are allowing to use only SELECT query.
How can we restrict only SELECT query execution using jdbcTemplate?
On
One simple solution would be to validate that the statement begins with "SELECT". Only if this is met, you should feed the statement to the JdbcTemplate.
Depending on your implementation, you might also want to forbid semicolons (";") inside the string provided by the user, so they cannot provide multiple statements (and thereby execute non-SELECT statements).
On
Your portal should only connect to a database user that is limited to read-only privileges in the database. Never, ever, ever connect an application to the account that actually owns database objects, especially if you're allowing any kind of ad-hoc SQL. The privileges of schema owners generally can't be restricted on the objects they own, so treat them like you would a superuser or admin account: not for public consumption.
On top of that, the input validations suggested by @yamass are spot on as well.
This is the wrong target for the restriction. If you want to restrict someone to only use
SELECTqueries then do it in the Oracle database rather than in the middle-tier, i.e. Java (or worse, trying to enforce the restriction on a client application).If you have an Oracle user
table_ownerthat, unsurprisingly, owns the tables and data that you are using then if you want to restrict the middle-tier to only usingSELECTstatements against those tables then do not let the middle-tier connect to thetable_owneruser; if you do then the database automatically assumes that a user has full permissions to read and modify everything that they own so there will be no restrictions on what you can do.Instead:
table_viewerGRANT SELECT ON table_owner.table_name TO table_viewertable_vieweruser and you can useSELECT * FROM table_owner.table1but you will be forbidden from usingINSERT,UPDATE,DELETE, etc. statements against that table because the user you are connecting to does not have those privileges.GRANTthe appropriate privileges to that user.Then you will not need to modify the Java application (apart from maybe changing which user you are connecting to) and the database will ensure that the connected user is only doing what their granted permissions allow.
If you want ALL users to only be able to read from a table then:
Then the table can only be read and any attempted modifications will raise an exception (until a user with the appropriate privileges changes it back to read-write).