Search in sources :

Example 36 with PasswordEncoder

use of org.springframework.security.crypto.password.PasswordEncoder in project BroadleafCommerce by BroadleafCommerce.

the class AdminSecurityServiceImpl method setupPasswordEncoder.

/**
 * <p>Sets either {@link #passwordEncoder} or {@link #passwordEncoderNew} based on the type of {@link #passwordEncoderBean}
 * in order to provide bean configuration backwards compatibility with the deprecated {@link org.springframework.security.authentication.encoding.PasswordEncoder PasswordEncoder} bean.
 *
 * <p>{@link #passwordEncoderBean} is set by the bean defined as "blPasswordEncoder".
 *
 * <p>This class will utilize either the new or deprecated PasswordEncoder type depending on which is not null.
 *
 * @throws NoSuchBeanDefinitionException if {@link #passwordEncoderBean} is null or not an instance of either PasswordEncoder
 */
@PostConstruct
protected void setupPasswordEncoder() {
    passwordEncoderNew = null;
    passwordEncoder = null;
    if (passwordEncoderBean instanceof PasswordEncoder) {
        passwordEncoderNew = (PasswordEncoder) passwordEncoderBean;
    } else if (passwordEncoderBean instanceof org.springframework.security.authentication.encoding.PasswordEncoder) {
        passwordEncoder = (org.springframework.security.authentication.encoding.PasswordEncoder) passwordEncoderBean;
    } else {
        throw new NoSuchBeanDefinitionException("No PasswordEncoder bean is defined");
    }
}
Also used : PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) PostConstruct(javax.annotation.PostConstruct)

Example 37 with PasswordEncoder

use of org.springframework.security.crypto.password.PasswordEncoder in project spring-security by spring-projects.

the class DaoAuthenticationProviderTests method IGNOREtestSec2056.

/**
 * This is an explicit test for SEC-2056. It is intentionally ignored since this test
 * is not deterministic and {@link #testUserNotFoundEncodesPassword()} ensures that
 * SEC-2056 is fixed.
 */
public void IGNOREtestSec2056() {
    UsernamePasswordAuthenticationToken foundUser = new UsernamePasswordAuthenticationToken("rod", "koala");
    UsernamePasswordAuthenticationToken notFoundUser = new UsernamePasswordAuthenticationToken("notFound", "koala");
    PasswordEncoder encoder = new BCryptPasswordEncoder(10, new SecureRandom());
    DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
    provider.setHideUserNotFoundExceptions(false);
    provider.setPasswordEncoder(encoder);
    MockUserDetailsServiceUserRod userDetailsService = new MockUserDetailsServiceUserRod();
    userDetailsService.password = encoder.encode((CharSequence) foundUser.getCredentials());
    provider.setUserDetailsService(userDetailsService);
    int sampleSize = 100;
    List<Long> userFoundTimes = new ArrayList<>(sampleSize);
    for (int i = 0; i < sampleSize; i++) {
        long start = System.currentTimeMillis();
        provider.authenticate(foundUser);
        userFoundTimes.add(System.currentTimeMillis() - start);
    }
    List<Long> userNotFoundTimes = new ArrayList<>(sampleSize);
    for (int i = 0; i < sampleSize; i++) {
        long start = System.currentTimeMillis();
        assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(notFoundUser));
        userNotFoundTimes.add(System.currentTimeMillis() - start);
    }
    double userFoundAvg = avg(userFoundTimes);
    double userNotFoundAvg = avg(userNotFoundTimes);
    assertThat(Math.abs(userNotFoundAvg - userFoundAvg) <= 3).withFailMessage("User not found average " + userNotFoundAvg + " should be within 3ms of user found average " + userFoundAvg).isTrue();
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) NoOpPasswordEncoder(org.springframework.security.crypto.password.NoOpPasswordEncoder) ArrayList(java.util.ArrayList) SecureRandom(java.security.SecureRandom) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder)

Example 38 with PasswordEncoder

use of org.springframework.security.crypto.password.PasswordEncoder in project spring-security by spring-projects.

the class DaoAuthenticationProviderTests method testUserNotFoundEncodesPassword.

// SEC-2056
@Test
public void testUserNotFoundEncodesPassword() throws Exception {
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("missing", "koala");
    PasswordEncoder encoder = mock(PasswordEncoder.class);
    given(encoder.encode(anyString())).willReturn("koala");
    DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
    provider.setHideUserNotFoundExceptions(false);
    provider.setPasswordEncoder(encoder);
    provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
    provider.afterPropertiesSet();
    assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(token));
    // ensure encoder invoked w/ non-null strings since PasswordEncoder impls may fail
    // if encoded password is null
    verify(encoder).matches(isA(String.class), isA(String.class));
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) NoOpPasswordEncoder(org.springframework.security.crypto.password.NoOpPasswordEncoder) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.jupiter.api.Test)

Example 39 with PasswordEncoder

use of org.springframework.security.crypto.password.PasswordEncoder in project spring-security by spring-projects.

the class DaoAuthenticationProviderTests method testUserNotFoundNullCredentials.

@Test
public void testUserNotFoundNullCredentials() {
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("missing", null);
    PasswordEncoder encoder = mock(PasswordEncoder.class);
    DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
    provider.setHideUserNotFoundExceptions(false);
    provider.setPasswordEncoder(encoder);
    provider.setUserDetailsService(new MockUserDetailsServiceUserRod());
    assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> provider.authenticate(token));
    verify(encoder, times(0)).matches(anyString(), anyString());
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) NoOpPasswordEncoder(org.springframework.security.crypto.password.NoOpPasswordEncoder) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) Test(org.junit.jupiter.api.Test)

Example 40 with PasswordEncoder

use of org.springframework.security.crypto.password.PasswordEncoder in project spring-security by spring-projects.

the class User method withDefaultPasswordEncoder.

/**
 * <p>
 * <b>WARNING:</b> This method is considered unsafe for production and is only
 * intended for sample applications.
 * </p>
 * <p>
 * Creates a user and automatically encodes the provided password using
 * {@code PasswordEncoderFactories.createDelegatingPasswordEncoder()}. For example:
 * </p>
 *
 * <pre>
 * <code>
 * UserDetails user = User.withDefaultPasswordEncoder()
 *     .username("user")
 *     .password("password")
 *     .roles("USER")
 *     .build();
 * // outputs {bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG
 * System.out.println(user.getPassword());
 * </code> </pre>
 *
 * This is not safe for production (it is intended for getting started experience)
 * because the password "password" is compiled into the source code and then is
 * included in memory at the time of creation. This means there are still ways to
 * recover the plain text password making it unsafe. It does provide a slight
 * improvement to using plain text passwords since the UserDetails password is
 * securely hashed. This means if the UserDetails password is accidentally exposed,
 * the password is securely stored.
 *
 * In a production setting, it is recommended to hash the password ahead of time. For
 * example:
 *
 * <pre>
 * <code>
 * PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
 * // outputs {bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG
 * // remember the password that is printed out and use in the next step
 * System.out.println(encoder.encode("password"));
 * </code> </pre>
 *
 * <pre>
 * <code>
 * UserDetails user = User.withUsername("user")
 *     .password("{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG")
 *     .roles("USER")
 *     .build();
 * </code> </pre>
 * @return a UserBuilder that automatically encodes the password with the default
 * PasswordEncoder
 * @deprecated Using this method is not considered safe for production, but is
 * acceptable for demos and getting started. For production purposes, ensure the
 * password is encoded externally. See the method Javadoc for additional details.
 * There are no plans to remove this support. It is deprecated to indicate that this
 * is considered insecure for production purposes.
 */
@Deprecated
public static UserBuilder withDefaultPasswordEncoder() {
    logger.warn("User.withDefaultPasswordEncoder() is considered unsafe for production " + "and is only intended for sample applications.");
    PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
    return builder().passwordEncoder(encoder::encode);
}
Also used : PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder)

Aggregations

PasswordEncoder (org.springframework.security.crypto.password.PasswordEncoder)44 BCryptPasswordEncoder (org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder)24 NoOpPasswordEncoder (org.springframework.security.crypto.password.NoOpPasswordEncoder)10 Test (org.junit.jupiter.api.Test)9 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)7 KeystorePasswordHolder (won.owner.model.KeystorePasswordHolder)7 User (won.owner.model.User)7 SCryptPasswordEncoder (org.springframework.security.crypto.scrypt.SCryptPasswordEncoder)5 HashMap (java.util.HashMap)4 KeystoreHolder (won.owner.model.KeystoreHolder)4 ExpensiveSecureRandomString (won.protocol.util.ExpensiveSecureRandomString)4 IOException (java.io.IOException)3 Test (org.junit.Test)3 DataIntegrityViolationException (org.springframework.dao.DataIntegrityViolationException)3 UserDetails (org.springframework.security.core.userdetails.UserDetails)3 UserDetailsPasswordService (org.springframework.security.core.userdetails.UserDetailsPasswordService)3 UserDetailsService (org.springframework.security.core.userdetails.UserDetailsService)3 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)3 Pbkdf2PasswordEncoder (org.springframework.security.crypto.password.Pbkdf2PasswordEncoder)3 UserEntity (com.zavada.entity.UserEntity)2