gpt4 book ai didi

Apache Shiro 使用手册(四) Realm 实现

转载 作者:qq735679552 更新时间:2022-09-29 22:32:09 30 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章Apache Shiro 使用手册(四) Realm 实现由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

在认证、授权内部实现机制中都有提到,最终处理都将交给Real进行处理。因为在Shiro中,最终是通过Realm来获取应用程序中的用户、角色及权限信息的。通常情况下,在Realm中会直接从我们的数据源中获取Shiro需要的验证信息。可以说,Realm是专用于安全框架的DAO. 。

1、认证实现 。

正如前文所提到的,Shiro的认证过程最终会交由Realm执行,这时会调用Realm的getAuthenticationInfo(token)方法。 该方法主要执行以下操作: 1、检查提交的进行认证的令牌信息 2、根据令牌信息从数据源(通常为数据库)中获取用户信息 3、对用户信息进行匹配验证。 4、验证通过将返回一个封装了用户信息的AuthenticationInfo实例。 5、验证失败则抛出AuthenticationException异常信息.

而在我们的应用程序中要做的就是自定义一个Realm类,继承AuthorizingRealm抽象类,重载doGetAuthenticationInfo (),重写获取用户信息的方法.

  。

复制代码 代码如下:

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
  UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
  User user = accountManager.findUserByUserName(token.getUsername());
  if (user != null) {
   return new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), getName());
  } else {
   return null;
  }
}

  。

2、授权实现 。

而授权实现则与认证实现非常相似,在我们自定义的Realm中,重载doGetAuthorizationInfo()方法,重写获取用户权限的方法即可.

  。

复制代码 代码如下:

protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  String userName = (String) principals.fromRealm(getName()).iterator().next();
  User user = accountManager.findUserByUserName(userName);
  if (user != null) {
   SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
   for (Group group : user.getGroupList()) {
    info.addStringPermissions(group.getPermissionList());
   }
   return info;
  } else {
   return null;
  }
}

最后此篇关于Apache Shiro 使用手册(四) Realm 实现的文章就讲到这里了,如果你想了解更多关于Apache Shiro 使用手册(四) Realm 实现的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com