shiro中自定义Realm的认证和授权信息

继承AuthorizingRealm 然后模拟数据库获取用户信息,和角色与权限信息


  /**
   * 模拟数据库或者缓存中用户信息
   */
  Map userMap = new HashMap<>(16);

  {
    userMap.put("wenzewen", "521314");
    super.setName("customRealm");
  }

  /**
   * 用来模拟获取数据库用户密码认证信息
   */
  private String getPasswordByUserName(String userNmae) {
    return userMap.get(userNmae);
  }

  /**
   * 模拟数据库存放权限信息
   */
  private Set getPermissionsByUserName(String userName) {
    Set sets = new HashSet<>();
    sets.add("update");
    sets.add("add");
    return sets;
  }

  /**
   * 模拟数据库存放角色信息
   */
  private Set getRolesByUserName(String userName) {
    Set sets = new HashSet<>();
    sets.add("admin");
    sets.add("user");
    return sets;
  }

  /**
   * 授权
   */
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    //1从主体传过来的授权信息中获取用户名
    String userName = (String) principalCollection.getPrimaryPrincipal();
    //2.通过用户名来获取数据库或者缓存中的角色数据
    Set roles = getRolesByUserName(userName);
    //3.通过用户名来获取数据库或者缓存中的权限数据
    Set permissions = getPermissionsByUserName(userName);

    SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
    simpleAuthorizationInfo.setRoles(roles);
    simpleAuthorizationInfo.setStringPermissions(permissions);

    return simpleAuthorizationInfo;
  }

  /**
   * 认证
   */
  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
      throws AuthenticationException {
    //1.从主体传过来的认证信息中获取用户名
    String userName = (String) authenticationToken.getPrincipal();
    //2.通过用户名导数据库中获取凭证
    String password = getPasswordByUserName(userName);
    if (password == null) {
      return null;
    }
    SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo("文泽稳",
        password, "customRealm");
    return simpleAuthenticationInfo;
  }

测试自定义Realm认证和授权

`` @Test
public void customerRealm() {
CustomerRealm customerRealm = new CustomerRealm();
//构建securityManager环境
final DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
defaultSecurityManager.setRealm(customerRealm);
//主体提交认证请求加入到securityManager环境 通过shiro的工具类SecurityUtils获取认证或授权的主体
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject = SecurityUtils.getSubject();
//模拟用户账号Token进行认证和授权
UsernamePasswordToken token = new UsernamePasswordToken(“wenzewen”, “521314”);
//登录
subject.login(token);
//登录认证成功校验true
System.out.println(subject.isAuthenticated());
//权限角色认证校验
subject.checkRoles(“admin”, “user”);
//shiro 权限认证
//subject.checkPermission(“user:select”);
subject.checkPermission(“update”);
subject.checkPermission(“add”);

}

你可能感兴趣的:(springboot,shiro)