问题
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?
回答1:
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();
来源:https://stackoverflow.com/questions/11580101/retrieving-shiro-principals