Reputation: 31
I am a bit stuck here.
Using a very simple Shiro configuration with jdbcRealm:
[main]
cacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
securityManager.cacheManager = $cacheManager
# Create JDBC realm.
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
# Configure JDBC realm datasource.
ds = org.postgresql.ds.PGSimpleDataSource
ds.databaseName = pg_sensor
***
jdbcRealm.dataSource = $ds
# Configure JDBC realm SQL queries.
jdbcRealm.authenticationQuery = SELECT pass FROM users WHERE name = ?
# user id is a user Role )
jdbcRealm.userRolesQuery = SELECT id FROM users WHERE name = ?
So, I use userid
as a role to do authorization in the code.
In one scenario I need to get role name to proceed.
Can anyone suggest how to do that from the Principal
(SecurityUtils.getSubject().getPrincipal()
)?
I guess we need to use getRoles()
withing SimpleAccount
class, but not able to connect it with Principal
.
Upvotes: 3
Views: 1896
Reputation: 3422
Before anything, some comment about your shiro.ini:
First of all, your jdbcRealm.userRolesQuery
does not really make sense: you are supposed to fetch the roles not the users for this query.
Assuming you have tables
CREATE TABLE user{
id INTEGER,
username VARCHAR,
password VARCHAR
}
CREATE TABLE user_role{
id INTEGER,
role_name VARCHAR,
username VARCHAR
}
your queries would like:
# Configure JDBC realm SQL queries.
jdbcRealm.authenticationQuery = SELECT password FROM user WHERE username = ?
# user id is a user Role )
jdbcRealm.userRolesQuery = SELECT role_name FROM user_role WHERE username = ?
I'm assuming that your subject is already successfully authenticated. So far, SecurityUtils.getSubject().getPrincipal()
will only return the login or username, anything which identify your user but nothing more. In my above example, it would return the value stored in username
column.
I think, you are rather looking does this authenticated user has role "MyRole"?. In this case, you can have a look around SecurityUtils.getSubject().hasRole("MyRole")
. As far as I know, there is no way to list all the roles a subject currently has. You can only check if the subject has such or such role
Feel free to comment if I misunderstood your question
Upvotes: 4