Shiro安全框架中 SecurityUtils.getSubject().getPrincipal() 获取用户登录信息

shiro 管理登录,获取登录信息的方式常用的是:


Subject sub = SecurityUtils.getSubject();

Object obj = sub.getPrincipal();

这里的 obj 是字符串,还是某个实体,取决于 ShiroRealm 类的设置值,代码如下:



@Override

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)

throws AuthenticationException {

System.out.println("获取登录者信息-->MyShiroRealm.doGetAuthenticationInfo()");

UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

String userS = token.getUsername();

 

User user = userService.findByName(userS);

if (user != null) {

LoginInfo info = new LoginInfo();

                    info.setName(user.getName());

                    info.setLoginId(user.getId);

return new SimpleAuthenticationInfo(info, user.getPassword(), getName());

}

return null;

}

如果像上面这样设置,读取登录信息就是



LoginInfo login = (LoginInfo) SecurityUtils.getSubject().getPrincipal();

如果设置登录信息的地方如下:



@Override

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)

throws AuthenticationException {

System.out.println("获取登录者信息-->MyShiroRealm.doGetAuthenticationInfo()");

UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

String userS = token.getUsername();

 

User user = userService.findByName(userS);

return new SimpleAuthenticationInfo(users, user.getPassword(), getName());

}

读取登录信息就是:



String loginName = (String) SecurityUtils.getSubject().getPrincipal();