shiro中的<shiro:principal />标签的使用

来源:互联网 发布:淘宝辅助软件哪个最好 编辑:程序博客网 时间:2024/05/22 06:31

最近最近在看开涛老师讲的关于shiro的教程,看到JSP标签的时候,关于<shiro:principal property="username" />这种写法,是要把一个带有username属性的对象转换为Prinipal后保存在session中,才能在页面上正确显示结果的。由于开始学习,所以我用的是ini配置文件作为安全数据源的。在登录的方法中,调用了subject.login(token)后,还要手动利用principal和realmName构造SimpleAuthenticationInfo对象,其实这里的pricipal是一个Object,就是我们的带有username属性的实体对象,然后将SimpleAuthenticationInfo对象存放在session中。
代码如下:

try {            subject.login(token);   //获取realmSecurityManager对象,其包含了很多信息,比如配置文件里面的数据            RealmSecurityManager realmSecurityManager = (RealmSecurityManager) securityManager;            Collection<Realm> collection = realmSecurityManager.getRealms();            if (collection!=null && collection.size()>0){                Iterator iterator = collection.iterator();                while (iterator.hasNext()){                    Realm realm = (Realm)iterator.next();             //得到默认的数据源名称,虽然默认的为iniRealm,也可以通过程序获得                    String realmName = realm.getName();                    //自定义的实体对象                    User user = new User();                    user.setUsername(username);                    user.setPassword(password);                    //得到SimpleAuthenticationInfo对象                    SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,password,realmName);                    //通过源码分析在调用subject.login(token)后,会通过SubjectContext来保存到session,所以就直接复用了源码(DefaultSecurityManager类中)                    SubjectContext subjectContext = new DefaultSubjectContext();                    subjectContext.setAuthenticated(true);                    subjectContext.setAuthenticationToken(token);                    subjectContext.setAuthenticationInfo(info);                    if (subject != null) {                        subjectContext.setSubject(subject);                    }                   //此方法中进行保存                   realmSecurityManager.createSubject(subjectContext);                }            }        }catch (UnknownAccountException e){            error = "用户名不存在";        }catch (IncorrectCredentialsException e){            error = "用户名或密码错误";        }catch (AuthenticationException e){            error = "其他错误"+e.getMessage();        }

最后结果是在页面上标签<shiro:principal property="username" /> 能正确显示结果,说明此方法可行。

0 0
原创粉丝点击