4

NOTE: Due to subsequent research this question has been completely restructured.

I am trying to retrieve values from Shiro's subject PrincipalCollection. I have added two principals to the collection. Username and UUID. When I try to recall these I get a SimplePrincipalCollection of size = 1 and this in turn has the principals as a LinkedHashMap of size = 2.

Question is how can I retrieve the principals directly?

Sampada
  • 2,931
  • 7
  • 27
  • 39
tarka
  • 5,289
  • 10
  • 51
  • 75
  • Can you share some code demonstrating what you're trying to do? There are several methods on the PrincipalCollection interface that allow access to the individual principals. Are they not doing what you want? – jbunting Jul 20 '12 at 16:52

1 Answers1

5

There is no need two add multiple principles for this purpose. You can create a simple object (POJO) containing all the information you need and use it as the only principle.

public class MyRealm extends JdbcRealm {

...
enter code here


@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    SimpleAuthenticationInfo info = null;
    try {
        //GET USER INFO FROM DB etc. here
        MyPrinciple USER_OBJECT = new MyPrinciple();
        USER_OBJECT.setId(UUID);
        USER_OBJECT.setUsername(username);
        info = new SimpleAuthenticationInfo(USER_OBJECT, password.toCharArray(), getName());

    } catch (IOException | SQLException e) {
        logger.error(message, e);
        throw new AuthenticationException(message, e);
    }

    return info;
}

Then when you need the user info for the logged in user, you can simply call getPrinciple() and use its getter methods after casting it to your user class (POJO):

MyPrinciple LoggedInUser = (MyPrinciple ) SecurityUtils.getSubject().getPrinciple();
long uid = LoggedInUser.getId();
String username = LoggedInUser.getUsername();
salihcenap
  • 1,927
  • 22
  • 25