最近在看开涛老师讲的关于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" /> 能正确显示结果,说明此方法可行。
———————————————————————————————————————
6.18快到了,这里给各位开发朋友们推荐云服务器:
1核2G1M40G盘,59元/1年,
1核2G1M40G盘,179元/3年,
2核8G1M40G盘,279元/1年。
本文介绍了使用Apache Shiro框架进行权限管理的过程,特别是在登录验证后如何手动创建SimpleAuthenticationInfo对象并将其保存到session中,以便在JSP页面上正确显示用户名。

1433

被折叠的 条评论
为什么被折叠?



