org.apache.shiro.config.Ini Java Examples

The following examples show how to use org.apache.shiro.config.Ini. 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: ChainDefinitionSectionMetaSource.java    From dubai with MIT License 6 votes vote down vote up
public Ini.Section getObject() throws BeansException {

        //获取所有Resource
        Iterable<Resource> list = resourceRepository.findAll();

        Ini ini = new Ini();
        //加载默认的url
        ini.load(filterChainDefinitions);
        Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
        //循环Resource的url,逐个添加到section中。section就是filterChainDefinitionMap,
        //里面的键就是链接URL,值就是存在什么条件才能访问该链接
        for (Iterator<Resource> it = list.iterator(); it.hasNext(); ) {

            Resource resource = it.next();
            //如果不为空值添加到section中
            if (StringUtils.isNotEmpty(resource.getResource()) && StringUtils.isNotEmpty(resource.getPermission())) {
                section.put(resource.getResource(), MessageFormat.format(PERMISSION_STRING, resource.getPermission()));
            }

        }

        return section;
    }
 
Example #2
Source File: ChainDefinitionSectionMetaSource.java    From base-framework with Apache License 2.0 6 votes vote down vote up
@Override
public Section getObject() throws BeansException {
	Ini ini = new Ini();
       //加载默认的url
       ini.load(filterChainDefinitions);
       Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
       //循环数据库资源的url
       for (Resource resource : accountManager.getResources()) {
       	if(StringUtils.isNotEmpty(resource.getValue()) && StringUtils.isNotEmpty(resource.getPermission())) {
       		section.put(resource.getValue(), resource.getPermission());
       	}
       }
       
       //循环数据库组的url
       for (Group group : accountManager.getGroup(GroupType.RoleGorup)) {
       	if(StringUtils.isNotEmpty(group.getValue()) && StringUtils.isNotEmpty(group.getRole())) {
       		section.put(group.getValue(), group.getRole());
       	}
       }
       
       return section;
}
 
Example #3
Source File: AbstractThymeleafShiroDialectTest.java    From thymeleaf-extras-shiro with Apache License 2.0 6 votes vote down vote up
private static void setupShiro() {
    Ini ini = new Ini();
    Ini.Section usersSection = ini.addSection("users");

    usersSection.put(ALICE.email(), ALICE.roles());
    usersSection.put(BOB.email(), BOB.roles());
    usersSection.put(CAESAR.email(), CAESAR.roles());

    Ini.Section rolesSection = ini.addSection("roles");
    rolesSection.put(ROLE_A.label(), ROLE_A.permissions());
    rolesSection.put(ROLE_B.label(), ROLE_B.permissions());
    rolesSection.put(ROLE_C.label(), ROLE_C.permissions());
    rolesSection.put(ROLE_D.label(), ROLE_D.permissions());

    Factory<SecurityManager> factory = new TestIniSecurityManagerFactory(ini);
    SecurityManager secMgr = factory.getInstance();
    setSecurityManager(secMgr);
}
 
Example #4
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 #5
Source File: ShiroIniConverter.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
@Override
public Ini convert(String raw) {
  Ini ini;
  try {
    ini = Ini.fromResourcePath(raw);
  } catch (ConfigurationException e) {
    throw new ParameterException(getErrorString(raw, e.getMessage()), e);
  }

  Set<String> presentSections = ImmutableSortedSet.copyOf(ini.getSectionNames());
  if (presentSections.isEmpty()) {
    throw new MissingSectionsException();
  }

  Set<String> extraSections = Sets.difference(presentSections, ALLOWED_SECTION_NAMES);
  if (!extraSections.isEmpty()) {
    throw new ExtraSectionsException(extraSections);
  }

  return ini;
}
 
Example #6
Source File: PolicyFiles.java    From incubator-sentry with Apache License 2.0 6 votes vote down vote up
public static Ini loadFromPath(FileSystem fileSystem, Path path) throws IOException {
  InputStream inputStream = null;
  try {
    LOGGER.debug("Opening " + path);
    inputStream = fileSystem.open(path);
    Ini ini = new Ini();
    ini.load(inputStream);
    return ini;
  } finally {
    if(inputStream != null) {
      try {
        inputStream.close();
      } catch (IOException e) {
        LOGGER.warn("Error closing " + inputStream);
      }
    }
  }
}
 
Example #7
Source File: LocalGroupMappingService.java    From incubator-sentry with Apache License 2.0 6 votes vote down vote up
private void parseGroups(FileSystem fileSystem, Path resourcePath) throws IOException {
  Ini ini = PolicyFiles.loadFromPath(fileSystem, resourcePath);
  Section usersSection = ini.getSection(PolicyFileConstants.USERS);
  if (usersSection == null) {
    LOGGER.warn("No section " + PolicyFileConstants.USERS + " in the " + resourcePath);
    return;
  }
  for (Entry<String, String> userEntry : usersSection.entrySet()) {
    String userName = Strings.nullToEmpty(userEntry.getKey()).trim();
    String groupNames = Strings.nullToEmpty(userEntry.getValue()).trim();
    if (userName.isEmpty()) {
      LOGGER.error("Invalid user name in the " + resourcePath);
      continue;
    }
    if (groupNames.isEmpty()) {
      LOGGER.warn("No groups available for user " + userName +
          " in the " + resourcePath);
      continue;
    }
    Set<String> groupList = Sets.newHashSet(PolicyConstants.ROLE_SPLITTER.trimResults().split(
        groupNames));
    LOGGER.debug("Got user mapping: " + userName + ", Groups: " + groupNames);
    groupMap.put(userName, groupList);
  }
}
 
Example #8
Source File: SimpleFileProviderBackend.java    From incubator-sentry with Apache License 2.0 6 votes vote down vote up
private void parseIni(String database, Ini ini,
    List<? extends PrivilegeValidator> validators, Path policyPath,
    Table<String, String, Set<String>> groupRolePrivilegeTable) {
  Ini.Section privilegesSection = ini.getSection(PolicyFileConstants.ROLES);
  boolean invalidConfiguration = false;
  if (privilegesSection == null) {
    String errMsg = String.format("Section %s empty for %s", PolicyFileConstants.ROLES, policyPath);
    LOGGER.warn(errMsg);
    configErrors.add(errMsg);
    invalidConfiguration = true;
  }
  Ini.Section groupsSection = ini.getSection(PolicyFileConstants.GROUPS);
  if (groupsSection == null) {
    String warnMsg = String.format("Section %s empty for %s", PolicyFileConstants.GROUPS, policyPath);
    LOGGER.warn(warnMsg);
    configErrors.add(warnMsg);
    invalidConfiguration = true;
  }
  if (!invalidConfiguration) {
    parsePrivileges(database, privilegesSection, groupsSection, validators, policyPath,
        groupRolePrivilegeTable);
  }
}
 
Example #9
Source File: KnoxCLI.java    From knox with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param config - the shiro.ini config file created in topology deployment.
 * @return returns the Subject given by the shiro config's settings.
 */
protected Subject getSubject(Ini config) throws BadSubjectException {
  try {
    ThreadContext.unbindSubject();
    @SuppressWarnings("deprecation")
    Factory factory = new IniSecurityManagerFactory(config);
    org.apache.shiro.mgt.SecurityManager securityManager = (org.apache.shiro.mgt.SecurityManager) factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);
    Subject subject = SecurityUtils.getSubject();
    if( subject != null) {
      return subject;
    } else {
      out.println("Error Creating Subject from config at: " + config);
    }
  } catch (Exception e){
    out.println(e.toString());
  }
  throw new BadSubjectException("Subject could not be created with Shiro Config at " + config);
}
 
Example #10
Source File: ShiroAuthProvider.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
ShiroAuthProvider(AuthConfig authConfig,
                  Ini config,
                  Supplier<String> sessionIdGenerator,
                  Function<Session, CompletableFuture<Void>> loginSessionPropagator,
                  Function<String, CompletableFuture<Void>> logoutSessionPropagator) {
    requireNonNull(authConfig, "authConfig");
    requireNonNull(config, "config");
    requireNonNull(sessionIdGenerator, "sessionIdGenerator");
    requireNonNull(loginSessionPropagator, "loginSessionPropagator");
    requireNonNull(logoutSessionPropagator, "logoutSessionPropagator");

    final SecurityManager securityManager = createSecurityManager(config, sessionIdGenerator);
    final Duration sessionValidDuration = Duration.ofMillis(authConfig.sessionTimeoutMillis());

    loginApiService = new LoginService(securityManager, authConfig.loginNameNormalizer(),
                                       loginSessionPropagator, sessionValidDuration);
    logoutApiService = new LogoutService(securityManager, logoutSessionPropagator);
}
 
Example #11
Source File: ShiroAuthProvider.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
private static SecurityManager createSecurityManager(Ini config, Supplier<String> sessionIdGenerator) {
    final Factory<SecurityManager> factory = new IniSecurityManagerFactory(config) {
        @Override
        protected SecurityManager createDefaultInstance() {
            final DefaultSessionManager sessionManager = new DefaultSessionManager();
            // This session DAO is required to cache the session in a very short time, especially while
            // logging in to the Central Dogma server. After that, the general session manager provided
            // by Central Dogma server will be working for the session management.
            sessionManager.setSessionDAO(new LimitedMemorySessionDAO(sessionIdGenerator,
                                                                     64, Duration.ofHours(1)));

            final DefaultSecurityManager securityManager = new DefaultSecurityManager();
            securityManager.setSessionManager(sessionManager);

            return securityManager;
        }
    };
    return factory.getInstance();
}
 
Example #12
Source File: ShiroFilterChainDefinitions.java    From shiroDemo with Apache License 2.0 6 votes vote down vote up
public Ini.Section getObject() throws Exception {
    List<AuthcMap> list = this.getAuthService().getFilterChainDefinitions();
    Ini ini = new Ini();
    ini.load(this.getFilterChainDefinitions());
    Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
    for (AuthcMap map : list) {
        String s = null;
        switch (AuthcType.valueOf(map.getAuthcType())) {
            case roles:
                s = MessageFormat.format(ROLE_STRING, map.getVal());
                break;
            case perms:
                s = MessageFormat.format(PREMISSION_STRING, map.getVal());
                break;
            case authc:
                s = AuthcType.authc.name();
            case anon:
                s = AuthcType.anon.name();
            default:
                s = AuthcType.authc.name();
        }
        section.put(map.getUrl(), s);
    }
    return section;
}
 
Example #13
Source File: LoginResourceTest.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
@Test
public void testLogin() throws IOException {
  try (InputStream is = ResourceUtils.getInputStreamForPath("classpath:shiro.ini")) {
    Ini ini = new Ini();
    ini.load(is);
    new WebIniSecurityManagerFactory(ini).getInstance().authenticate(new UsernamePasswordToken("admin", "admin"));
  }
}
 
Example #14
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 #15
Source File: ShiroDialectTest.java    From thymeleaf-extras-shiro with Apache License 2.0 5 votes vote down vote up
private static void setupShiro() {
    Ini ini = new Ini();
    Ini.Section usersSection = ini.addSection("users");
    usersSection.put(USER1, PASS1 + ",rolea,roled");
    usersSection.put(USER2, PASS2 + ",roleb,rolec");
    usersSection.put(USER3, PASS3 + ",rolec,rolee");
    Ini.Section rolesSection = ini.addSection("roles");
    rolesSection.put("rolea", "*");
    rolesSection.put("roleb", "permtype1:permaction1:perminst1");
    rolesSection.put("rolec", "permtype1:permaction2:*");
    rolesSection.put("roled", "permtype3:*");
    Factory<SecurityManager> factory = new TestIniSecurityManagerFactory(ini);
    SecurityManager secMgr = factory.getInstance();
    setSecurityManager(secMgr);
}
 
Example #16
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 #17
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 #18
Source File: ShiroAuthProviderFactory.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private static Ini fromConfig(AuthConfig cfg) {
    try {
        final String iniPath = cfg.properties(String.class);
        return Ini.fromResourcePath(iniPath);
    } catch (Exception e) {
        throw new IllegalStateException("Failed to create " + Ini.class.getSimpleName(), e);
    }
}
 
Example #19
Source File: ShiroLoginAndLogoutTest.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(CentralDogmaBuilder builder) {
    builder.authProviderFactory(new ShiroAuthProviderFactory(unused -> {
        final Ini iniConfig = new Ini();
        iniConfig.addSection("users").put(USERNAME, PASSWORD);
        return iniConfig;
    }));
    builder.webAppEnabled(true);
}
 
Example #20
Source File: ChainDefinitionSectionMetaSource.java    From Autumn with GNU General Public License v2.0 5 votes vote down vote up
@Override
public synchronized Ini.Section getObject() throws Exception {

    //获取所有的插件
    List<Plugin> pluginList = pluginMapper.selectAllStatus1Plugin();

    //获取所有Resource
    List<Resource> list = resourceMapper.selectResourceAllList();

    Ini ini = new Ini();
    //加载默认的url
    ini.load(filterChainDefinitions);
    Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
    //循环Resource的url,逐个添加到section中。section就是filterChainDefinitionMap,
    //里面的键就是链接URL,值就是存在什么条件才能访问该链接
    for (Iterator<Resource> it = list.iterator(); it.hasNext();) {

        Resource resource = it.next();
        //如果不为空值添加到section中
        if(StringUtils.isNotEmpty(resource.getLink_address())) {
            section.put(resource.getLink_address(),  MessageFormat.format(PERMISSION_STRING,resource.getId()));
        }
    }

    for (Iterator<Plugin> iterator = pluginList.iterator(); iterator.hasNext();){
        Plugin plugin = iterator.next();
        if (StringUtils.isNotEmpty(plugin.getDir()) && StringUtils.isNotEmpty(plugin.getHtmlcurl())){
            section.put(plugin.getDir()+plugin.getHtmlcurl(), MessageFormat.format(PERMISSION_STRING,plugin.getId()));
        }
    }
    section.put("/**", "authc");
    logger.debug("the list of filter url:" + section.values() + "---Total:" +section.values().size());
    return section;
}
 
Example #21
Source File: ChainDefinitionSectionMetaSource.java    From Autumn with GNU General Public License v2.0 5 votes vote down vote up
@Override
public synchronized Ini.Section getObject() throws Exception {
    //获取所有Resource
    List<Resource> list = resourceMapper.selectResourceAllList();

    //获取所有的插件
    List<Plugin> pluginList = pluginMapper.selectAllStatus1Plugin();

    Ini ini = new Ini();
    //加载默认的url
    ini.load(filterChainDefinitions);
    Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
    //循环Resource的url,逐个添加到section中。section就是filterChainDefinitionMap,
    //里面的键就是链接URL,值就是存在什么条件才能访问该链接
    for (Iterator<Resource> it = list.iterator(); it.hasNext();) {

        Resource resource = it.next();
        //如果不为空值添加到section中
        if(StringUtils.isNotEmpty(resource.getLink_address())) {
            section.put(resource.getLink_address(),  MessageFormat.format(PERMISSION_STRING,resource.getId()));
        }
    }

    for (Iterator<Plugin> iterator = pluginList.iterator(); iterator.hasNext();){
        Plugin plugin = iterator.next();
        if (StringUtils.isNotEmpty(plugin.getDir()) && StringUtils.isNotEmpty(plugin.getHtmlcurl())){
            section.put(plugin.getDir()+plugin.getHtmlcurl(), MessageFormat.format(PERMISSION_STRING,plugin.getId()));
        }
    }
    section.put("/**", "authc");
    logger.debug("the list of filter url:" + section.values() + "---Total:" +section.values().size());
    return section;
}
 
Example #22
Source File: ChainDefinitionSectionMetaSource.java    From zhcc-server with Apache License 2.0 5 votes vote down vote up
@Override
public Section getObject() throws Exception {
	/*******************************************
	 * rest:例子/admins/user/**=rest[user],根据请求的方法,相当于/admins/user/**=perms[user:method]
	 * ,其中method为post,get,delete等。
	 * port:例子/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal://serverName:8081?queryString,
	 * 其中schmal是协议http或https等,serverName是你访问的host,8081是url配置里port的端口,queryString是你访问的url里的?后面的参数。
	 * perms:例子/admins/user/**=perms[user:add:*],perms参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,
	 * 例如/admins/user/**=perms["user:add:*,user:modify:*"],当有多个参数时必须每个参数都通过才通过,想当于isPermitedAll()方法。
	 * roles:例子/admins/user/**=roles[admin],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,当有多个参数时,
	 * 例如/admins/user/**=roles["admin,guest"],每个参数通过才算通过,相当于hasAllRoles()方法。
	 * anon:例子/admins/**=anon 没有参数,表示可以匿名使用。
	 * authc:例如/admins/user/**=authc表示需要认证才能使用,没有参数。
	 * authcBasic:例如/admins/user/**=authcBasic没有参数表示httpBasic认证。
	 * ssl:例子/admins/user/**=ssl没有参数,表示安全的url请求,协议为https
	 * user:例如/admins/user/**=user没有参数表示必须存在用户,当登入操作时不做检查。
	 *******************************************/
    //jwtAuthcFilter控制器用来做身份认证,用restfulPermissionFilter做restful权限验证。
	String restPermissionString = "jwtAuthcFilter,restfulPermissionFilter[{0}]";
	
	// 加载默认的url过滤定义
	Ini ini = new Ini();
	ini.load(this.filterChainDefinitions);
	Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);

	List<AvailableResourceDTO> dtoList = this.resourceService.listAllAvailable();
	// 将自定义url过滤添加到section中
	for (AvailableResourceDTO dto : dtoList) {
           if(dto.getCode() != null && !dto.getCode().trim().equals("")) {
               if(!section.containsKey(dto.getCode())) {
                   section.put(dto.getUrl(), MessageFormat.format(restPermissionString, dto.getCode()));
               }
           }
	}
	section.put("/**", "jwtAuthcFilter");
	return section;
}
 
Example #23
Source File: KnoxCLI.java    From knox with Apache License 2.0 5 votes vote down vote up
protected Subject getSubject(String config) throws ConfigurationException {
  Ini ini = new Ini();
  ini.loadFromPath(config);
  try {
    return getSubject(ini);
  } catch (BadSubjectException e) {
    throw new ConfigurationException("Could not get Subject with Ini at " + config);
  }
}
 
Example #24
Source File: KnoxCLI.java    From knox with Apache License 2.0 5 votes vote down vote up
/**
     *
     * @param t - topology configuration to use
     * @param config - the path to the shiro.ini file from the topology deployment.
     * @return - true/false whether LDAP successfully authenticated with system credentials.
     */
    protected boolean testSysBind(Topology t, String config) {
      boolean result = false;
      String username;
      char[] password;

      try {
//        Pull out contextFactory.url param for light shiro config
        Provider shiro = t.getProvider("authentication", "ShiroProvider");
        Map<String, String> params = shiro.getParams();
        String url = params.get("main.ldapRealm.contextFactory.url");

//        Build the Ini with minimum requirements
        Ini ini = new Ini();
        ini.addSection("main");
        ini.setSectionProperty("main", "ldapRealm", "org.apache.knox.gateway.shirorealm.KnoxLdapRealm");
        ini.setSectionProperty("main", "ldapContextFactory", "org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory");
        ini.setSectionProperty("main", "ldapRealm.contextFactory.url", url);

        username = getSystemUsername(t);
        password = getSystemPassword(t);
        result = authenticateUser(ini, new UsernamePasswordToken(username, password));
      } catch (MissingUsernameException | NoSuchProviderException | MissingPasswordException | NullPointerException e) {
        out.println(e.toString());
      }
      return result;
    }
 
Example #25
Source File: IniSecurityManagerService.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public void activateService()
        throws Exception
{
    configuration.refresh();
    ShiroIniConfiguration config = configuration.get();

    String iniResourcePath = config.iniResourcePath().get() == null
                             ? Shiro.DEFAULT_INI_RESOURCE_PATH
                             : config.iniResourcePath().get();

    setIni( Ini.fromResourcePath( iniResourcePath ) );
    securityManager = getInstance();

    if ( realmsRefs != null && realmsRefs.iterator().hasNext() ) {

        // Register Realms Services
        RealmSecurityManager realmSecurityManager = ( RealmSecurityManager ) securityManager;
        Collection<Realm> iniRealms = new ArrayList<>( realmSecurityManager.getRealms() );
        for ( ServiceReference<Realm> realmRef : realmsRefs ) {
            iniRealms.add( realmRef.get() );
            LOG.debug( "Realm Service '{}' registered!", realmRef.identity() );
        }
        realmSecurityManager.setRealms( iniRealms );

    }

    ThreadContext.bind( securityManager );
}
 
Example #26
Source File: LoginResourceLdapTest.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoginLdap() throws IOException {
  try (InputStream is = ResourceUtils.getInputStreamForPath("classpath:test-shiro-ldap.ini")) {
    Ini ini = new Ini();
    ini.load(is);
    int port = embeddedLdapRule.embeddedServerPort();
    ini.setSectionProperty("main", "ldapRealm.contextFactory.url", "ldap://localhost:" + port);
    new WebIniSecurityManagerFactory(ini).getInstance().authenticate(new UsernamePasswordToken("sclaus", "abcdefg"));
  }
}
 
Example #27
Source File: LoginResourceTest.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
@Test
public void testShiroConfig() throws IOException {
  try (InputStream is = ResourceUtils.getInputStreamForPath("classpath:shiro.ini")) {
    Ini ini = new Ini();
    ini.load(is);
    new WebIniSecurityManagerFactory(ini).getInstance();
  }
}
 
Example #28
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();
    }
 
Example #29
Source File: IniShiroRealmModule.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
IniShiroRealmModule(Ini ini, Class<? extends CredentialsMatcher> shiroCredentialsMatcher) {
  this(Optional.of(ini), Optional.of(shiroCredentialsMatcher));
}
 
Example #30
Source File: IniShiroRealmModule.java    From attic-aurora with Apache License 2.0 4 votes vote down vote up
private IniShiroRealmModule(Optional<Ini> ini,
    Optional<Class<? extends CredentialsMatcher>> shiroCredentialsMatcher) {
  this.ini = ini;
  this.shiroCredentialsMatcher = shiroCredentialsMatcher;
}