Search in sources :

Example 1 with InvalidCookieException

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

use of org.springframework.security.web.authentication.rememberme.InvalidCookieException in project kylo by Teradata.

the class JwtRememberMeServices method decodeCookie.

/**
 * Decodes the specified JWT cookie into tokens.
 *
 * <p>The first element of the return value with be the JWT subject. The remaining element (should be 1) is the principals JSON token.</p>
 *
 * @param cookie the JWT cookie
 * @return an array with the username and group names
 * @throws IllegalStateException  if the secret key is invalid
 * @throws InvalidCookieException if the cookie cannot be decoded
 */
@Nonnull
@Override
protected String[] decodeCookie(@Nonnull final String cookie) throws InvalidCookieException {
    // Build the JWT parser
    final JwtConsumer consumer = new JwtConsumerBuilder().setEvaluationTime(NumericDate.fromMilliseconds(DateTimeUtils.currentTimeMillis())).setVerificationKey(getSecretKey()).build();
    // Parse the cookie
    final String user;
    final List<String> principalsClaim;
    try {
        final JwtClaims claims = consumer.processToClaims(cookie);
        user = claims.getSubject();
        principalsClaim = claims.getStringListClaimValue(PRINCIPALS);
    } catch (final InvalidJwtException e) {
        log.debug("JWT cookie is invalid: ", e);
        throw new InvalidCookieException("JWT cookie is invalid: " + e);
    } catch (final MalformedClaimException e) {
        log.debug("JWT cookie is malformed: ", e);
        throw new InvalidCookieException("JWT cookie is malformed: " + cookie);
    }
    if (StringUtils.isBlank(user)) {
        throw new InvalidCookieException("Missing user in JWT cookie: " + cookie);
    }
    // Build the token array
    final Stream<String> userStream = Stream.of(user);
    final Stream<String> groupStream = principalsClaim.stream();
    return Stream.concat(userStream, groupStream).toArray(String[]::new);
}
Also used : InvalidJwtException(org.jose4j.jwt.consumer.InvalidJwtException) InvalidCookieException(org.springframework.security.web.authentication.rememberme.InvalidCookieException) MalformedClaimException(org.jose4j.jwt.MalformedClaimException) JwtClaims(org.jose4j.jwt.JwtClaims) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) Nonnull(javax.annotation.Nonnull)

Example 3 with InvalidCookieException

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

use of org.springframework.security.web.authentication.rememberme.InvalidCookieException 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)

Example 5 with InvalidCookieException

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

the class ProfileRememberMeServices method processAutoLoginCookie.

@Override
protected UserDetails processAutoLoginCookie(final String[] cookieTokens, final HttpServletRequest request, final HttpServletResponse response) throws RememberMeAuthenticationException, UsernameNotFoundException {
    if (cookieTokens.length != 2) {
        throw new InvalidCookieException("Cookie token did not contain 2 tokens, but contained '" + Arrays.asList(cookieTokens) + "'");
    }
    final String presentedId = cookieTokens[0];
    final String presentedToken = cookieTokens[1];
    try {
        PersistentLogin persistentLogin = authenticationService.getPersistentLogin(presentedId);
        if (persistentLogin == null) {
            // No series match, so we can't authenticate using this cookie
            throw new RememberMeAuthenticationException("No persistent token found for id: " + presentedId);
        }
        // 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.
            authenticationService.deletePersistentLogin(presentedId);
            throw new CookieTheftException("Invalid remember-me token (id/token) mismatch. Implies previous cookie theft attack.");
        }
        if (persistentLogin.getTimestamp().getTime() + getTokenValiditySeconds() * 1000L < currentTimeMillis()) {
            throw new RememberMeAuthenticationException("Remember-me login has expired");
        }
        // *same* series number.
        if (logger.isDebugEnabled()) {
            logger.debug("Refreshing persistent login token for profile '" + persistentLogin.getProfileId() + "', id '" + persistentLogin.getId() + "'");
        }
        persistentLogin = authenticationService.refreshPersistentLoginToken(presentedId);
        setCookie(new String[] { persistentLogin.getId(), persistentLogin.getToken() }, getTokenValiditySeconds(), request, response);
        return ((ProfileUserDetailsService) getUserDetailsService()).loadUserById(persistentLogin.getProfileId());
    } catch (ProfileException e) {
        throw new RememberMeAuthenticationException("Error validating persistent login " + presentedId, e);
    }
}
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) ProfileException(org.craftercms.profile.api.exceptions.ProfileException) PersistentLogin(org.craftercms.profile.api.PersistentLogin)

Aggregations

InvalidCookieException (org.springframework.security.web.authentication.rememberme.InvalidCookieException)5 RememberMeAuthenticationException (org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException)4 CookieTheftException (org.springframework.security.web.authentication.rememberme.CookieTheftException)3 PersistentToken (de.tum.in.www1.artemis.domain.PersistentToken)2 Transactional (org.springframework.transaction.annotation.Transactional)2 KeyStore (java.security.KeyStore)1 Date (java.util.Date)1 Nonnull (javax.annotation.Nonnull)1 PersistentLogin (org.craftercms.profile.api.PersistentLogin)1 ProfileException (org.craftercms.profile.api.exceptions.ProfileException)1 JwtClaims (org.jose4j.jwt.JwtClaims)1 MalformedClaimException (org.jose4j.jwt.MalformedClaimException)1 InvalidJwtException (org.jose4j.jwt.consumer.InvalidJwtException)1 JwtConsumer (org.jose4j.jwt.consumer.JwtConsumer)1 JwtConsumerBuilder (org.jose4j.jwt.consumer.JwtConsumerBuilder)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 KeystorePasswordHolder (won.owner.model.KeystorePasswordHolder)1