Search in sources :

Example 1 with RememberMeAuthenticationException

use of org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException in project webofneeds by researchstudio-sat.

the class KeystoreEnabledPersistentRememberMeServices method onLoginSuccess.

/**
 * Creates a new persistent login token with a new series number, stores the data in
 * the persistent token repository and adds the corresponding cookie to the response.
 */
@Transactional
protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {
    String username = successfulAuthentication.getName();
    KeystoreEnabledUserDetails keystoreEnabledUserDetails = (KeystoreEnabledUserDetails) successfulAuthentication.getPrincipal();
    logger.debug("Creating new persistent login for user " + username);
    PersistentLogin persistentLogin = new PersistentLogin();
    persistentLogin.setUsername(username);
    persistentLogin.setSeries(generateSeriesData());
    persistentLogin.setToken(generateTokenData());
    persistentLogin.setLastUsed(new Date());
    String newUnlockKey = KeystorePasswordUtils.generatePassword(KeystorePasswordUtils.KEYSTORE_PASSWORD_BYTES);
    KeystorePasswordHolder keystorePasswordHolder = new KeystorePasswordHolder();
    keystorePasswordHolder.setPassword(keystoreEnabledUserDetails.getKeystorePassword(), newUnlockKey);
    persistentLogin.setKeystorePasswordHolder(keystorePasswordHolder);
    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");
    }
}
Also used : RememberMeAuthenticationException(org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException) PersistentLogin(won.owner.model.PersistentLogin) KeystorePasswordHolder(won.owner.model.KeystorePasswordHolder) 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) Transactional(org.springframework.transaction.annotation.Transactional)

Example 2 with RememberMeAuthenticationException

use of org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException 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 3 with RememberMeAuthenticationException

use of org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException in project ArTEMiS by ls1intum.

the class PersistentTokenRememberMeServices method getPersistentToken.

/**
 * Validate the token and return it.
 */
private PersistentToken getPersistentToken(String[] cookieTokens) {
    if (cookieTokens.length != 2) {
        throw new InvalidCookieException("Cookie token did not contain " + 2 + " tokens, but contained '" + Arrays.asList(cookieTokens) + "'");
    }
    String presentedSeries = cookieTokens[0];
    String presentedToken = cookieTokens[1];
    PersistentToken token = persistentTokenRepository.findOne(presentedSeries);
    if (token == 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
    log.info("presentedToken={} / tokenValue={}", presentedToken, token.getTokenValue());
    if (!presentedToken.equals(token.getTokenValue())) {
        // Token doesn't match series value. Delete this session and throw an exception.
        persistentTokenRepository.delete(token);
        throw new CookieTheftException("Invalid remember-me token (Series/token) mismatch. Implies previous " + "cookie theft attack.");
    }
    if (token.getTokenDate().plusDays(TOKEN_VALIDITY_DAYS).isBefore(LocalDate.now())) {
        persistentTokenRepository.delete(token);
        throw new RememberMeAuthenticationException("Remember-me login has expired");
    }
    return token;
}
Also used : RememberMeAuthenticationException(org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException) InvalidCookieException(org.springframework.security.web.authentication.rememberme.InvalidCookieException) CookieTheftException(org.springframework.security.web.authentication.rememberme.CookieTheftException) PersistentToken(de.tum.in.www1.artemis.domain.PersistentToken)

Example 4 with RememberMeAuthenticationException

use of org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException in project engine by craftercms.

the class ProfileRememberMeServices method onLoginSuccess.

@Override
protected void onLoginSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication successfulAuthentication) {
    ProfileUser profileUser = (ProfileUser) successfulAuthentication.getPrincipal();
    try {
        PersistentLogin persistentLogin = authenticationService.createPersistentLogin(profileUser.getProfile().getId().toHexString());
        setCookie(new String[] { persistentLogin.getId(), persistentLogin.getToken() }, getTokenValiditySeconds(), request, response);
    } catch (ProfileException e) {
        throw new RememberMeAuthenticationException("Error creating persistent login for " + profileUser.getUsername(), e);
    }
}
Also used : RememberMeAuthenticationException(org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException) ProfileException(org.craftercms.profile.api.exceptions.ProfileException) PersistentLogin(org.craftercms.profile.api.PersistentLogin)

Example 5 with RememberMeAuthenticationException

use of org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException in project ArTEMiS by ls1intum.

the class PersistentTokenRememberMeServices method logout.

/**
 * When logout occurs, only invalidate the current token, and not all user sessions.
 * <p>
 * The standard Spring Security implementations are too basic: they invalidate all tokens for the
 * current user, so when he logs out from one browser, all his other sessions are destroyed.
 */
@Override
@Transactional
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    String rememberMeCookie = extractRememberMeCookie(request);
    if (rememberMeCookie != null && rememberMeCookie.length() != 0) {
        try {
            String[] cookieTokens = decodeCookie(rememberMeCookie);
            PersistentToken token = getPersistentToken(cookieTokens);
            persistentTokenRepository.delete(token);
        } catch (InvalidCookieException ice) {
            log.info("Invalid cookie, no persistent token could be deleted", ice);
        } catch (RememberMeAuthenticationException rmae) {
            log.debug("No persistent token found, so no token could be deleted", rmae);
        }
    }
    super.logout(request, response, authentication);
}
Also used : RememberMeAuthenticationException(org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException) InvalidCookieException(org.springframework.security.web.authentication.rememberme.InvalidCookieException) PersistentToken(de.tum.in.www1.artemis.domain.PersistentToken) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

RememberMeAuthenticationException (org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException)8 InvalidCookieException (org.springframework.security.web.authentication.rememberme.InvalidCookieException)5 CookieTheftException (org.springframework.security.web.authentication.rememberme.CookieTheftException)4 PersistentToken (de.tum.in.www1.artemis.domain.PersistentToken)3 ProfileException (org.craftercms.profile.api.exceptions.ProfileException)3 Transactional (org.springframework.transaction.annotation.Transactional)3 Date (java.util.Date)2 PersistentLogin (org.craftercms.profile.api.PersistentLogin)2 KeystorePasswordHolder (won.owner.model.KeystorePasswordHolder)2 PersistentLogin (won.owner.model.PersistentLogin)2 KeyStore (java.security.KeyStore)1 DataAccessException (org.springframework.dao.DataAccessException)1 UserDetails (org.springframework.security.core.userdetails.UserDetails)1 TransactionStatus (org.springframework.transaction.TransactionStatus)1 TransactionTemplate (org.springframework.transaction.support.TransactionTemplate)1 KeystoreHolder (won.owner.model.KeystoreHolder)1 User (won.owner.model.User)1