/** * authenticates a second user while the main user is already authenticated. The authentication information for the * second user are not stored in the security context but in Cibet context. A second authentication is necessary for * the Two-man-rule actuator. * * @param auth * Credentials of the second user * @throws AuthenticationException * in case of error */ public void logonSecondUser(Authentication auth) throws AuthenticationException { try { AuthenticationManager authManager = context.getBean(ProviderManager.class); Authentication result = authManager.authenticate(auth); Context.internalSessionScope().setSecondUser(result.getName()); Context.internalSessionScope().setProperty(InternalSessionScope.SECOND_PRINCIPAL, result); if (log.isDebugEnabled()) { log.debug("User " + result.getName() + " is successfully authenticated"); } } catch (NoSuchBeanDefinitionException e1) { String msg = "Failed to authenticate second user: " + "Failed to find a ProviderManager bean in Spring context. Configure Spring context correctly: " + e1.getMessage(); log.error(msg); throw new RuntimeException(msg, e1); } }
private void runUserSynchronizerJob() { if (LOG.isDebugEnabled()) { LOG.debug("Run user synchronizer job ..."); } long t = System.currentTimeMillis(); // JobDetail userSynchronizerJob = (JobDetail) // getSpringBean("userSynchronizerJob"); ProviderManager authenticationManager = (ProviderManager) getSpringBean("authenticationManager"); UserSynchronizerJob userSynchronizerJob = new UserSynchronizerJob(); userSynchronizerJob.setAuthenticationManager(authenticationManager); userSynchronizerJob.setStorageService((StorageService) getSpringBean("storageService")); userSynchronizerJob.syncUsers(); if (LOG.isDebugEnabled()) { t = System.currentTimeMillis() - t; LOG.debug("Users synchronized in " + t + " ms"); } }
@Bean("authenticationManager") public ProviderManager authenticationManager() { List<AuthenticationProvider> authProviderList = new ArrayList<AuthenticationProvider>(); authProviderList.add(authProvider()); ProviderManager providerManager = new ProviderManager(authProviderList); return providerManager; }
@Bean public AuthenticationManager clientAuthenticationManager() { DaoAuthenticationProvider clientAuthenticationProvider = new DaoAuthenticationProvider(); clientAuthenticationProvider.setUserDetailsService(clientDetailsUserDetailsService()); clientAuthenticationProvider.setHideUserNotFoundExceptions(false); return new ProviderManager(Collections.singletonList(clientAuthenticationProvider)); }
private UserDetails getUser() { ProviderManager parent = (ProviderManager) this.context .getBean(AuthenticationManager.class); DaoAuthenticationProvider provider = (DaoAuthenticationProvider) parent .getProviders().get(0); UserDetailsService service = (UserDetailsService) ReflectionTestUtils .getField(provider, "userDetailsService"); UserDetails user = service.loadUserByUsername("user"); return user; }
/** * @param identifier * Identifier of the provider to use. if <code>null</code> the next possible provider * will be used. * @return Get the provider, which is able to handle an invitation. */ public BaseCommunoteAuthenticationProvider getInvitationProvider(String identifier) { ProviderManager authenticationManager = getProviderManager(); // all providers to iterate for List<AuthenticationProvider> providers = new ArrayList<AuthenticationProvider>( authenticationManager.getProviders()); // also add the plugin providers // TODO far from perfect, it would be better to have them all in single list, but this means // moving the authentication provider stuff into the core List<CommunoteAuthenticationProvider> pluginProviders = ServiceLocator.instance() .getService(AuthenticationProviderManagement.class).getProviders(); providers.addAll(pluginProviders); for (Object object : providers) { if (!(object instanceof BaseCommunoteAuthenticationProvider)) { continue; } BaseCommunoteAuthenticationProvider provider = (BaseCommunoteAuthenticationProvider) object; if (provider.supportsUserQuerying() && (identifier == null || provider.getIdentifier().equals(identifier))) { return provider; } } throw new IllegalStateException("There is no provider that allows an invitation!"); }
/** * Iterates over the internal list of authentication providers an tries to authenticate. * * @param authentication * The authentication. * @return The resulting authentication. */ public Authentication authenticate(Authentication authentication) { ProviderManager providerManager = getManager(); if (providerManager != null) { try { return providerManager.authenticate(authentication); } catch (ProviderNotFoundException e) { // will be thrown if there is no supporting provider, ignore it since we are not // calling supports methods of the registered providers } } return null; }
/** * @return the lazily initialized manager or null if no providers are registered */ private ProviderManager getManager() { if (manager == null && !providers.isEmpty()) { initProviderManager(); } return manager; }
/** * @param alias * the alias * @param password * the password * @param email * the email * @throws Exception * in case of an error */ @BeforeClass(dependsOnGroups = "integration-test-setup") public void init() throws Exception { UserVO userVO = TestUtils.createKenmeiUserVO(TestUtils.createRandomUserAlias(), UserRole.ROLE_KENMEI_USER); userVO.setPassword("123456"); AuthenticationTestUtils.setManagerContext(); userManagement.createUser(userVO, false, false); Map<ClientConfigurationPropertyConstant, String> map; map = new HashMap<ClientConfigurationPropertyConstant, String>(); // set lower limit for getting permanently locked (to speed up test) map.put(ClientPropertySecurity.FAILED_AUTH_LIMIT_PERMLOCK, String.valueOf(6)); // set shorter wait time for temporarily locked users map.put(ClientPropertySecurity.FAILED_AUTH_LOCKED_TIMESPAN, String.valueOf(3)); CommunoteRuntime.getInstance().getConfigurationManager() .updateClientConfigurationProperties(map); AuthenticationTestUtils.setAuthentication(null); // initiate authenticationManager ArrayList<AuthenticationProvider> providers = new ArrayList<>(); providers.add(new DatabaseAuthenticationProvider()); ProviderManager providerManager = new ProviderManager(providers); providerManager.setAuthenticationEventPublisher(new AuthenticationFailedEventPublisher()); authManager = providerManager; // create valid user + password-token validAuth = new UsernamePasswordAuthenticationToken(userVO.getAlias(), userVO.getPassword()); // create invalid user + password-token invalidAuth = new UsernamePasswordAuthenticationToken(userVO.getAlias(), userVO.getPassword() + "invalid"); }
@Override public void configure(HttpSecurity http) throws Exception { PreAuthenticatedAuthenticationProvider casAuthenticationProvider = new PreAuthenticatedAuthenticationProvider(); casAuthenticationProvider.setPreAuthenticatedUserDetailsService( new UserDetailsByNameServiceWrapper<>(peticionamentoUserDetailService.orElseThrow(() -> SingularServerException.rethrow( String.format("Bean %s do tipo %s não pode ser nulo. Para utilizar a configuração de segurança %s é preciso declarar um bean do tipo %s identificado pelo nome %s .", UserDetailsService.class.getName(), "peticionamentoUserDetailService", SingularCASSpringSecurityConfig.class.getName(), UserDetailsService.class.getName(), "peticionamentoUserDetailService" )) ) ) ); ProviderManager authenticationManager = new ProviderManager(Arrays.asList(new AuthenticationProvider[]{casAuthenticationProvider})); J2eePreAuthenticatedProcessingFilter j2eeFilter = new J2eePreAuthenticatedProcessingFilter(); j2eeFilter.setAuthenticationManager(authenticationManager); http .regexMatcher(getContext().getPathRegex()) .httpBasic().authenticationEntryPoint(new Http403ForbiddenEntryPoint()) .and() .csrf().disable() .headers().frameOptions().sameOrigin() .and() .jee().j2eePreAuthenticatedProcessingFilter(j2eeFilter) .and() .authorizeRequests() .antMatchers(getContext().getContextPath()).authenticated(); }
@Bean @SuppressWarnings({ "rawtypes", "unchecked" }) public AuthenticationManager authenticationManager(){ if (authenticationManager == null){ List providers = new ArrayList(); providers.add(daoAuthenticationProvider()); providers.add(new AnonymousAuthenticationProvider("changeThis")); providers.add(new RememberMeAuthenticationProvider("changeThis")); ProviderManager bean = new ProviderManager(providers); authenticationManager = bean; } return authenticationManager; }
@Bean public AuthenticationManager authenticationManager(UserDetailsService userDetailsService, RunAsImplAuthenticationProvider runAsProvider, PasswordEncoder passwordEncoder) { List<AuthenticationProvider> providers = Lists.newArrayList(); providers.add(runAsProvider); DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); authenticationProvider.setUserDetailsService(userDetailsService); authenticationProvider.setPasswordEncoder(passwordEncoder); providers.add(authenticationProvider); return new ProviderManager(providers); }
@Bean @Override public AuthenticationManager authenticationManager() { PreAuthenticatedAuthenticationProvider authenticationProvider = new PreAuthenticatedAuthenticationProvider(); authenticationProvider.setPreAuthenticatedUserDetailsService(herdUserDetailsService); List<AuthenticationProvider> providers = new ArrayList<>(); providers.add(authenticationProvider); return new ProviderManager(providers); }
public void refreshContext(boolean ssoMode, String entityId) { LOG.info("Context refresh process started. SSO mode: {}", ssoMode); CONTEXT_REFRESH_IN_PROCESS = true; //for sso if(ssoMode) { // do not change order of context refreshes // we need to refresh root context otherwise springSecurityFilterChain will not be updated // https://jira.spring.io/browse/SPR-6228 XmlWebApplicationContext rootContext = (XmlWebApplicationContext) applicationContext.getParent(); rootContext.setConfigLocations("/WEB-INF/spring-security-saml.xml"); // add property entityId to root context, it will be used as psw for jks rootContext.getEnvironment().getPropertySources().addLast((new RefreshRootContextPropertySource(entityId))); rootContext.refresh(); // refresh application context applicationContext.setConfigLocations("/WEB-INF/spring-web-config.xml"); applicationContext.refresh(); // set userService property to userDetails bean, so we could manage users roles within ssoLogin mode applicationContext.getBean(SamlUserDetails.class).setUserService(applicationContext.getBean(UserService.class)); applicationContext.getBean(SAMLAuthenticationProviderImpl.class).setConfigurationMediator(applicationContext.getBean(ConfigurationMediator.class)); applicationContext.getBean(SAMLAuthenticationProviderImpl.class).setUserService(applicationContext.getBean(UserService.class)); } // for local authentication else { applicationContext.setConfigLocations("/WEB-INF/spring-web-config.xml", "/WEB-INF/spring-security-dynamoDB.xml"); applicationContext.refresh(); // clearing init auth providers ((ProviderManager)applicationContext.getBean("authenticationManager")).getProviders().clear(); // adding main auth provider ((ProviderManager)applicationContext.getBean("authenticationManager")).getProviders() .add((AuthenticationProvider) applicationContext.getBean("authProvider")); } LOG.info("Context refreshed successfully."); SecurityContextHolder.clearContext(); CONTEXT_REFRESH_IN_PROCESS = false; }
/** * Gets the provider manager. * * @return the provider manager */ @Bean(name = "authenticationManager") public ProviderManager getProviderManager() { List<AuthenticationProvider> providers = new ArrayList<>(); providers.add(getPreAuthenticatedAuthenticationProvider()); return new ProviderManager(providers); }
/** * @throws Exception */ @Test public final void testLogin() throws Exception { Authentication auth = new UsernamePasswordAuthenticationToken( username, pwd ); Authentication authentication = ( ( ProviderManager ) authenticationManager ).authenticate( auth ); assertTrue( authentication.isAuthenticated() ); }
@Test public final void testLoginNonexistentUser() throws Exception { Authentication auth = new UsernamePasswordAuthenticationToken( "bad user", "wrong password" ); try { ( ( ProviderManager ) authenticationManager ).authenticate( auth ); fail( "Should have gotten a bad credentials exception" ); } catch ( BadCredentialsException e ) { // } }
@Test public final void testLoginWrongPassword() throws Exception { Authentication auth = new UsernamePasswordAuthenticationToken( username, "wrong password" ); try { ( ( ProviderManager ) authenticationManager ).authenticate( auth ); fail( "Should have gotten a bad credentials exception" ); } catch ( BadCredentialsException e ) { // } }
/** * Grant authority to a test user, with admin privileges, and put the token in the context. This means your tests * will be authorized to do anything an administrator would be able to do. */ protected void grantAdminAuthority( ApplicationContext ctx ) { ProviderManager providerManager = ( ProviderManager ) ctx.getBean( "authenticationManager" ); providerManager.getProviders().add( new TestingAuthenticationProvider() ); // Grant all roles to test user. TestingAuthenticationToken token = new TestingAuthenticationToken( "administrator", "administrator", Arrays.asList( new GrantedAuthority[] { new SimpleGrantedAuthority( AuthorityConstants.ADMIN_GROUP_AUTHORITY ) } ) ); token.setAuthenticated( true ); putTokenInContext( token ); }
protected void grantAnonAuthority( ApplicationContext ctx ) { ProviderManager providerManager = ( ProviderManager ) ctx.getBean( "authenticationManager" ); providerManager.getProviders().add( new TestingAuthenticationProvider() ); // Grant all roles to test user. TestingAuthenticationToken token = new TestingAuthenticationToken( "anon", "anon", Arrays.asList( new GrantedAuthority[] { new SimpleGrantedAuthority( AuthorityConstants.IS_AUTHENTICATED_ANONYMOUSLY ) } ) ); token.setAuthenticated( true ); putTokenInContext( token ); }
@Bean(name = "preAuthAuthenticationManager") public AuthenticationManager preAuthAuthenticationManager() { PreAuthenticatedAuthenticationProvider preAuthProvider = new PreAuthenticatedAuthenticationProvider(); preAuthProvider.setPreAuthenticatedUserDetailsService(preAuthUserDetailsService); List<AuthenticationProvider> providers = new ArrayList<AuthenticationProvider>(); providers.add(preAuthProvider); return new ProviderManager(providers); }
@Bean(name = "preAuthAuthenticationManager") public AuthenticationManager preAuthAuthenticationManager() { PreAuthenticatedAuthenticationProvider preAuthProvider = new PreAuthenticatedAuthenticationProvider(); preAuthProvider.setPreAuthenticatedUserDetailsService(preAuthUserDetailsService()); return new ProviderManager(Arrays.asList(preAuthProvider)); }
@Override protected AuthenticationManager authenticationManager() throws Exception { return new ProviderManager(Arrays.asList(appAdminProvider, appHRProvider ), appAuthenticationMgr); }
@Bean @Override public AuthenticationManager authenticationManager() throws Exception { return new ProviderManager(Arrays.asList(authenticationProvider)); }
@Bean public AuthenticationManager authenticationManager() { return new ProviderManager(Arrays.asList(clientAuthenticationProvider(), userAuthenticationProvider())); }
@Bean public AuthenticationManager authenticationManager() { return new ProviderManager(Arrays.asList(new DaoAuthenticationProvider())); }
private void configureAuthenticationManager(AuthenticationManager manager) { if (manager instanceof ProviderManager) { ((ProviderManager) manager) .setAuthenticationEventPublisher(this.eventPublisher); } }
/** * @return the configured provider manager */ public ProviderManager getProviderManager() { ProviderManager authenticationManager = (ProviderManager) webApplicationContext .getBean("authenticationManager"); return authenticationManager; }
/** * Tests the correct ordering. */ @Test public void testCorrectOrder() { AuthenticationProviderManagement providerManagement = new AuthenticationProviderManagement(); List<AuthenticationProvider> providers = new ArrayList<AuthenticationProvider>(); StringBuilder stringToBuild = new StringBuilder(); providers.add(new TestAuthenticationProvider(0, "A", stringToBuild, false)); PluginAuthenticationProvider pluginAuthenticationProvider = new PluginAuthenticationProvider(); pluginAuthenticationProvider.setAuthenticationProviderManagement(providerManagement); providers.add(pluginAuthenticationProvider); providers.add(new TestAuthenticationProvider(0, "E", stringToBuild, true)); // Plugin providers. CommunoteAuthenticationProvider lowPriorityProvider = new TestAuthenticationProvider(0, "B", stringToBuild, true); CommunoteAuthenticationProvider midPriorityProvider = new TestAuthenticationProvider(500, "C", stringToBuild, true); CommunoteAuthenticationProvider noProvider = new TestAuthenticationProvider(1000, "Z", stringToBuild, false); ProviderManager providerManager = new ProviderManager(providers); // Test without filters providerManager.authenticate(new TestingAuthenticationToken(null, null)); Assert.assertEquals(stringToBuild.toString(), "E"); // Test with 1 additional filter stringToBuild.delete(0, 10); providerManagement.addAuthenticationProvider(lowPriorityProvider); providerManager.authenticate(new TestingAuthenticationToken(null, null)); Assert.assertEquals(stringToBuild.toString(), "B"); // Test with 2 additional filter (higher priority wins) stringToBuild.delete(0, 10); providerManagement.addAuthenticationProvider(midPriorityProvider); providerManager.authenticate(new TestingAuthenticationToken(null, null)); Assert.assertEquals(stringToBuild.toString(), "C"); // Test with 3 additional filter stringToBuild.delete(0, 10); providerManagement.addAuthenticationProvider(noProvider); providerManager.authenticate(new TestingAuthenticationToken(null, null)); Assert.assertEquals(stringToBuild.toString(), "C"); // Test with 2 additional filter stringToBuild.delete(0, 10); providerManagement.removeCommunoteAuthenticationProvider(midPriorityProvider); providerManager.authenticate(new TestingAuthenticationToken(null, null)); Assert.assertEquals(stringToBuild.toString(), "B"); }
@Bean @Override public AuthenticationManager authenticationManager() throws Exception { return new ProviderManager(Arrays.asList(provider)); }
@Bean public AuthenticationManager authenticationManager() { return new ProviderManager(Collections.singletonList(samlAuthenticationProvider())); }
@SuppressWarnings( { "unchecked" }) public void contextInitialized(ServletContextEvent event) { log.debug("initializing context..."); ServletContext context = event.getServletContext(); // Orion starts Servlets before Listeners, so check if the config // object already exists Map<String, Object> config = (HashMap<String, Object>) context .getAttribute(Constants.CONFIG); if (config == null) { config = new HashMap<String, Object>(); } if (context.getInitParameter(Constants.CSS_THEME) != null) { config.put(Constants.CSS_THEME, context .getInitParameter(Constants.CSS_THEME)); } ApplicationContext ctx = WebApplicationContextUtils .getRequiredWebApplicationContext(context); boolean encryptPassword = true; try { ProviderManager provider = (ProviderManager) ctx.getBean(ctx.getBeanNamesForType(ProviderManager.class)[0]); for (Object o : provider.getProviders()) { AuthenticationProvider p = (AuthenticationProvider) o; if (p instanceof RememberMeAuthenticationProvider) { config.put("rememberMeEnabled", Boolean.TRUE); } config.put(Constants.ENCRYPT_PASSWORD, Boolean.TRUE); config.put(Constants.ENC_ALGORITHM, "SHA"); } } catch (NoSuchBeanDefinitionException n) { log.debug("authenticationManager bean not found, assuming test and ignoring..."); // ignore, should only happen when testing } context.setAttribute(Constants.CONFIG, config); // output the retrieved values for the Init and Context Parameters if (log.isDebugEnabled()) { log .debug("Remember Me Enabled? " + config.get("rememberMeEnabled")); log.debug("Encrypt Passwords? " + encryptPassword); if (encryptPassword) { log.debug("Encryption Algorithm: " + config.get(Constants.ENC_ALGORITHM)); } log.debug("Populating drop-downs..."); } setupContext(context); }
/** * {@inheritDoc} */ @SuppressWarnings("unchecked") public void contextInitialized(ServletContextEvent event) { log.debug("Initializing context..."); ServletContext context = event.getServletContext(); // Orion starts Servlets before Listeners, so check if the config // object already exists Map<String, Object> config = (HashMap<String, Object>) context.getAttribute(Constants.CONFIG); if (config == null) { config = new HashMap<String, Object>(); } ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context); PasswordEncoder passwordEncoder = null; try { ProviderManager provider = (ProviderManager) ctx.getBean("org.springframework.security.authentication.ProviderManager#0"); for (Object o : provider.getProviders()) { AuthenticationProvider p = (AuthenticationProvider) o; if (p instanceof RememberMeAuthenticationProvider) { config.put("rememberMeEnabled", Boolean.TRUE); } else if (ctx.getBean("passwordEncoder") != null) { passwordEncoder = (PasswordEncoder) ctx.getBean("passwordEncoder"); } } } catch (NoSuchBeanDefinitionException n) { log.debug("authenticationManager bean not found, assuming test and ignoring..."); // ignore, should only happen when testing } context.setAttribute(Constants.CONFIG, config); // output the retrieved values for the Init and Context Parameters if (log.isDebugEnabled()) { log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled")); if (passwordEncoder != null) { log.debug("Password Encoder: " + passwordEncoder.getClass().getSimpleName()); } log.debug("Populating drop-downs..."); } setupContext(context); // Determine version number for CSS and JS Assets String appVersion = null; try { InputStream is = context.getResourceAsStream("/META-INF/MANIFEST.MF"); if (is == null) { log.warn("META-INF/MANIFEST.MF not found."); } else { Manifest mf = new Manifest(); mf.read(is); Attributes atts = mf.getMainAttributes(); appVersion = atts.getValue("Implementation-Version"); } } catch (IOException e) { log.error("I/O Exception reading manifest: " + e.getMessage()); } // If there was a build number defined in the war, then use it for // the cache buster. Otherwise, assume we are in development mode // and use a random cache buster so developers don't have to clear // their browser cache. if (appVersion == null || appVersion.contains("SNAPSHOT")) { appVersion = "" + new Random().nextInt(100000); } log.info("Application version set to: " + appVersion); context.setAttribute(Constants.ASSETS_VERSION, appVersion); }