@Bean PasswordAuthenticator passwordAuthenticator() { SshdShellProperties.Shell.Auth props = properties.getShell().getAuth(); switch (props.getAuthType()) { case SIMPLE: return new SimpleSshdPasswordAuthenticator(properties); case AUTH_PROVIDER: try { AuthenticationProvider authProvider = Objects.isNull(props.getAuthProviderBeanName()) ? appContext.getBean(AuthenticationProvider.class) : appContext.getBean(props.getAuthProviderBeanName(), AuthenticationProvider.class); return new AuthProviderSshdPasswordAuthenticator(authProvider); } catch (BeansException ex) { throw new IllegalArgumentException("Expected a default or valid AuthenticationProvider bean", ex); } default: throw new IllegalArgumentException("Invalid/Unsupported auth type"); } }
public OtpGeneratingAuthenticationProvider(AuthenticationProvider provider, Tokenstore tokenstore, LookupStrategy lookupStrategy, SendStrategy sendStrategy) { if (provider == null) { throw new IllegalArgumentException("Embedded authentication provider must not be null."); } if (tokenstore == null) { throw new IllegalArgumentException("Tokenstore must not be null."); } if (lookupStrategy == null) { throw new IllegalArgumentException("LookupStrategy must not be null."); } if (sendStrategy == null) { throw new IllegalArgumentException("SendStrategy must not be null."); } this.provider = provider; this.tokenstore = tokenstore; this.lookupStrategy = lookupStrategy; this.sendStrategy = sendStrategy; this.gen = new DefaultOtpGenerator(DEFAULT_OTP_LENGTH); }
@Test public void authenticatesWithAuthoritiesResolver() throws HodErrorException { final GrantedAuthoritiesResolver resolver = (tokenProxy1, combinedTokenInformation) -> ImmutableList.<GrantedAuthority>builder() .add(new SimpleGrantedAuthority("ROLE_1")) .add(new SimpleGrantedAuthority("ROLE_2")) .build(); final AuthenticationProvider provider = new HodAuthenticationProvider(tokenRepository, resolver, authenticationService, unboundTokenService); final Authentication authentication = provider.authenticate(new HodTokenAuthentication<>(combinedSsoToken)); assertThat(authentication.getAuthorities(), containsInAnyOrder( new SimpleGrantedAuthority("ROLE_1"), new SimpleGrantedAuthority("ROLE_2"), new HodApplicationGrantedAuthority(new ResourceName(APPLICATION_DOMAIN, APPLICATION_NAME)) )); }
@Test public void authenticatesWithUsernameResolver() throws HodErrorException { final Map<String, JsonNode> hodMetadata = ImmutableMap.<String, JsonNode>builder() .put("username", mock(JsonNode.class)) .put("manager", mock(JsonNode.class)) .build(); final Map<String, Serializable> outputMetadata = ImmutableMap.<String, Serializable>builder() .put("username", "fred") .put("manager", "penny") .build(); final AuthenticationProvider provider = new HodAuthenticationProvider( tokenRepository, USER_ROLE, authenticationService, unboundTokenService, userStoreUsersService, metadata -> new HodUserMetadata("fred", outputMetadata) ); when(userStoreUsersService.getUserMetadata(tokenProxy, new ResourceName(USERSTORE_DOMAIN, USERSTORE_NAME), USER_UUID)) .thenReturn(hodMetadata); final Authentication authentication = provider.authenticate(new HodTokenAuthentication<>(combinedSsoToken)); assertThat(authentication.getName(), is("fred")); }
@Test public void authenticatesWithAuthoritiesResolver() throws HodErrorException { when(authenticationService.getCombinedTokenInformation(combinedToken)).thenReturn(createCombinedTokenInformation(applicationAuthenticationUuid)); final GrantedAuthoritiesResolver resolver = (proxy, combinedTokenInformation) -> ImmutableList.<GrantedAuthority>builder() .add(new SimpleGrantedAuthority("ROLE_1")) .add(new SimpleGrantedAuthority("ROLE_2")) .build(); final AuthenticationProvider provider = new CookieHodAuthenticationProvider(tokenRepository, resolver, authenticationService, unboundTokenService); final Authentication authentication = provider.authenticate(new HodTokenAuthentication<>(combinedToken)); assertThat(authentication.getAuthorities(), containsInAnyOrder( new SimpleGrantedAuthority("ROLE_1"), new SimpleGrantedAuthority("ROLE_2"), new HodApplicationGrantedAuthority(new ResourceName(APPLICATION_DOMAIN, APPLICATION_NAME)) )); }
private AuthenticationProvider communityAuthenticationProvider() { final Role user = new Role.Builder() .setName(FindCommunityRole.USER.value()) .setPrivileges(Collections.singleton("login")) .build(); final Set<String> defaultRoles; if (defaultRolesProperty.isEmpty()) { defaultRoles = Collections.emptySet(); } else { defaultRoles = new HashSet<>(Arrays.asList(defaultRolesProperty.split(","))); } return new CommunityAuthenticationProvider( configService, userService, new Roles(Collections.singletonList(user)), Collections.singleton("login"), grantedAuthoritiesMapper, defaultRoles ); }
private Collection<? extends AuthenticationProvider> getProviders(){ Collection<? extends AuthenticationProvider> authenticationProviders = externalComponentInstanceProvider.getImplInstancesAnnotatedWith(CalendarSecurity.class, AuthenticationProvider.class); checkAuthenticationProviders(authenticationProviders); LOGGER.info("Found [{}] authentication provider implementations", authenticationProviders.size()); Collection<? extends SuccessfulAuthenticationListener> successfulAuthenticationListeners = getSuccessfulAuthenticationListeners(); LOGGER.info("Found [{}] successful authentication listener implementations", authenticationProviders.size()); List<AuthenticationProvider> result = new ArrayList<>(1); for(AuthenticationProvider authenticationProvider : authenticationProviders){ AuthenticationProvider authenticationProviderProxy = authenticationProviderProxyFactory.createProxyFor(authenticationProvider, successfulAuthenticationListeners); result.add(authenticationProviderProxy); } return result; }
public List<String> getRealms() { List<AuthenticationProvider> providers = authenticationManager.getProviders(); if (LOG.isDebugEnabled()) { LOG.debug("Found " + providers.size() + " authentication providers"); } List<String> realms = new ArrayList<String>(); for (AuthenticationProvider provider : providers) { if (provider instanceof ExternalAuthenticationProvider) { ExternalAuthenticationProvider externalProvider = (ExternalAuthenticationProvider) provider; realms.add(externalProvider.getRealm()); } else if (provider instanceof NextServerAuthenticationProvider) { realms.add(""); // default provider } } return realms; }
@Bean("authenticationManager") public ProviderManager authenticationManager() { List<AuthenticationProvider> authProviderList = new ArrayList<AuthenticationProvider>(); authProviderList.add(authProvider()); ProviderManager providerManager = new ProviderManager(authProviderList); return providerManager; }
@Bean public AuthenticationProvider authenticationProvider(UserRepository repository) { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setUserDetailsService(userDetailsService(repository)); provider.setPasswordEncoder(passwordEncoder()); return provider; }
@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { AuthenticationProvider[] providers = primaryAuthProviders(); for (AuthenticationProvider provider : providers) { auth = auth.authenticationProvider(provider); } auth.authenticationProvider(tokenProvider); }
@Bean(name = "clientAuthenticationProvider") public AuthenticationProvider clientAuthenticationProvider() { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setPasswordEncoder(new BCryptPasswordEncoder()); provider.setUserDetailsService(new ClientDetailsUserDetailsService(clientAuthenticationService)); return provider; }
@Bean public AuthenticationProvider userAuthenticationProvider() { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setPasswordEncoder(new BCryptPasswordEncoder()); provider.setUserDetailsService(accountAuthenticationService); return provider; }
@Bean public AuthenticationProvider authenticationProvider(){ ActiveDirectoryLdapAuthenticationProvider ap = new ActiveDirectoryLdapAuthenticationProvider( "corp.jbcpcalendar.com", "ldap://corp.jbcpcalendar.com/"); ap.setConvertSubErrorCodesToExceptions(true); return ap; }
@Override protected AuthenticationProvider getDelegate() { ActiveDirectoryConfig adConfig = authConfigRepository.findActiveDirectory(true) .orElseThrow(() -> new BadCredentialsException("Active Directory is not configured")); ActiveDirectoryLdapAuthenticationProvider adAuth = new ActiveDirectoryLdapAuthenticationProvider(adConfig.getDomain(), adConfig.getUrl(), adConfig.getBaseDn()); adAuth.setAuthoritiesMapper(new NullAuthoritiesMapper()); adAuth.setUserDetailsContextMapper(new DetailsContextMapper(ldapUserReplicator, adConfig.getSynchronizationAttributes())); return adAuth; }
@Bean AuthenticationProvider basicPasswordAuthProvider() { BasicPasswordAuthenticationProvider provider = new BasicPasswordAuthenticationProvider(); provider.setUserDetailsService(userDetailsService()); provider.setPasswordEncoder(new Md5PasswordEncoder()); return provider; }
public @Bean AuthenticationProvider inMemProvider() { DaoAuthenticationProvider dap = new DaoAuthenticationProvider(); dap.setPasswordEncoder(new BCryptPasswordEncoder()); dap.setUserDetailsService(new InMemoryUserDetailsManager(Collections.singletonList(new User("user", "test", Collections.singletonList(new SimpleGrantedAuthority("API_CLIENT")))))); return dap; }
public @Bean AuthenticationProvider inMemProvider() { DaoAuthenticationProvider dap = new DaoAuthenticationProvider(); //dap.setPasswordEncoder(new BCryptPasswordEncoder()); dap.setUserDetailsService(new InMemoryUserDetailsManager(Collections.singletonList(new User("user", "test", Collections.singletonList(new SimpleGrantedAuthority("API_CLIENT")))))); return dap; }
/** * {@inheritDoc} * <p> * If the name of the {@link AuthenticationProvider AuthenticationProvider} is defined as annotation property, this bean is assigned to * the {@link org.springframework.security.authentication.AuthenticationManager AuthenticationManager}. */ @Override public void configure(AuthenticationManagerBuilder auth) { if (StringUtils.hasText(authenticationProviderBean)) { AuthenticationProvider ap = beanFactory.getBean(authenticationProviderBean, AuthenticationProvider.class); auth.authenticationProvider(ap); } }
/** * This implementation provides an {@link HttpAuthenticationProvider HttpAuthenticationProvider}. * * @return An instance of HttpAuthenticationProvider */ public @Bean AuthenticationProvider httpAuthenticationProvider() { HttpAuthenticationProvider ap = new HttpAuthenticationProvider(new DefaultAuthenticationDelegate(authenticationUrl)); try { ap.setPasswordEncoder(beanFactory.getBean(PasswordEncoder.class)); } catch (BeansException e) { // no need to set en encoder .... can be optimized here } return ap; }
@Autowired public void registerGlobalAuthentication(AuthenticationManagerBuilder auth) throws Exception { if (StringUtils.hasText(authenticationProviderBean)) { AuthenticationProvider ap = beanFactory.getBean(authenticationProviderBean, AuthenticationProvider.class); auth.authenticationProvider(ap); } }
@Bean public AuthenticationProvider authenticationProvider() { if (properties.isSecurityEnabled() && sessionService() != null) { log.info("Using RbacAuthenticationProvider"); return new RbacAuthenticationProvider(sessionService()); } log.info("Using DefaultAuthenticationProvider"); return new DefaultAuthenticationProvider(); }
@Test public void shouldCreateRS256ConfigurerWithCustomAuthenticationProvider() throws Exception { AuthenticationProvider provider = mock(AuthenticationProvider.class); JwtWebSecurityConfigurer configurer = JwtWebSecurityConfigurer.forRS256("audience", "issuer", provider); assertThat(configurer, is(notNullValue())); assertThat(configurer.audience, is("audience")); assertThat(configurer.issuer, is("issuer")); assertThat(configurer.provider, is(notNullValue())); assertThat(configurer.provider, is(provider)); }
@Test public void shouldCreateHS256ConfigurerWithCustomAuthenticationProvider() throws Exception { AuthenticationProvider provider = mock(AuthenticationProvider.class); JwtWebSecurityConfigurer configurer = JwtWebSecurityConfigurer.forHS256("audience", "issuer", provider); assertThat(configurer, is(notNullValue())); assertThat(configurer.audience, is("audience")); assertThat(configurer.issuer, is("issuer")); assertThat(configurer.provider, is(notNullValue())); assertThat(configurer.provider, is(provider)); }
@Bean(name = "dbAuthenticationProvider") public AuthenticationProvider dbAuthenticationProvider() { CustomDaoAuthenticationProvider daoAuthenticationProvider = new CustomDaoAuthenticationProvider(); daoAuthenticationProvider.setUserDetailsService(userDetailsService()); daoAuthenticationProvider.setPasswordEncoder(passwordEncoder); return daoAuthenticationProvider; }
/** * Database authentication provider using BCrypt password encoder * * @return */ @Bean public AuthenticationProvider authenticationProvider() { DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(); daoAuthenticationProvider.setUserDetailsService(userDetailsService); daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder()); return daoAuthenticationProvider; }
/** * @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!"); }
/** * @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 public AuthenticationProvider daoAuthenticationProvider() { DaoAuthenticationProvider impl = new DaoAuthenticationProvider(); impl.setUserDetailsService(new UserServiceImpl()); impl.setHideUserNotFoundExceptions(false) ; return impl; }
@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); }
/** * Authenticate against the given external providers. * * @see edu.ur.ir.security.ExternalAuthenticationProvider#authenticate(org.springframework.security.Authentication) */ public Authentication authenticate(Authentication authentication) throws AuthenticationException { AuthenticationException ae = null; for( AuthenticationProvider provider : authenticationProviders) { try { // return out of loop as soon as authentication occurs if( provider.supports(authentication.getClass())) { Authentication auth = provider.authenticate(authentication); return auth; } } catch(AuthenticationException exception) { ae = exception; } } if( ae != null ) { throw ae; } else { throw new BadCredentialsException(messages.getMessage("ProviderManager.providerNotFound", authentication.getClass().getName())); } }
@Override public Collection<AuthenticationProvider> getAuthenticationProviders() { return Collections.singleton(new IdolPreAuthenticatedAuthenticationProvider( userService, grantedAuthoritiesMapper, Arrays.stream(preAuthenticatedRoles.split(",")) .map(FindCommunityRole::fromValue) .filter(role -> FindCommunityRole.ADMIN != role) .map(FindCommunityRole::value) .collect(Collectors.toSet()) )); }
@Test public void testRoleFiltering() { final Collection<AuthenticationProvider> authenticationProviders = reverseProxyIdolSecurityCustomizer.getAuthenticationProviders(); assertThat(authenticationProviders, hasSize(1)); final Authentication authentication = authenticationProviders.stream() .map(authenticationProvider -> authenticationProvider.authenticate(this.foreignAuthentication)) .findFirst() .orElseThrow(() -> new AssertionError("AuthenticationProvider did not authenticate")); assertThat(authentication.getAuthorities(), contains(authority("FindUser"), authority("FindBI"))); }
@Test public void testDefaultRoles() { final Collection<AuthenticationProvider> authenticationProviders = idolSecurityCustomizer.getAuthenticationProviders(); assertThat(authenticationProviders, hasSize(1)); final Authentication authentication = authenticationProviders.stream() .findFirst() .map(authenticationProvider -> authenticationProvider.authenticate(this.foreignAuthentication)) .orElseThrow(() -> new AssertionError("AuthenticationProvider did not authenticate")); assertThat(authentication.getAuthorities(), contains(authority("FindUser"))); }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { Authentication result = null; for(AuthenticationProvider delegate : delegates){ if(delegate.supports(authentication.getClass()) && (result = delegate.authenticate(authentication)) != null){ break; } } return result; }
@Override public boolean supports(Class<?> authentication) { for(AuthenticationProvider delegate : delegates){ if(delegate.supports(authentication)){ return true; } } return false; }