Search in sources :

Example 26 with PasswordEncoder

use of org.springframework.security.crypto.password.PasswordEncoder in project webofneeds by researchstudio-sat.

the class RestUserController method registerUser.

/**
 * Registers the specified user with password and an opional role.
 * Assumes values have already been checked for syntactic validity.
 * @param email
 * @param password
 * @param role
 * @throws UserAlreadyExistsException
 */
private void registerUser(String email, String password, String role) throws UserAlreadyExistsException {
    User user = userRepository.findByUsername(email);
    if (user != null) {
        throw new UserAlreadyExistsException();
    }
    try {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        user = new User(email, passwordEncoder.encode(password), role);
        user.setEmail(email);
        KeystorePasswordHolder keystorePassword = new KeystorePasswordHolder();
        // generate a password for the keystore and save it in the database, encrypted with a symmetric key
        // derived from the user's password
        keystorePassword.setPassword(KeystorePasswordUtils.generatePassword(KeystorePasswordUtils.KEYSTORE_PASSWORD_BYTES), password);
        // keystorePassword = keystorePasswordRepository.save(keystorePassword);
        // generate the keystore for the user
        KeystoreHolder keystoreHolder = new KeystoreHolder();
        try {
            // create the keystore if it doesnt exist yet
            keystoreHolder.getKeystore(keystorePassword.getPassword(password));
        } catch (Exception e) {
            throw new IllegalStateException("could not create keystore for user " + email);
        }
        // keystoreHolder = keystoreHolderRepository.save(keystoreHolder);
        user.setKeystorePasswordHolder(keystorePassword);
        user.setKeystoreHolder(keystoreHolder);
        userRepository.save(user);
    } catch (DataIntegrityViolationException e) {
        // username is already in database
        throw new UserAlreadyExistsException();
    }
}
Also used : User(won.owner.model.User) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) KeystoreHolder(won.owner.model.KeystoreHolder) UserAlreadyExistsException(won.owner.service.impl.UserAlreadyExistsException) KeystorePasswordHolder(won.owner.model.KeystorePasswordHolder) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) URISyntaxException(java.net.URISyntaxException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) UserAlreadyExistsException(won.owner.service.impl.UserAlreadyExistsException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException)

Example 27 with PasswordEncoder

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

the class SpringEncoderBuilder method tryCreatePasswordEncoder.

public void tryCreatePasswordEncoder(final Map<String, org.pac4j.core.credentials.password.PasswordEncoder> encoders) {
    for (int i = 0; i <= MAX_NUM_ENCODERS; i++) {
        final String type = getProperty(SPRING_ENCODER_TYPE, i);
        if (isNotBlank(type)) {
            final PasswordEncoder encoder;
            if (SpringEncoderType.NOOP.toString().equalsIgnoreCase(type)) {
                encoder = NoOpPasswordEncoder.getInstance();
            } else if (SpringEncoderType.BCRYPT.toString().equalsIgnoreCase(type)) {
                if (containsProperty(SPRING_ENCODER_BCRYPT_LENGTH, i)) {
                    encoder = new BCryptPasswordEncoder(getPropertyAsInteger(SPRING_ENCODER_BCRYPT_LENGTH, i));
                } else {
                    encoder = new BCryptPasswordEncoder();
                }
            } else if (SpringEncoderType.PBKDF2.toString().equalsIgnoreCase(type)) {
                if (containsProperty(SPRING_ENCODER_PBKDF2_SECRET, i)) {
                    final String secret = getProperty(SPRING_ENCODER_PBKDF2_SECRET, i);
                    if (containsProperty(SPRING_ENCODER_PBKDF2_ITERATIONS, i) && containsProperty(SPRING_ENCODER_PBKDF2_HASH_WIDTH, i)) {
                        encoder = new Pbkdf2PasswordEncoder(secret, getPropertyAsInteger(SPRING_ENCODER_PBKDF2_ITERATIONS, i), getPropertyAsInteger(SPRING_ENCODER_PBKDF2_HASH_WIDTH, i));
                    } else {
                        encoder = new Pbkdf2PasswordEncoder(secret);
                    }
                } else {
                    encoder = new Pbkdf2PasswordEncoder();
                }
            } else if (SpringEncoderType.SCRYPT.toString().equalsIgnoreCase(type)) {
                if (containsProperty(SPRING_ENCODER_SCRYPT_CPU_COST, i) && containsProperty(SPRING_ENCODER_SCRYPT_MEMORY_COST, i) && containsProperty(SPRING_ENCODER_SCRYPT_PARALLELIZATION, i) && containsProperty(SPRING_ENCODER_SCRYPT_KEY_LENGTH, i) && containsProperty(SPRING_ENCODER_SCRYPT_SALT_LENGTH, i)) {
                    encoder = new SCryptPasswordEncoder(getPropertyAsInteger(SPRING_ENCODER_SCRYPT_CPU_COST, i), getPropertyAsInteger(SPRING_ENCODER_SCRYPT_MEMORY_COST, i), getPropertyAsInteger(SPRING_ENCODER_SCRYPT_PARALLELIZATION, i), getPropertyAsInteger(SPRING_ENCODER_SCRYPT_KEY_LENGTH, i), getPropertyAsInteger(SPRING_ENCODER_SCRYPT_SALT_LENGTH, i));
                } else {
                    encoder = new SCryptPasswordEncoder();
                }
            } else if (SpringEncoderType.STANDARD.toString().equalsIgnoreCase(type)) {
                if (containsProperty(SPRING_ENCODER_STANDARD_SECRET, i)) {
                    encoder = new StandardPasswordEncoder(getProperty(SPRING_ENCODER_STANDARD_SECRET, i));
                } else {
                    encoder = new StandardPasswordEncoder();
                }
            } else {
                throw new TechnicalException("Unsupported spring encoder type: " + type);
            }
            encoders.put(concat(SPRING_ENCODER, i), new SpringSecurityPasswordEncoder(encoder));
        }
    }
}
Also used : StandardPasswordEncoder(org.springframework.security.crypto.password.StandardPasswordEncoder) TechnicalException(org.pac4j.core.exception.TechnicalException) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) Pbkdf2PasswordEncoder(org.springframework.security.crypto.password.Pbkdf2PasswordEncoder) SpringSecurityPasswordEncoder(org.pac4j.core.credentials.password.SpringSecurityPasswordEncoder) NoOpPasswordEncoder(org.springframework.security.crypto.password.NoOpPasswordEncoder) StandardPasswordEncoder(org.springframework.security.crypto.password.StandardPasswordEncoder) SCryptPasswordEncoder(org.springframework.security.crypto.scrypt.SCryptPasswordEncoder) SCryptPasswordEncoder(org.springframework.security.crypto.scrypt.SCryptPasswordEncoder) SpringSecurityPasswordEncoder(org.pac4j.core.credentials.password.SpringSecurityPasswordEncoder) Pbkdf2PasswordEncoder(org.springframework.security.crypto.password.Pbkdf2PasswordEncoder) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder)

Example 28 with PasswordEncoder

use of org.springframework.security.crypto.password.PasswordEncoder in project vaadin-jsf-integration by alejandro-du.

the class StartupListener method contextInitialized.

/**
 * {@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<>();
    }
    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());
    }
    // 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);
}
Also used : HashMap(java.util.HashMap) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) RememberMeAuthenticationProvider(org.springframework.security.authentication.RememberMeAuthenticationProvider) InputStream(java.io.InputStream) AuthenticationProvider(org.springframework.security.authentication.AuthenticationProvider) RememberMeAuthenticationProvider(org.springframework.security.authentication.RememberMeAuthenticationProvider) Attributes(java.util.jar.Attributes) IOException(java.io.IOException) Manifest(java.util.jar.Manifest) ApplicationContext(org.springframework.context.ApplicationContext) Random(java.util.Random) ProviderManager(org.springframework.security.authentication.ProviderManager) ServletContext(javax.servlet.ServletContext) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException)

Example 29 with PasswordEncoder

use of org.springframework.security.crypto.password.PasswordEncoder in project hub-alert by blackducksoftware.

the class PasswordEncoderSample method testEncodePassword.

@Test
public void testEncodePassword() {
    PasswordEncoder encoder = new BCryptPasswordEncoder(16);
    String encodedString = encoder.encode("replace_me_with_a_password_to_get_encoded_value");
    logger.debug("Encoded String: {}", encodedString);
}
Also used : BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) Test(org.junit.jupiter.api.Test)

Example 30 with PasswordEncoder

use of org.springframework.security.crypto.password.PasswordEncoder in project webofneeds by researchstudio-sat.

the class UserService method useRecoveryKey.

/**
 * Uses the recoveryKey to unlock the keystore password, then generates a new
 * keystore password and if that all works, changes the user's password and
 * deletes the recovery key.
 */
@Transactional(propagation = Propagation.REQUIRED)
public User useRecoveryKey(String username, String newPassword, String recoveryKey) throws UserNotFoundException, KeyStoreIOException, IncorrectPasswordException {
    logger.debug("using recoery key to reset password for user {}", username);
    PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    User user = getByUsernameWithKeystorePassword(username);
    if (user == null) {
        throw new UserNotFoundException("cannot change password: user not found");
    }
    KeystorePasswordHolder keystorePasswordHolder = user.getRecoverableKeystorePasswordHolder();
    String oldKeystorePassword = keystorePasswordHolder.getPassword(recoveryKey);
    logger.debug("re-encrypting keystore for user {} with new keystore password", username);
    String newKeystorePassword = changeKeystorePassword(user, oldKeystorePassword);
    user.setKeystorePasswordHolder(keystorePasswordHolder);
    user.getKeystorePasswordHolder().setPassword(newKeystorePassword, newPassword);
    // everything has worked so far, now we can also change the user's password
    user.setPassword(passwordEncoder.encode(newPassword));
    // we delete the recoverable keystore key as it will no longer work
    user.setRecoverableKeystorePasswordHolder(null);
    save(user);
    logger.debug("password changed for user {}", username);
    // persistent logins won't work any more as we changed the keystore password, so
    // let's delete them
    persistentLoginRepository.deleteByUsername(username);
    return user;
}
Also used : User(won.owner.model.User) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) ExpensiveSecureRandomString(won.protocol.util.ExpensiveSecureRandomString) KeystorePasswordHolder(won.owner.model.KeystorePasswordHolder) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) Transactional(org.springframework.transaction.annotation.Transactional)

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