Search in sources :

Example 1 with Realm

use of org.apache.shiro.realm.Realm in project zeppelin by apache.

the class SecurityRestApi method getUserList.

/**
   * Get userlist
   * Returns list of all user from available realms
   *
   * @return 200 response
   */
@GET
@Path("userlist/{searchText}")
public Response getUserList(@PathParam("searchText") final String searchText) {
    List<String> usersList = new ArrayList<>();
    List<String> rolesList = new ArrayList<>();
    try {
        GetUserList getUserListObj = new GetUserList();
        Collection realmsList = SecurityUtils.getRealmsList();
        if (realmsList != null) {
            for (Iterator<Realm> iterator = realmsList.iterator(); iterator.hasNext(); ) {
                Realm realm = iterator.next();
                String name = realm.getClass().getName();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("RealmClass.getName: " + name);
                }
                if (name.equals("org.apache.shiro.realm.text.IniRealm")) {
                    usersList.addAll(getUserListObj.getUserList((IniRealm) realm));
                    rolesList.addAll(getUserListObj.getRolesList((IniRealm) realm));
                } else if (name.equals("org.apache.zeppelin.realm.LdapGroupRealm")) {
                    usersList.addAll(getUserListObj.getUserList((JndiLdapRealm) realm, searchText));
                } else if (name.equals("org.apache.zeppelin.realm.LdapRealm")) {
                    usersList.addAll(getUserListObj.getUserList((LdapRealm) realm, searchText));
                    rolesList.addAll(getUserListObj.getRolesList((LdapRealm) realm));
                } else if (name.equals("org.apache.zeppelin.realm.ActiveDirectoryGroupRealm")) {
                    usersList.addAll(getUserListObj.getUserList((ActiveDirectoryGroupRealm) realm, searchText));
                } else if (name.equals("org.apache.shiro.realm.jdbc.JdbcRealm")) {
                    usersList.addAll(getUserListObj.getUserList((JdbcRealm) realm));
                }
            }
        }
    } catch (Exception e) {
        LOG.error("Exception in retrieving Users from realms ", e);
    }
    List<String> autoSuggestUserList = new ArrayList<>();
    List<String> autoSuggestRoleList = new ArrayList<>();
    Collections.sort(usersList);
    Collections.sort(rolesList);
    Collections.sort(usersList, new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            if (o1.matches(searchText + "(.*)") && o2.matches(searchText + "(.*)")) {
                return 0;
            } else if (o1.matches(searchText + "(.*)")) {
                return -1;
            }
            return 0;
        }
    });
    int maxLength = 0;
    for (String user : usersList) {
        if (StringUtils.containsIgnoreCase(user, searchText)) {
            autoSuggestUserList.add(user);
            maxLength++;
        }
        if (maxLength == 5) {
            break;
        }
    }
    for (String role : rolesList) {
        if (StringUtils.containsIgnoreCase(role, searchText)) {
            autoSuggestRoleList.add(role);
        }
    }
    Map<String, List> returnListMap = new HashMap<>();
    returnListMap.put("users", autoSuggestUserList);
    returnListMap.put("roles", autoSuggestRoleList);
    return new JsonResponse<>(Response.Status.OK, "", returnListMap).build();
}
Also used : IniRealm(org.apache.shiro.realm.text.IniRealm) JdbcRealm(org.apache.shiro.realm.jdbc.JdbcRealm) LdapRealm(org.apache.zeppelin.realm.LdapRealm) JndiLdapRealm(org.apache.shiro.realm.ldap.JndiLdapRealm) IniRealm(org.apache.shiro.realm.text.IniRealm) LdapRealm(org.apache.zeppelin.realm.LdapRealm) Realm(org.apache.shiro.realm.Realm) ActiveDirectoryGroupRealm(org.apache.zeppelin.realm.ActiveDirectoryGroupRealm) JdbcRealm(org.apache.shiro.realm.jdbc.JdbcRealm) JndiLdapRealm(org.apache.shiro.realm.ldap.JndiLdapRealm) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 2 with Realm

use of org.apache.shiro.realm.Realm in project zeppelin by apache.

the class SecurityUtils method getRoles.

/**
   * 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
   */
public static HashSet<String> getRoles() {
    if (!isEnabled) {
        return EMPTY_HASHSET;
    }
    Subject subject = org.apache.shiro.SecurityUtils.getSubject();
    HashSet<String> roles = new HashSet<>();
    Map allRoles = null;
    if (subject.isAuthenticated()) {
        Collection realmsList = SecurityUtils.getRealmsList();
        for (Iterator<Realm> iterator = realmsList.iterator(); iterator.hasNext(); ) {
            Realm realm = iterator.next();
            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")) {
                allRoles = ((LdapRealm) 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;
}
Also used : IniRealm(org.apache.shiro.realm.text.IniRealm) Subject(org.apache.shiro.subject.Subject) Iterator(java.util.Iterator) Collection(java.util.Collection) LdapRealm(org.apache.zeppelin.realm.LdapRealm) Map(java.util.Map) IniRealm(org.apache.shiro.realm.text.IniRealm) LdapRealm(org.apache.zeppelin.realm.LdapRealm) Realm(org.apache.shiro.realm.Realm) HashSet(java.util.HashSet)

Example 3 with Realm

use of org.apache.shiro.realm.Realm in project killbill by killbill.

the class ModularRealmAuthenticatorWith540 method doMultiRealmAuthentication.

/**
     * Performs the multi-realm authentication attempt by calling back to a {@link AuthenticationStrategy} object
     * as each realm is consulted for {@code AuthenticationInfo} for the specified {@code token}.
     *
     * @param realms the multiple realms configured on this Authenticator instance.
     * @param token  the submitted AuthenticationToken representing the subject's (user's) log-in principals and credentials.
     * @return an aggregated AuthenticationInfo instance representing account data across all the successfully
     * consulted realms.
     */
protected AuthenticationInfo doMultiRealmAuthentication(final Collection<Realm> realms, final AuthenticationToken token) {
    final AuthenticationStrategy strategy = getAuthenticationStrategy();
    AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token);
    if (log.isTraceEnabled()) {
        log.trace("Iterating through {} realms for PAM authentication", realms.size());
    }
    for (final Realm realm : realms) {
        aggregate = strategy.beforeAttempt(realm, token, aggregate);
        if (realm.supports(token)) {
            log.trace("Attempting to authenticate token [{}] using realm [{}]", token, realm);
            AuthenticationInfo info = null;
            Throwable t = null;
            try {
                info = realm.getAuthenticationInfo(token);
            } catch (final Throwable throwable) {
                t = throwable;
                if (log.isDebugEnabled()) {
                    final String msg = "Realm [" + realm + "] threw an exception during a multi-realm authentication attempt:";
                    log.debug(msg, t);
                }
            }
            aggregate = strategy.afterAttempt(realm, token, info, aggregate, t);
            if (strategy instanceof FirstSuccessfulStrategyWith540) {
                // check if we should check the next realm, or just stop here.
                if (!((FirstSuccessfulStrategyWith540) strategy).continueAfterAttempt(info, aggregate, t)) {
                    log.trace("Will not consult any other realms for authentication, last realm [{}].", realm);
                    break;
                }
            }
        } else {
            log.debug("Realm [{}] does not support token {}.  Skipping realm.", realm, token);
        }
    }
    aggregate = strategy.afterAllAttempts(token, aggregate);
    return aggregate;
}
Also used : FirstSuccessfulStrategyWith540(org.killbill.billing.server.security.FirstSuccessfulStrategyWith540) Realm(org.apache.shiro.realm.Realm) AuthenticationInfo(org.apache.shiro.authc.AuthenticationInfo)

Example 4 with Realm

use of org.apache.shiro.realm.Realm in project neo4j by neo4j.

the class EnterpriseSecurityModule method createPluginRealms.

private static List<PluginRealm> createPluginRealms(Config config, SecurityLog securityLog, SecureHasher secureHasher, SecurityConfig securityConfig) {
    List<PluginRealm> availablePluginRealms = new ArrayList<>();
    Set<Class> excludedClasses = new HashSet<>();
    if (securityConfig.pluginAuthentication && securityConfig.pluginAuthorization) {
        for (AuthPlugin plugin : Service.load(AuthPlugin.class)) {
            PluginRealm pluginRealm = new PluginRealm(plugin, config, securityLog, Clocks.systemClock(), secureHasher);
            availablePluginRealms.add(pluginRealm);
        }
    }
    if (securityConfig.pluginAuthentication) {
        for (AuthenticationPlugin plugin : Service.load(AuthenticationPlugin.class)) {
            PluginRealm pluginRealm;
            if (securityConfig.pluginAuthorization && plugin instanceof AuthorizationPlugin) {
                // This plugin implements both interfaces, create a combined plugin
                pluginRealm = new PluginRealm(plugin, (AuthorizationPlugin) plugin, config, securityLog, Clocks.systemClock(), secureHasher);
                // We need to make sure we do not add a duplicate when the AuthorizationPlugin service gets loaded
                // so we allow only one instance per combined plugin class
                excludedClasses.add(plugin.getClass());
            } else {
                pluginRealm = new PluginRealm(plugin, null, config, securityLog, Clocks.systemClock(), secureHasher);
            }
            availablePluginRealms.add(pluginRealm);
        }
    }
    if (securityConfig.pluginAuthorization) {
        for (AuthorizationPlugin plugin : Service.load(AuthorizationPlugin.class)) {
            if (!excludedClasses.contains(plugin.getClass())) {
                availablePluginRealms.add(new PluginRealm(null, plugin, config, securityLog, Clocks.systemClock(), secureHasher));
            }
        }
    }
    for (String pluginRealmName : securityConfig.pluginAuthProviders) {
        if (!availablePluginRealms.stream().anyMatch(r -> r.getName().equals(pluginRealmName))) {
            throw illegalConfiguration(format("Failed to load auth plugin '%s'.", pluginRealmName));
        }
    }
    List<PluginRealm> realms = availablePluginRealms.stream().filter(realm -> securityConfig.pluginAuthProviders.contains(realm.getName())).collect(Collectors.toList());
    boolean missingAuthenticatingRealm = securityConfig.onlyPluginAuthentication() && !realms.stream().anyMatch(PluginRealm::canAuthenticate);
    boolean missingAuthorizingRealm = securityConfig.onlyPluginAuthorization() && !realms.stream().anyMatch(PluginRealm::canAuthorize);
    if (missingAuthenticatingRealm || missingAuthorizingRealm) {
        String missingProvider = (missingAuthenticatingRealm && missingAuthorizingRealm) ? "authentication or authorization" : missingAuthenticatingRealm ? "authentication" : "authorization";
        throw illegalConfiguration(format("No plugin %s provider loaded even though required by configuration.", missingProvider));
    }
    return realms;
}
Also used : Service(org.neo4j.helpers.Service) Ticker(com.github.benmanes.caffeine.cache.Ticker) EnterpriseSecurityContext(org.neo4j.kernel.enterprise.api.security.EnterpriseSecurityContext) DatabaseManagementSystemSettings(org.neo4j.dbms.DatabaseManagementSystemSettings) EnterpriseAuthManager(org.neo4j.kernel.enterprise.api.security.EnterpriseAuthManager) LogProvider(org.neo4j.logging.LogProvider) AuthenticationPlugin(org.neo4j.server.security.enterprise.auth.plugin.spi.AuthenticationPlugin) JobScheduler(org.neo4j.kernel.impl.util.JobScheduler) LifeSupport(org.neo4j.kernel.lifecycle.LifeSupport) SecurityModule(org.neo4j.kernel.api.security.SecurityModule) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) SecuritySettings(org.neo4j.server.security.enterprise.configuration.SecuritySettings) Realm(org.apache.shiro.realm.Realm) SetDefaultAdminCommand(org.neo4j.commandline.admin.security.SetDefaultAdminCommand) SecurityContext(org.neo4j.kernel.api.security.SecurityContext) SecurityLog(org.neo4j.server.security.enterprise.log.SecurityLog) SECURITY_CONTEXT(org.neo4j.kernel.api.proc.Context.SECURITY_CONTEXT) EnterpriseEditionSettings(org.neo4j.kernel.impl.enterprise.configuration.EnterpriseEditionSettings) RateLimitedAuthenticationStrategy(org.neo4j.server.security.auth.RateLimitedAuthenticationStrategy) Config(org.neo4j.kernel.configuration.Config) CommunitySecurityModule(org.neo4j.server.security.auth.CommunitySecurityModule) BasicPasswordPolicy(org.neo4j.server.security.auth.BasicPasswordPolicy) UserRepository(org.neo4j.server.security.auth.UserRepository) Set(java.util.Set) Collectors(java.util.stream.Collectors) File(java.io.File) KernelException(org.neo4j.kernel.api.exceptions.KernelException) String.format(java.lang.String.format) AuthorizationPlugin(org.neo4j.server.security.enterprise.auth.plugin.spi.AuthorizationPlugin) CacheManager(org.apache.shiro.cache.CacheManager) List(java.util.List) Procedures(org.neo4j.kernel.impl.proc.Procedures) PluginRealm(org.neo4j.server.security.enterprise.auth.plugin.PluginRealm) GraphDatabaseFacade(org.neo4j.kernel.impl.factory.GraphDatabaseFacade) Optional(java.util.Optional) FileUserRepository(org.neo4j.server.security.auth.FileUserRepository) AuthPlugin(org.neo4j.server.security.enterprise.auth.plugin.spi.AuthPlugin) Clocks(org.neo4j.time.Clocks) FileSystemAbstraction(org.neo4j.io.fs.FileSystemAbstraction) AuthPlugin(org.neo4j.server.security.enterprise.auth.plugin.spi.AuthPlugin) PluginRealm(org.neo4j.server.security.enterprise.auth.plugin.PluginRealm) ArrayList(java.util.ArrayList) AuthenticationPlugin(org.neo4j.server.security.enterprise.auth.plugin.spi.AuthenticationPlugin) AuthorizationPlugin(org.neo4j.server.security.enterprise.auth.plugin.spi.AuthorizationPlugin) HashSet(java.util.HashSet)

Example 5 with Realm

use of org.apache.shiro.realm.Realm in project neo4j by neo4j.

the class LdapCachingTest method setup.

@Before
public void setup() throws Throwable {
    SecurityLog securityLog = mock(SecurityLog.class);
    InternalFlatFileRealm internalFlatFileRealm = new InternalFlatFileRealm(new InMemoryUserRepository(), new InMemoryRoleRepository(), new BasicPasswordPolicy(), new RateLimitedAuthenticationStrategy(Clock.systemUTC(), 3), mock(JobScheduler.class), new InMemoryUserRepository(), new InMemoryUserRepository());
    testRealm = new TestRealm(getLdapConfig(), securityLog, new SecureHasher());
    List<Realm> realms = listOf(internalFlatFileRealm, testRealm);
    fakeTicker = new FakeTicker();
    authManager = new MultiRealmAuthManager(internalFlatFileRealm, realms, new ShiroCaffeineCache.Manager(fakeTicker::read, 100, 10), securityLog, false);
    authManager.init();
    authManager.start();
    authManager.getUserManager().newUser("mike", "123", false);
    authManager.getUserManager().newUser("mats", "456", false);
}
Also used : JobScheduler(org.neo4j.kernel.impl.util.JobScheduler) RateLimitedAuthenticationStrategy(org.neo4j.server.security.auth.RateLimitedAuthenticationStrategy) SecurityLog(org.neo4j.server.security.enterprise.log.SecurityLog) InMemoryUserRepository(org.neo4j.server.security.auth.InMemoryUserRepository) FakeTicker(com.google.common.testing.FakeTicker) BasicPasswordPolicy(org.neo4j.server.security.auth.BasicPasswordPolicy) Realm(org.apache.shiro.realm.Realm) Before(org.junit.Before)

Aggregations

Realm (org.apache.shiro.realm.Realm)16 SimplePrincipalCollection (org.apache.shiro.subject.SimplePrincipalCollection)6 DefaultSecurityManager (org.apache.shiro.mgt.DefaultSecurityManager)5 IniRealm (org.apache.shiro.realm.text.IniRealm)4 Principal (java.security.Principal)3 ArrayList (java.util.ArrayList)3 AuthenticationInfo (org.apache.shiro.authc.AuthenticationInfo)3 AuthorizingRealm (org.apache.shiro.realm.AuthorizingRealm)3 LdapRealm (org.apache.zeppelin.realm.LdapRealm)3 Subject (ddf.security.Subject)2 HashSet (java.util.HashSet)2 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)2 AuthenticationToken (org.apache.shiro.authc.AuthenticationToken)2 Permission (org.apache.shiro.authz.Permission)2 PrincipalCollection (org.apache.shiro.subject.PrincipalCollection)2 DefaultWebSecurityManager (org.apache.shiro.web.mgt.DefaultWebSecurityManager)2 Before (org.junit.Before)2 Test (org.junit.Test)2 JobScheduler (org.neo4j.kernel.impl.util.JobScheduler)2 BasicPasswordPolicy (org.neo4j.server.security.auth.BasicPasswordPolicy)2