Retrieving Shiro Principals

元气小坏坏 提交于 2019-12-10 17:14:01

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!