4

I built a database with the entity user and permission

user (id, email, password, permission) permission (id, create_user, delete_user, user_fk)

create_user and delete_user is BOOLEAN.

Relationship: One-One

Now every user can have it's own permissions.

My question is: How can I use shiro to read the permissions from the database?

André Schild
  • 4,592
  • 5
  • 28
  • 42
internet
  • 385
  • 1
  • 8
  • 27

2 Answers2

5

If you really only wish to assign permissions on user level, you can "fake" the roles table to make Shiro happy.

As Wouter mentioned, use the JdbcRealm and specify the 3 queries for your table setup. You should modify your permission table to have this structure:

permission (id, permissionname, user_fk)

Then you insert rows for the create_user/delete_user rights as needed. This way it's very simple to add another permission (reset_password for example) to your setup, without the need to modify the db schema.

In the shiro.ini (or how you call the your shiro config file):

jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm

For the queries use then this:

jdbcRealm.authenticationQuery = select password from user where email=?
jdbcRealm.userRolesQuery = select id from user where email=?
jdbcRealm.authenticationQuery = select permissionname from permission where user_fk=?

The small trick in your setup is: you don't have roles at all, so we just return the id of the user as the role name. When the lookup in the permission table is done, it then uses the role name (=user pk) and returns the associated permissions.

Jens Piegsa
  • 7,399
  • 5
  • 58
  • 106
André Schild
  • 4,592
  • 5
  • 28
  • 42
4

You should configure a JdbcReam in your .ini file:

jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm

If you change your schema to adhere to the shiro queries, no extra config is needed. You need tables users, user_roles and roles_permissions.

See the source code how the exact column names should be:

https://svn.apache.org/repos/asf/shiro/trunk/core/src/main/java/org/apache/shiro/realm/jdbc/JdbcRealm.java

Alternatively you can configure your own queries to match your schema in the .ini file like so:

jdbcRealm.authenticationQuery=<your password select statement>
jdbcRealm.userRolesQuery=<your role names for username select statement>
jdbcRealm.authenticationQuery=<your permissions for role name select statement>
Wouter
  • 3,976
  • 2
  • 31
  • 50