org.apache.shiro.realm.text.IniRealm Java Examples

The following examples show how to use org.apache.shiro.realm.text.IniRealm. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ShiroAuthenticationService.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
/**
 * Get matched roles.
 *
 * @return
 */
@Override
public List<String> getMatchedRoles() {
  List<String> rolesList = new ArrayList<>();
  try {
    Collection<Realm> realmsList = getRealmsList();
    if (realmsList != null) {
      for (Realm realm : realmsList) {
        String name = realm.getClass().getName();
        LOGGER.debug("RealmClass.getName: " + name);
        if (name.equals("org.apache.shiro.realm.text.IniRealm")) {
          rolesList.addAll(getRolesList((IniRealm) realm));
        } else if (name.equals("org.apache.zeppelin.realm.LdapRealm")) {
          rolesList.addAll(getRolesList((LdapRealm) realm));
        }
      }
    }
  } catch (Exception e) {
    LOGGER.error("Exception in retrieving Users from realms ", e);
  }
  return rolesList;
}
 
Example #2
Source File: IniShiroRealmModule.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
  if (ini.isPresent()) {
    bind(Ini.class).toInstance(ini.get());
  } else {
    addError("shiro.ini is required.");
  }

  if (shiroCredentialsMatcher.isPresent()) {
    bind(CredentialsMatcher.class).to(shiroCredentialsMatcher.get()).in(Singleton.class);
  } else {
    addError("shiro_credentials_matcher is required.");
  }

  ShiroUtils.addRealmBinding(binder()).to(IniRealm.class);
}
 
Example #3
Source File: ShiroAuthenticationService.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Inject
public ShiroAuthenticationService(ZeppelinConfiguration conf) throws Exception {
  LOGGER.info("ShiroAuthenticationService is initialized");
  this.conf = conf;
  if (conf.getShiroPath().length() > 0) {
    try {
      Collection<Realm> realms =
          ((DefaultWebSecurityManager) org.apache.shiro.SecurityUtils.getSecurityManager())
              .getRealms();
      if (realms.size() > 1) {
        Boolean isIniRealmEnabled = false;
        for (Realm realm : realms) {
          if (realm instanceof IniRealm && ((IniRealm) realm).getIni().get("users") != null) {
            isIniRealmEnabled = true;
            break;
          }
        }
        if (isIniRealmEnabled) {
          throw new Exception(
              "IniRealm/password based auth mechanisms should be exclusive. "
                  + "Consider removing [users] block from shiro.ini");
        }
      }
    } catch (UnavailableSecurityManagerException e) {
      LOGGER.error("Failed to initialise shiro configuration", e);
    }
  }
}
 
Example #4
Source File: ShiroAuthenticationService.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
/**
 * Get candidated users based on searchText
 *
 * @param searchText
 * @param numUsersToFetch
 * @return
 */
@Override
public List<String> getMatchedUsers(String searchText, int numUsersToFetch) {
  List<String> usersList = new ArrayList<>();
  try {
    Collection<Realm> realmsList = getRealmsList();
    if (realmsList != null) {
      for (Realm realm : realmsList) {
        String realClassName = realm.getClass().getName();
        LOGGER.debug("RealmClass.getName: " + realClassName);
        if (realClassName.equals("org.apache.shiro.realm.text.IniRealm")) {
          usersList.addAll(getUserList((IniRealm) realm));
        } else if (realClassName.equals("org.apache.zeppelin.realm.LdapGroupRealm")) {
          usersList.addAll(getUserList((JndiLdapRealm) realm, searchText, numUsersToFetch));
        } else if (realClassName.equals("org.apache.zeppelin.realm.LdapRealm")) {
          usersList.addAll(getUserList((LdapRealm) realm, searchText, numUsersToFetch));
        } else if (realClassName.equals("org.apache.zeppelin.realm.ActiveDirectoryGroupRealm")) {
          usersList.addAll(
              getUserList((ActiveDirectoryGroupRealm) realm, searchText, numUsersToFetch));
        } else if (realClassName.equals("org.apache.shiro.realm.jdbc.JdbcRealm")) {
          usersList.addAll(getUserList((JdbcRealm) realm));
        }
      }
    }
  } catch (Exception e) {
    LOGGER.error("Exception in retrieving Users from realms ", e);
  }
  return usersList;
}
 
Example #5
Source File: ShiroAuthenticationService.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
/** Function to extract users from shiro.ini. */
private List<String> getUserList(IniRealm r) {
  List<String> userList = new ArrayList<>();
  Map getIniUser = r.getIni().get("users");
  if (getIniUser != null) {
    Iterator it = getIniUser.entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry pair = (Map.Entry) it.next();
      userList.add(pair.getKey().toString().trim());
    }
  }
  return userList;
}
 
Example #6
Source File: ShiroAuthenticationService.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
/**
 * * Get user roles from shiro.ini.
 *
 * @param r
 * @return
 */
private List<String> getRolesList(IniRealm r) {
  List<String> roleList = new ArrayList<>();
  Map getIniRoles = r.getIni().get("roles");
  if (getIniRoles != null) {
    Iterator it = getIniRoles.entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry pair = (Map.Entry) it.next();
      roleList.add(pair.getKey().toString().trim());
    }
  }
  return roleList;
}
 
Example #7
Source File: IniShiroRealmModule.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Singleton
@Provides
public IniRealm providesIniReal(Ini providedIni,
    CredentialsMatcher providedShiroCredentialsMatcher) {
  IniRealm result = new IniRealm(providedIni);
  result.setCredentialsMatcher(providedShiroCredentialsMatcher);
  result.init();

  return result;
}
 
Example #8
Source File: HttpSecurityIT.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  ini = new Ini();
  credentialsMatcher = SimpleCredentialsMatcher.class;

  Ini.Section users = ini.addSection(IniRealm.USERS_SECTION_NAME);
  users.put(ROOT.getUserName(), COMMA_JOINER.join(ROOT.getPassword(), ADMIN_ROLE));
  users.put(WFARNER.getUserName(), COMMA_JOINER.join(WFARNER.getPassword(), ENG_ROLE));
  users.put(UNPRIVILEGED.getUserName(), UNPRIVILEGED.getPassword());
  users.put(
      BACKUP_SERVICE.getUserName(),
      COMMA_JOINER.join(BACKUP_SERVICE.getPassword(), BACKUP_ROLE));
  users.put(
      DEPLOY_SERVICE.getUserName(),
      COMMA_JOINER.join(DEPLOY_SERVICE.getPassword(), DEPLOY_ROLE));

  Ini.Section roles = ini.addSection(IniRealm.ROLES_SECTION_NAME);
  roles.put(ADMIN_ROLE, "*");
  roles.put(ENG_ROLE, "thrift.AuroraSchedulerManager:*");
  roles.put(BACKUP_ROLE, "thrift.AuroraAdmin:listBackups");
  roles.put(
      DEPLOY_ROLE,
      "thrift.AuroraSchedulerManager:killTasks:"
          + ADS_STAGING_JOB.getRole()
          + ":"
          + ADS_STAGING_JOB.getEnvironment()
          + ":"
          + ADS_STAGING_JOB.getName());

  auroraAdmin = createMock(AnnotatedAuroraAdmin.class);
  afterAuthCalls = new AtomicInteger();
}
 
Example #9
Source File: ShiroIniConverterTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoParseOptionalSections() {
  assertEquals(
      ImmutableSet.of(IniRealm.ROLES_SECTION_NAME),
      parser
          .convert(ShiroIniConverterTest.class.getResource(MISSING_SECTIONS_SHIRO_INI).toString())
          .getSectionNames());
}
 
Example #10
Source File: TestIniSecurityManagerFactory.java    From thymeleaf-extras-shiro with Apache License 2.0 5 votes vote down vote up
@Override
protected Realm createRealm(Ini ini) {
    //IniRealm realm = new IniRealm(ini); changed to support SHIRO-322
    IniRealm realm = new TestIniRealm();
    realm.setName(INI_REALM_NAME);
    realm.setIni(ini); //added for SHIRO-322
    return realm;
}
 
Example #11
Source File: ShiroAuthenticationService.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
/**
 * Return the roles associated with the authenticated user if any otherwise returns empty set.
 * TODO(prasadwagle) Find correct way to get user roles (see SHIRO-492)
 *
 * @return shiro roles
 */
@Override
public Set<String> getAssociatedRoles() {
  Subject subject = org.apache.shiro.SecurityUtils.getSubject();
  HashSet<String> roles = new HashSet<>();
  Map allRoles = null;

  if (subject.isAuthenticated()) {
    Collection<Realm> realmsList = getRealmsList();
    for (Realm realm : realmsList) {
      String name = realm.getClass().getName();
      if (name.equals("org.apache.shiro.realm.text.IniRealm")) {
        allRoles = ((IniRealm) realm).getIni().get("roles");
        break;
      } else if (name.equals("org.apache.zeppelin.realm.LdapRealm")) {
        try {
          AuthorizationInfo auth =
              ((LdapRealm) realm)
                  .queryForAuthorizationInfo(
                      new SimplePrincipalCollection(subject.getPrincipal(), realm.getName()),
                      ((LdapRealm) realm).getContextFactory());
          if (auth != null) {
            roles = new HashSet<>(auth.getRoles());
          }
        } catch (NamingException e) {
          LOGGER.error("Can't fetch roles", e);
        }
        break;
      } else if (name.equals("org.apache.zeppelin.realm.ActiveDirectoryGroupRealm")) {
        allRoles = ((ActiveDirectoryGroupRealm) realm).getListRoles();
        break;
      }
    }
    if (allRoles != null) {
      Iterator it = allRoles.entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        if (subject.hasRole((String) pair.getKey())) {
          roles.add((String) pair.getKey());
        }
      }
    }
  }
  return roles;
}
 
Example #12
Source File: Main.java    From tutorials with MIT License 4 votes vote down vote up
public static void main(String[] args) {

        IniRealm realm = new IniRealm();
        Ini ini = Ini.fromResourcePath(Main.class.getResource("/com/baeldung/shiro/permissions/custom/shiro.ini").getPath());
        realm.setIni(ini);
        realm.setPermissionResolver(new PathPermissionResolver());
        realm.init();
        SecurityManager securityManager = new DefaultSecurityManager(realm);

        SecurityUtils.setSecurityManager(securityManager);
        Subject currentUser = SecurityUtils.getSubject();

        if (!currentUser.isAuthenticated()) {
          UsernamePasswordToken token = new UsernamePasswordToken("paul.reader", "password4");
          token.setRememberMe(true);
          try {
              currentUser.login(token);
          } catch (UnknownAccountException uae) {
              log.error("Username Not Found!", uae);
          } catch (IncorrectCredentialsException ice) {
              log.error("Invalid Credentials!", ice);
          } catch (LockedAccountException lae) {
              log.error("Your Account is Locked!", lae);
          } catch (AuthenticationException ae) {
              log.error("Unexpected Error!", ae);
          }
        }

        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        if (currentUser.hasRole("admin")) {
            log.info("Welcome Admin");
        } else if(currentUser.hasRole("editor")) {
            log.info("Welcome, Editor!");
        } else if(currentUser.hasRole("author")) {
            log.info("Welcome, Author");
        } else {
            log.info("Welcome, Guest");
        }

        if(currentUser.isPermitted("/articles/drafts/new-article")) {
            log.info("You can access articles");
        } else {
            log.info("You cannot access articles!");
        }
        currentUser.logout();
    }