Search in sources :

Example 1 with KeystoreHolder

use of won.owner.model.KeystoreHolder in project webofneeds by researchstudio-sat.

the class KeystoreEnabledPersistentRememberMeServices method processAutoLoginCookie.

@Transactional
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) {
    if (cookieTokens.length != 2) {
        throw new InvalidCookieException("Cookie token did not contain " + 2 + " tokens, but contained '" + Arrays.asList(cookieTokens) + "'");
    }
    final String presentedSeries = cookieTokens[0];
    final String presentedToken = cookieTokens[1];
    TransactionTemplate transactionTemplate = new TransactionTemplate(platformTransactionManager);
    return transactionTemplate.execute(new TransactionCallback<UserDetails>() {

        @Override
        public UserDetails doInTransaction(TransactionStatus status) {
            PersistentLogin persistentLogin = persistentLoginRepository.findOne(presentedSeries);
            if (persistentLogin == null) {
                // No series match, so we can't authenticate using this cookie
                throw new RememberMeAuthenticationException("No persistent token found for series id: " + presentedSeries);
            }
            // We have a match for this user/series combination
            if (!presentedToken.equals(persistentLogin.getToken())) {
                // Token doesn't match series value. Delete all logins for this user and throw
                // an exception to warn them.
                persistentLoginRepository.deleteByUsername(persistentLogin.getUsername());
                throw new CookieTheftException(messages.getMessage("PersistentTokenBasedRememberMeServices.cookieStolen", "Invalid remember-me token (Series/token) mismatch. Implies previous cookie theft attack."));
            }
            if (persistentLogin.getLastUsed().getTime() + getTokenValiditySeconds() * 1000L < System.currentTimeMillis()) {
                throw new RememberMeAuthenticationException("Remember-me login has expired");
            }
            // *same* series number.
            if (logger.isDebugEnabled()) {
                logger.debug("Refreshing persistent login token for user '" + persistentLogin.getUsername() + "', series '" + persistentLogin.getSeries() + "'");
            }
            // ------------- begin: added for WoN  -----------------------
            // fetch the password from the keystore_password table
            // using the value of the 'wonUnlock' coookie as key
            String unlockKey = extractUnlockCookie(request);
            if (unlockKey == null) {
                // we did not find the unlock cookie - something is wrong.
                throw new CookieTheftException("The rememberMe cookie was ok but no unlock cookie was found.");
            }
            KeystorePasswordHolder keystorePasswordHolder = persistentLogin.getKeystorePasswordHolder();
            String keystorePassword = keystorePasswordHolder.getPassword(unlockKey);
            // update the persistent login: new date, new token, and change unlock key for keystore password
            persistentLogin.setLastUsed(new Date());
            persistentLogin.setToken(generateTokenData());
            persistentLogin.setKeystorePasswordHolder(keystorePasswordHolder);
            String newUnlockKey = KeystorePasswordUtils.generatePassword(256);
            keystorePasswordHolder.setPassword(keystorePassword, newUnlockKey);
            try {
                persistentLoginRepository.save(persistentLogin);
                addCookies(persistentLogin, newUnlockKey, request, response);
            } catch (Exception e) {
                logger.error("Failed to update token: ", e);
                throw new RememberMeAuthenticationException("Autologin failed due to data access problem");
            }
            User userDetails = (User) getUserDetailsService().loadUserByUsername(persistentLogin.getUsername());
            KeystoreHolder keystoreHolder = userDetails.getKeystoreHolder();
            KeyStore keystore;
            try {
                keystore = keystoreHolder.getKeystore(keystorePassword);
            } catch (Exception e) {
                logger.error("Failed to load keystore: ", e);
                throw new RememberMeAuthenticationException("Autologin failed due to data access problem");
            }
            KeystoreEnabledUserDetails keystoreEnabledUserDetails = new KeystoreEnabledUserDetails((User) userDetails, keystore, keystorePassword);
            keystore = null;
            keystorePassword = null;
            return keystoreEnabledUserDetails;
        // delete the password
        }
    });
}
Also used : User(won.owner.model.User) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) PersistentLogin(won.owner.model.PersistentLogin) KeystorePasswordHolder(won.owner.model.KeystorePasswordHolder) KeyStore(java.security.KeyStore) Date(java.util.Date) RememberMeAuthenticationException(org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException) CookieTheftException(org.springframework.security.web.authentication.rememberme.CookieTheftException) InvalidCookieException(org.springframework.security.web.authentication.rememberme.InvalidCookieException) RememberMeAuthenticationException(org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException) InvalidCookieException(org.springframework.security.web.authentication.rememberme.InvalidCookieException) UserDetails(org.springframework.security.core.userdetails.UserDetails) CookieTheftException(org.springframework.security.web.authentication.rememberme.CookieTheftException) KeystoreHolder(won.owner.model.KeystoreHolder) Transactional(org.springframework.transaction.annotation.Transactional)

Example 2 with KeystoreHolder

use of won.owner.model.KeystoreHolder 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 3 with KeystoreHolder

use of won.owner.model.KeystoreHolder in project webofneeds by researchstudio-sat.

the class KeystoreEnabledDaoAuthenticationProvider method authenticate.

@Override
@Transactional
public Authentication authenticate(Authentication authentication) {
    String password = (String) authentication.getCredentials();
    String username = (String) authentication.getPrincipal();
    UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) super.authenticate(authentication);
    User user = (User) auth.getPrincipal();
    // can't use that object as it's detached. load the user again:
    user = userRepository.findOne(user.getId());
    KeystorePasswordHolder keystorePasswordHolder = user.getKeystorePasswordHolder();
    if (keystorePasswordHolder == null || keystorePasswordHolder.getEncryptedPassword() == null || keystorePasswordHolder.getEncryptedPassword().length() == 0) {
        keystorePasswordHolder = 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
        keystorePasswordHolder.setPassword(KeystorePasswordUtils.generatePassword(KeystorePasswordUtils.KEYSTORE_PASSWORD_BYTES), password);
        // keystorePasswordHolder = keystorePasswordRepository.save(keystorePasswordHolder);
        // generate the keystore for the user
        user.setKeystorePasswordHolder(keystorePasswordHolder);
    }
    String keystorePassword = keystorePasswordHolder.getPassword(password);
    KeystoreHolder keystoreHolder = user.getKeystoreHolder();
    KeyStore keystore = null;
    if (keystoreHolder == null || keystoreHolder.getKeystoreBytes() == null || keystoreHolder.getKeystoreBytes().length == 0) {
        // new user or legacy user that has no keystore yet: create keystoreHolder
        keystoreHolder = new KeystoreHolder();
        keystore = openOrCreateKeyStore(keystorePassword, auth.getName(), keystoreHolder);
        // keystoreHolder = keystoreHolderRepository.save(keystoreHolder);
        user.setKeystoreHolder(keystoreHolder);
    } else {
        try {
            keystore = keystoreHolder.getKeystore(keystorePassword);
        } catch (Exception e) {
            throw new IllegalStateException("could not open keystore for user " + username);
        }
    }
    userRepository.save(user);
    KeystoreEnabledUserDetails ud = new KeystoreEnabledUserDetails(user, keystore, keystorePassword);
    return new UsernamePasswordAuthenticationToken(ud, null, auth.getAuthorities());
}
Also used : User(won.owner.model.User) KeystoreHolder(won.owner.model.KeystoreHolder) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) KeystorePasswordHolder(won.owner.model.KeystorePasswordHolder) KeyStore(java.security.KeyStore) Transactional(javax.transaction.Transactional)

Aggregations

KeystoreHolder (won.owner.model.KeystoreHolder)3 KeystorePasswordHolder (won.owner.model.KeystorePasswordHolder)3 User (won.owner.model.User)3 KeyStore (java.security.KeyStore)2 URISyntaxException (java.net.URISyntaxException)1 Date (java.util.Date)1 Transactional (javax.transaction.Transactional)1 DataIntegrityViolationException (org.springframework.dao.DataIntegrityViolationException)1 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)1 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)1 UserDetails (org.springframework.security.core.userdetails.UserDetails)1 BCryptPasswordEncoder (org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder)1 PasswordEncoder (org.springframework.security.crypto.password.PasswordEncoder)1 CookieTheftException (org.springframework.security.web.authentication.rememberme.CookieTheftException)1 InvalidCookieException (org.springframework.security.web.authentication.rememberme.InvalidCookieException)1 RememberMeAuthenticationException (org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException)1 TransactionStatus (org.springframework.transaction.TransactionStatus)1 Transactional (org.springframework.transaction.annotation.Transactional)1 TransactionTemplate (org.springframework.transaction.support.TransactionTemplate)1 PersistentLogin (won.owner.model.PersistentLogin)1