Search code examples
springauthenticationrolesshiro

Apache Shiro decide what role to use after login


I have an existing legacy project which is built with Spring 3 and Apache Shiro for authentication and authorization. It uses a JDBC realm.

We have the authorization implemented with permissions assigned to authorities and authorities to users.

The scenario is like:

  • use1: fooRole, barRole

  • fooRole: foo.permission.1, foo.permission.2

  • barRole: bar.permission.1, bar.permission.2

I've been requested to login with "user1" and afer login select whhich role "user1" wants to operate with. For example:

  1. Correct login user1
  2. select fooRole or barRole
  3. select fooRole and now operate with "foo.permission.1, foo.permission.2" permissions.

According tho the shiro architecture in my application I have a "Subject" accesible as read only. And the security mannager gets the information from my database. I can check if the subject has a specific role or permission. But once I've loged in I dont see a way to alter user roles to the subject.

I think this is not the way Apache Shiro is suposed to work, and this may not be the best of practices, but anyway: Does any of you have an idea to explicit select one of asigned roles to operate only with, in Apache Shiro?

Thanks you all for your time.


Solution

  • You can change user permissions at runtime. There is a discussion about this issue here. This is something you have to do in a custom Shiro realm since it's the only place you have access to the AuthorizationInfo by design. The AuthorizationInfo stores authorisation data like permissions and roles represented by a single subject. There is no getter and setter outside of your realm for a subject to assign roles and permissions. You can always check:

    • if a subject holds a permission: SecurityUtils.getSubject().isPermitted();
    • if a subject holds a role: SecurityUtils.getSubject().hasRoles();

    The simplest implementation of AuthorizationInfo is SimpleAuthorizationInfo.

    IMHO this is a bad practise for many reasons. This is not what Shiro is build for.