org.apache.shiro.realm.Realm Java Examples

The following examples show how to use org.apache.shiro.realm.Realm. 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: FirstSuccessfulModularRealAuthenticatorTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testMultiRealmMultipleFailures() {
  UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("username", "password");

  Realm realmOne = mock(Realm.class);
  Realm realmTwo = mock(Realm.class);

  when(realmOne.supports(usernamePasswordToken)).thenReturn(true);
  when(realmTwo.supports(usernamePasswordToken)).thenReturn(true);

  when(realmOne.getAuthenticationInfo(usernamePasswordToken)).thenThrow(new IncorrectCredentialsException());
  when(realmTwo.getAuthenticationInfo(usernamePasswordToken)).thenThrow(new UnknownAccountException());

  try {
    firstSuccessfulModularRealmAuthenticator
        .doMultiRealmAuthentication(Lists.newArrayList(realmOne, realmTwo), usernamePasswordToken);
  }
  catch (NexusAuthenticationException e) {
    assertThat(e.getAuthenticationFailureReasons(), containsInAnyOrder(AuthenticationFailureReason.INCORRECT_CREDENTIALS, AuthenticationFailureReason.USER_NOT_FOUND));
  }
}
 
Example #2
Source File: RealmManagerImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Looks up registered {@link AuthorizingRealm}s, and clears their authz caches if they have it set.
 */
private void clearAuthzRealmCaches() {
  // NOTE: we don't need to iterate all the Sec Managers, they use the same Realms, so one is fine.
  Collection<Realm> realms = realmSecurityManager.getRealms();
  if (realms != null) {
    for (Realm realm : realms) {
      if (realm instanceof AuthorizingRealm) {
        Cache<Object, AuthorizationInfo> cache = ((AuthorizingRealm) realm).getAuthorizationCache();
        if (cache != null) {
          log.debug("Clearing cache: {}", cache);
          cache.clear();
        }
      }
    }
  }
}
 
Example #3
Source File: ShiroConfig.java    From spring-boot-starter-samples with Apache License 2.0 6 votes vote down vote up
@Bean
public Realm defRealm(ShiroPrincipalRepository defRepository,
		@Autowired(required = false) List<AuthorizingRealmListener> realmsListeners, ShiroBizProperties properties) {

	LoginAuthorizingRealm authzRealm = new LoginAuthorizingRealm();
	// 认证账号信息提供实现:认证信息、角色信息、权限信息;业务系统需要自己实现该接口
	//authzRealm.setRepository(defRepository);
	// 凭证匹配器:该对象主要做密码校验
	authzRealm.setCredentialsMatcher(new AllowAllCredentialsMatcher());
	// Realm 执行监听:实现该接口可监听认证失败和成功的状态,从而做业务系统自己的事情,比如记录日志
	authzRealm.setRealmsListeners(realmsListeners);
	// 缓存相关的配置:采用提供的默认配置即可
	authzRealm.setCachingEnabled(properties.isCachingEnabled());
	// 认证缓存配置:无状态情况不缓存认证信息
	authzRealm.setAuthenticationCachingEnabled(properties.isAuthenticationCachingEnabled());
	authzRealm.setAuthenticationCacheName(properties.getAuthenticationCacheName());
	// 授权缓存配置:无状态情况不缓存认证信息
	authzRealm.setAuthorizationCachingEnabled(properties.isAuthorizationCachingEnabled());
	authzRealm.setAuthorizationCacheName(properties.getAuthorizationCacheName());

	return authzRealm;
}
 
Example #4
Source File: ShiroConfig.java    From spring-boot-starter-samples with Apache License 2.0 6 votes vote down vote up
@Bean
public Realm defRealm(ShiroPrincipalRepository defRepository,
		@Autowired(required = false) List<AuthorizingRealmListener> realmsListeners, ShiroBizProperties properties) {

	LoginAuthorizingRealm authzRealm = new LoginAuthorizingRealm();
	// 认证账号信息提供实现:认证信息、角色信息、权限信息;业务系统需要自己实现该接口
	//authzRealm.setRepository(defRepository);
	// 凭证匹配器:该对象主要做密码校验
	authzRealm.setCredentialsMatcher(new AllowAllCredentialsMatcher());
	// Realm 执行监听:实现该接口可监听认证失败和成功的状态,从而做业务系统自己的事情,比如记录日志
	authzRealm.setRealmsListeners(realmsListeners);
	// 缓存相关的配置:采用提供的默认配置即可
	authzRealm.setCachingEnabled(properties.isCachingEnabled());
	// 认证缓存配置:无状态情况不缓存认证信息
	authzRealm.setAuthenticationCachingEnabled(properties.isAuthenticationCachingEnabled());
	authzRealm.setAuthenticationCacheName(properties.getAuthenticationCacheName());
	// 授权缓存配置:无状态情况不缓存认证信息
	authzRealm.setAuthorizationCachingEnabled(properties.isAuthorizationCachingEnabled());
	authzRealm.setAuthorizationCacheName(properties.getAuthorizationCacheName());

	return authzRealm;
}
 
Example #5
Source File: RealmManagerImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Looks up registered {@link AuthenticatingRealm}s, and clears their authc caches if they have it set.
 */
private void clearAuthcRealmCaches() {
  // NOTE: we don't need to iterate all the Sec Managers, they use the same Realms, so one is fine.
  Collection<Realm> realms = realmSecurityManager.getRealms();
  if (realms != null) {
    for (Realm realm : realms) {
      if (realm instanceof AuthenticatingRealm) {
        Cache<Object, AuthenticationInfo> cache = ((AuthenticatingRealm) realm).getAuthenticationCache();
        if (cache != null) {
          log.debug("Clearing cache: {}", cache);
          cache.clear();
        }
      }
    }
  }
}
 
Example #6
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 #7
Source File: SecurityInternalModuleUnitTest.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testProvider() {
    SecurityInternalModule.RealmProvider rp = new SecurityInternalModule.RealmProvider(new SecurityConfig());
    Injector i = mock(Injector.class);
    ShiroRealmAdapter adapter = new ShiroRealmAdapter();
    when(i.getInstance(ShiroRealmAdapter.class)).thenReturn(adapter);
    Set<Class<? extends org.seedstack.seed.security.Realm>> realmClasses = new HashSet<>();
    realmClasses.add(ConfigurationRealm.class);

    Whitebox.setInternalState(rp, "injector", i);
    Whitebox.setInternalState(rp, "realmClasses", realmClasses);

    Set<Realm> realms = rp.get();
    assertEquals(1, realms.size());
    assertEquals(adapter, realms.iterator().next());
}
 
Example #8
Source File: CachingTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testCacheClearing() throws Exception {
  SecuritySystem securitySystem = this.lookup(SecuritySystem.class);

  MockRealmB mockRealmB = (MockRealmB) this.lookup(Realm.class, "MockRealmB");

  // cache should be empty to start
  Assert.assertTrue(mockRealmB.getAuthorizationCache().keys().isEmpty());

  Assert.assertTrue(securitySystem.isPermitted(
      new SimplePrincipalCollection("jcool", mockRealmB.getName()), "test:heHasIt"));

  // now something will be in the cache, just make sure
  Assert.assertFalse(mockRealmB.getAuthorizationCache().keys().isEmpty());

  // now if we update a user the cache should be cleared
  User user = securitySystem.getUser("bburton", "MockUserManagerB");
  // different user, doesn't matter, in the future we should get a little more fine grained
  securitySystem.updateUser(user);

  // empty again
  Assert.assertTrue(mockRealmB.getAuthorizationCache().keys().isEmpty());
}
 
Example #9
Source File: JsetsModularRealmAuthenticator.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
	assertRealmsConfigured();
	List<Realm> realms = this.getRealms()
		.stream()
		.filter(realm -> {
				return realm.supports(authenticationToken);
		})
		.collect(toList());
	if (CollectionUtils.isEmpty(realms)) 
		throw new IllegalStateException("Configuration error:  No realms support token type:" + authenticationToken.getClass());
	
	if (realms.size() == 1) {
		return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
	} else {
		return doMultiRealmAuthentication(realms, authenticationToken);
	}
}
 
Example #10
Source File: FirstSuccessfulModularRealAuthenticatorTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testMultiRealmInvalidCredentials() {
  UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("username", "password");

  Realm realmOne = mock(Realm.class);
  Realm realmTwo = mock(Realm.class);

  when(realmOne.supports(usernamePasswordToken)).thenReturn(true);
  when(realmTwo.supports(usernamePasswordToken)).thenReturn(true);

  when(realmOne.getAuthenticationInfo(usernamePasswordToken)).thenThrow(new IncorrectCredentialsException());
  when(realmTwo.getAuthenticationInfo(usernamePasswordToken)).thenThrow(new IncorrectCredentialsException());

  try {
    firstSuccessfulModularRealmAuthenticator
        .doMultiRealmAuthentication(Lists.newArrayList(realmOne, realmTwo), usernamePasswordToken);
  }
  catch (NexusAuthenticationException e) {
    assertThat(e.getAuthenticationFailureReasons(), containsInAnyOrder(AuthenticationFailureReason.INCORRECT_CREDENTIALS));
  }
}
 
Example #11
Source File: RealmManagerImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Inject
public RealmManagerImpl(
    final BeanLocator beanLocator,
    final EventManager eventManager,
    final RealmConfigurationStore store,
    @Named("initial") final Provider<RealmConfiguration> defaults,
    final RealmSecurityManager realmSecurityManager,
    final Map<String, Realm> availableRealms)
{
  this.beanLocator = checkNotNull(beanLocator);
  this.eventManager = checkNotNull(eventManager);
  this.store = checkNotNull(store);
  log.debug("Store: {}", store);
  this.defaults = checkNotNull(defaults);
  log.debug("Defaults: {}", defaults);
  this.realmSecurityManager = checkNotNull(realmSecurityManager);
  this.availableRealms = checkNotNull(availableRealms);
}
 
Example #12
Source File: DefineModularRealmAuthenticator.java    From cms with Apache License 2.0 6 votes vote down vote up
/**
 * 调用单个realm执行操作
 *
 * @param realm
 * @param token
 * @return
 */
@Override
protected AuthenticationInfo doSingleRealmAuthentication(Realm realm, AuthenticationToken token) {
    // 如果该realms不支持(不能验证)当前token
    if (!realm.supports(token)) {
        throw new ShiroException("token 错误");
    }
    AuthenticationInfo info = null;
    try {
        info = realm.getAuthenticationInfo(token);

        if (info == null) {
            throw new ShiroException("token不存在!");
        }
    } catch (Exception e) {
        throw new ShiroException("用户名或者密码错误!");
    }
    return info;
}
 
Example #13
Source File: FirstSuccessfulModularRealAuthenticatorTest.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testSingleRealmFailureIsStillSuccessful() {
  UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("username", "password");

  Realm realmOne = mock(Realm.class);
  Realm realmTwo = mock(Realm.class);

  when(realmOne.supports(usernamePasswordToken)).thenReturn(true);
  when(realmTwo.supports(usernamePasswordToken)).thenReturn(true);

  when(realmOne.getAuthenticationInfo(usernamePasswordToken)).thenThrow(new IncorrectCredentialsException());
  when(realmTwo.getAuthenticationInfo(usernamePasswordToken)).thenReturn(new SimpleAccount());

  firstSuccessfulModularRealmAuthenticator
      .doMultiRealmAuthentication(Lists.newArrayList(realmOne, realmTwo), usernamePasswordToken);
}
 
Example #14
Source File: ShiroBundle.java    From dropwizard-shiro with Apache License 2.0 6 votes vote down vote up
/**
 * Create the Shiro filter. Overriding this method allows for complete customization of how Shiro is initialized.
 */
protected Filter createFilter(final T configuration) {
    ShiroConfiguration shiroConfig = narrow(configuration);
    final IniWebEnvironment shiroEnv = new IniWebEnvironment();
    shiroEnv.setConfigLocations(shiroConfig.iniConfigs());
    shiroEnv.init();

    AbstractShiroFilter shiroFilter = new AbstractShiroFilter() {
        @Override
        public void init() throws Exception {
            Collection<Realm> realms = createRealms(configuration);
            WebSecurityManager securityManager = realms.isEmpty()
                    ? shiroEnv.getWebSecurityManager()
                    : new DefaultWebSecurityManager(realms);
            setSecurityManager(securityManager);
            setFilterChainResolver(shiroEnv.getFilterChainResolver());
        }
    };
    return shiroFilter;
}
 
Example #15
Source File: DefaultUserHealthCheck.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected Result check() {
  if (!realmManager.isRealmEnabled(AuthenticatingRealmImpl.NAME)) {
    return Result.healthy();
  }

  Optional<Realm> realm = realmSecurityManager.getRealms().stream()
      .filter(r -> r.getName().equals(AuthenticatingRealmImpl.NAME)).findFirst();

  try {
    if (realm.map(r -> r.getAuthenticationInfo(new UsernamePasswordToken("admin", "admin123"))).isPresent()) {
      return Result.unhealthy(ERROR_MESSAGE);
    }
  }
  catch (AuthenticationException e) {
    log.trace("Unable to locate admin/admin123 user", e);
  }
  return Result.healthy();
}
 
Example #16
Source File: ShiroAutoConfiguration.java    From shiro-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Bean(name = "shiroFilter")
@DependsOn("securityManager")
@ConditionalOnMissingBean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultSecurityManager securityManager, Realm realm, ShiroFilterRegistry registry) {
	securityManager.setRealm(realm);

       Map<String, String> filterDef = swapKeyValue(properties.getFilterChainDefinitions());
       log.info("过虑器配置: {}", filterDef);
       log.info("自定义过虑器: {}", registry.getFilterMap());

	ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
	shiroFilter.setSecurityManager(securityManager);
	shiroFilter.setLoginUrl(properties.getLoginUrl());
	shiroFilter.setSuccessUrl(properties.getSuccessUrl());
	shiroFilter.setUnauthorizedUrl(properties.getUnauthorizedUrl());

	shiroFilter.setFilterChainDefinitionMap(filterDef);
       shiroFilter.getFilters().putAll(registry.getFilterMap());

	return shiroFilter;
}
 
Example #17
Source File: ShiroAutoConfiguration.java    From utils with Apache License 2.0 6 votes vote down vote up
@Bean(name = "mainRealm")
@ConditionalOnMissingBean(name = "mainRealm")
@ConditionalOnProperty(prefix = "shiro.realm.jdbc", name = "enabled", havingValue = "true")
@DependsOn(value = {"dataSource", "lifecycleBeanPostProcessor", "credentialsMatcher"})
public Realm jdbcRealm(DataSource dataSource, CredentialsMatcher credentialsMatcher) {
    JdbcRealm realm = new JdbcRealm();

    if (shiroJdbcRealmProperties.getAuthenticationQuery() != null) {
        realm.setAuthenticationQuery(shiroJdbcRealmProperties.getAuthenticationQuery());
    }
    if (shiroJdbcRealmProperties.getUserRolesQuery() != null) {
        realm.setUserRolesQuery(shiroJdbcRealmProperties.getUserRolesQuery());
    }
    if (shiroJdbcRealmProperties.getPermissionsQuery() != null) {
        realm.setPermissionsQuery(shiroJdbcRealmProperties.getPermissionsQuery());
    }
    if (shiroJdbcRealmProperties.getSalt() != null) {
        realm.setSaltStyle(shiroJdbcRealmProperties.getSalt());
    }
    realm.setPermissionsLookupEnabled(shiroJdbcRealmProperties.isPermissionsLookupEnabled());
    realm.setDataSource(dataSource);
    realm.setCredentialsMatcher(credentialsMatcher);

    return realm;
}
 
Example #18
Source File: ShiroConfig.java    From frpMgr with MIT License 6 votes vote down vote up
/**
 * 定义Shiro安全管理配置
 */
@Bean
public WebSecurityManager securityManager(AuthorizingRealm authorizingRealm,
		CasAuthorizingRealm casAuthorizingRealm, SessionManager sessionManager,
		CacheManager shiroCacheManager) {
	WebSecurityManager bean = new WebSecurityManager();
	Collection<Realm> realms = ListUtils.newArrayList();
	realms.add(authorizingRealm); // 第一个为权限授权控制类
	realms.add(casAuthorizingRealm);
	bean.setRealms(realms);
	bean.setSessionManager(sessionManager);
	bean.setCacheManager(shiroCacheManager);
	// 设置支持CAS的subjectFactory
	bean.setSubjectFactory(new CasSubjectFactory());
	return bean;
}
 
Example #19
Source File: ShiroTest.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
@Before
public void setupConfigs() throws Exception {
    authzConfig = getConfigurationAdmin()
            .getConfiguration("org.apache.aries.jax.rs.shiro.authorization");

    Hashtable<String, Object> table = new Hashtable<>();
    table.put("shiro.authz", TRUE);
    table.put(JAX_RS_EXTENSION_SELECT, "(shiro.authc=true)");
    authzConfig.update(table);

    authcConfig = getConfigurationAdmin()
            .getConfiguration("org.apache.aries.jax.rs.shiro.authentication");

    table = new Hashtable<>();
    table.put("shiro.authc", TRUE);
    authcConfig.update(table);

    realm = new SimpleAccountRealm();

    reg = bundleContext.registerService(Realm.class, realm, null);

    Thread.sleep(1000);
}
 
Example #20
Source File: ShiroBaseConfigure.java    From ueboot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 当用户的环境没有配置redisTemplate时则使用ehcache做缓存
 *
 * @param realm realm
 * @return DefaultWebSecurityManager
 */
@Bean
@Conditional(RedisDisabledCondition.class)
public DefaultWebSecurityManager webSecurityManager(Realm realm) {
    DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
    securityManager.setRealm(realm);
    //使用ehcache当缓存
    EhCacheManager cacheManager = new EhCacheManager();
    securityManager.setCacheManager(cacheManager);
    return securityManager;
}
 
Example #21
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 #22
Source File: ShiroBaseConfigure.java    From ueboot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 当用户的环境配置了redisTemplate时则使用Redis做缓存
 *
 * @param realm         realm
 * @param redisTemplate spring RedisTemplate
 * @return DefaultWebSecurityManager
 */
@Bean
@Conditional(RedisEnableCondition.class)
public DefaultWebSecurityManager defaultWebSecurityManager(Realm realm, RedisTemplate<Object, Object> redisTemplate) {
    DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
    securityManager.setRealm(realm);
    //使用自定义的Redis缓存实现,依赖redisTemplate,keyNamespace可以默认为空
    securityManager.setCacheManager(this.getCacheManager(redisTemplate));
    return securityManager;
}
 
Example #23
Source File: AonModularRealmAuthenticator.java    From bootshiro with MIT License 5 votes vote down vote up
@Override
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {

    assertRealmsConfigured();
    List<Realm> realms = this.getRealms()
            .stream()
            .filter(realm -> {
                return realm.supports(authenticationToken);
            })
            .collect(toList());
    return realms.size() == 1 ? this.doSingleRealmAuthentication(realms.iterator().next(), authenticationToken) : this.doMultiRealmAuthentication(realms, authenticationToken);

}
 
Example #24
Source File: SecurityInternalModule.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public Set<Realm> get() {
    if (realms == null) {
        realms = new HashSet<>();
        for (Class<? extends org.seedstack.seed.security.Realm> seedRealmClass : realmClasses) {
            ShiroRealmAdapter realmAdapter = injector.getInstance(ShiroRealmAdapter.class);
            realmAdapter.setRealm(injector.getInstance(seedRealmClass));

            if (securityConfiguration.cache().isEnabled()) {
                realmAdapter.setCachingEnabled(true);

                // Authentication cache
                realmAdapter.setAuthenticationCachingEnabled(
                        securityConfiguration.cache().authentication().isEnabled());
                String authenticationCacheName = securityConfiguration.cache().authentication().getName();
                if (!Strings.isNullOrEmpty(authenticationCacheName)) {
                    realmAdapter.setAuthenticationCacheName(authenticationCacheName);
                }

                // Authorization cache
                realmAdapter.setAuthorizationCachingEnabled(
                        securityConfiguration.cache().authorization().isEnabled());
                String authorizationCacheName = securityConfiguration.cache().authorization().getName();
                if (!Strings.isNullOrEmpty(authorizationCacheName)) {
                    realmAdapter.setAuthorizationCacheName(authorizationCacheName);
                }
            } else {
                realmAdapter.setCachingEnabled(false);
            }

            realms.add(realmAdapter);
        }
    }
    return realms;
}
 
Example #25
Source File: RealmManagerImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public List<SecurityRealm> getAvailableRealms() {
  return StreamSupport.stream(beanLocator.locate(Key.get(Realm.class, Named.class)).spliterator(), false)
      .map(entry -> {
        return new SecurityRealm(((Named) entry.getKey()).value(), entry.getDescription());
      }).sorted((a, b) -> a.getName().compareToIgnoreCase(b.getName())).collect(toList());
}
 
Example #26
Source File: ShiroConfiguration.java    From spring-boot-shiro with Apache License 2.0 5 votes vote down vote up
@Bean(name = "securityManager")
@DependsOn(value = {"cacheManager", "rememberMeManager", "mainRealm"})
public DefaultSecurityManager securityManager(Realm realm, RememberMeManager rememberMeManager,
                                              CacheManager cacheManager, SessionManager sessionManager) {
    DefaultSecurityManager sm = new DefaultWebSecurityManager();
    sm.setRealm(realm);
    sm.setCacheManager(cacheManager);
    sm.setSessionManager(sessionManager);
    sm.setRememberMeManager(rememberMeManager);
    return sm;
}
 
Example #27
Source File: ExceptionCatchingModularRealmAuthorizer.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Inject
public ExceptionCatchingModularRealmAuthorizer(final Collection<Realm> realms, 
                                               final Provider<RolePermissionResolver> rolePermissionResolverProvider)
{
  this.rolePermissionResolverProvider = rolePermissionResolverProvider;
  setRealms(realms);
}
 
Example #28
Source File: ShiroConfiguration.java    From utils with Apache License 2.0 5 votes vote down vote up
@Bean(name = "securityManager")
@DependsOn(value = {"cacheManager", "rememberMeManager", "mainRealm"})
public DefaultSecurityManager securityManager(Realm realm, RememberMeManager rememberMeManager, CacheManager cacheManager, SessionManager sessionManager) {
    DefaultSecurityManager sm = new DefaultWebSecurityManager();
    sm.setRealm(realm);
    sm.setCacheManager(cacheManager);
    sm.setSessionManager(sessionManager);
    sm.setRememberMeManager(rememberMeManager);

    return sm;
}
 
Example #29
Source File: LoginRestApi.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
private KnoxJwtRealm getJTWRealm() {
  Collection<Realm> realmsList = authenticationService.getRealmsList();
  if (realmsList != null) {
    for (Realm realm : realmsList) {
      if (realm instanceof KnoxJwtRealm) {
        return (KnoxJwtRealm) realm;
      }
    }
  }
  return null;
}
 
Example #30
Source File: LDAPAuthProvider.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public static Realm createRealm(JsonObject config) {
  JndiLdapRealm ldapRealm = new JndiLdapRealm();
  JndiLdapContextFactory factory = new JndiLdapContextFactory();
  String userDNTemplate = config.getString(LDAP_USER_DN_TEMPLATE_FIELD);
  if (userDNTemplate != null) {
    ldapRealm.setUserDnTemplate(userDNTemplate);
  }
  String url = config.getString(LDAP_URL);
  if (url != null) {
    factory.setUrl(url);
  }
  String authenticationMechanism = config.getString(LDAP_AUTHENTICATION_MECHANISM);
  if (authenticationMechanism != null) {
    factory.setAuthenticationMechanism(authenticationMechanism);
  }
  String contextFactoryClassName = config.getString(LDAP_CONTEXT_FACTORY_CLASS_NAME);
  if (contextFactoryClassName != null) {
    factory.setContextFactoryClassName(contextFactoryClassName);
  }
  boolean poolingEnabled = config.getBoolean(LDAP_POOLING_ENABLED, false);
  factory.setPoolingEnabled(poolingEnabled);
  String referral = config.getString(LDAP_REFERRAL);
  if (referral != null) {
    factory.setReferral(referral);
  }
  String systemUsername = config.getString(LDAP_SYSTEM_USERNAME);
  if (systemUsername != null) {
    factory.setSystemUsername(systemUsername);
  }
  String systemPassword = config.getString(LDAP_SYSTEM_PASSWORD);
  if (systemPassword != null) {
    factory.setSystemPassword(systemPassword);
  }
  ldapRealm.setContextFactory(factory);
  ldapRealm.init();
  return ldapRealm;
}