Java Code Examples for org.springframework.security.web.authentication.rememberme.InvalidCookieException

The following examples show how to use org.springframework.security.web.authentication.rememberme.InvalidCookieException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * 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
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);
}
 
Example 2
/**
 * 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);
            persistentTokenService.delete(token);
        } catch (InvalidCookieException ice) {
            log.info("Invalid cookie, no persistent token could be deleted");
        } catch (RememberMeAuthenticationException rmae) {
            log.debug("No persistent token found, so no token could be deleted");
        }
    }
    super.logout(request, response, authentication);
}
 
Example 3
/**
 * 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.
 *
 * @param request        the request.
 * @param response       the response.
 * @param authentication the authentication.
 */
@Override
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 persistentToken = getToken(cookieTokens);
			persistentTokenRepository.deleteById(persistentToken.getSeries());
		} 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);
}
 
Example 4
/**
 * 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);
            Token token = getPersistentToken(cookieTokens);
            persistentTokenService.delete(token);
        } catch (InvalidCookieException ice) {
            LOGGER.info("Invalid cookie, no persistent token could be deleted");
        } catch (RememberMeAuthenticationException rmae) {
            LOGGER.debug("No persistent token found, so no token could be deleted");
        }
    }
    super.logout(request, response, authentication);
}
 
Example 5
/**
 * 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(final HttpServletRequest request, final HttpServletResponse response, final 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");
		} catch (RememberMeAuthenticationException rmae) {
			log.debug("No persistent token found, so no token could be deleted");
		}
	}
	super.logout(request, response, authentication);
}
 
Example 6
/**
 * 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
public void logout(HttpServletRequest request, HttpServletResponse response,
		Authentication authentication) {

	String rememberMeCookie = extractRememberMeCookie(request);
	if (rememberMeCookie != null && rememberMeCookie.length() != 0) {
		try {
			String[] cookieTokens = decodeCookie(rememberMeCookie);
			removePersistentLogin(getPersistentToken(cookieTokens));
		}
		catch (InvalidCookieException ice) {
			Application.logger
					.info("Invalid cookie, no persistent token could be deleted");
		}
		catch (RememberMeAuthenticationException rmae) {
			Application.logger
					.debug("No persistent token found, so no token could be deleted");
		}
	}

	super.logout(request, response, authentication);
}
 
Example 7
/**
 * 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];
    Optional<PersistentToken> optionalToken = persistentTokenRepository.findById(presentedSeries);
    if (!optionalToken.isPresent()) {
        // No series match, so we can't authenticate using this cookie
        throw new RememberMeAuthenticationException("No persistent token found for series id: " + presentedSeries);
    }
    PersistentToken token = optionalToken.get();
    // 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;
}
 
Example 8
@Override
protected String[] decodeCookie(String cookieValue) throws InvalidCookieException {
	try {
		return super.decodeCookie(cookieValue);
	} catch (Exception e) {
		throw new InvalidCookieException("invalid Cookie token");
	}
}
 
Example 9
/**
 * Validate the token and return it.
 */
private PersistentToken getToken(String[] cookieTokens) {
	if (cookieTokens.length != TOKEN_LENGTH) {
		throw new InvalidCookieException("Cookie token did not contain " + TOKEN_LENGTH +
			" tokens, but contained '" + Arrays.asList(cookieTokens) + "'");
	}
	String presentedSeries = cookieTokens[0];
	String presentedToken = cookieTokens[1];
	PersistentToken persistentToken = persistentTokenRepository.selectById(presentedSeries);
	if (persistentToken == 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, persistentToken.getTokenValue());
	if (!presentedToken.equals(persistentToken.getTokenValue())) {
		// Token doesn't match series value. Delete this session and throw an exception.
		persistentTokenRepository.deleteById(persistentToken.getSeries());
		throw new CookieTheftException("Invalid remember-me token (Series/token) mismatch. Implies previous " +
			"cookie theft attack.");
	}
	if (persistentToken.getTokenDate().plusDays(TOKEN_VALIDITY_DAYS).isBefore(LocalDateTime.now())) {
		persistentTokenRepository.deleteById(persistentToken.getSeries());
		throw new RememberMeAuthenticationException("Remember-me login has expired");
	}
	return persistentToken;
}
 
Example 10
/**
 * Validate the token and return it.
 */
private Token getPersistentToken(String[] cookieTokens) {
    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];

    Token token = persistentTokenService.getPersistentToken(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
    if (!presentedToken.equals(token.getTokenValue())) {

        // This could be caused by the opportunity window where the token just has been refreshed, but
        // has not been put into the token cache yet. Invalidate the token and refetch and it the new token value from the db is now returned.

        token = persistentTokenService.getPersistentToken(presentedSeries, true); // Note the 'true' here, which invalidates the cache before fetching
        if (token != null && !presentedToken.equals(token.getTokenValue())) {

            // Token doesn't match series value. Delete this session and throw an exception.
            if (token != null) {
                persistentTokenService.delete(token);
            }
            
            throw new CookieTheftException("Invalid remember-me token (Series/token) mismatch. Implies previous cookie theft attack.");

        }
    }

    if (new Date().getTime() - token.getTokenDate().getTime() > tokenMaxAgeInMilliseconds) {
        throw new RememberMeAuthenticationException("Remember-me login has expired");
    }
    return token;
}
 
Example 11
/**
 * Validate the token and return it.
 */
private PersistentToken getPersistentToken(final 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;
}
 
Example 12
Source Project: jasypt   Source File: TokenBasedRememberMeServices.java    License: Apache License 2.0 4 votes vote down vote up
protected UserDetails processAutoLoginCookie(final String[] cookieTokens, 
        final HttpServletRequest request, final HttpServletResponse response) {

    if (this.digester == null) {
        throw new IllegalStateException("Service incorrectly initialized: a " +
                "digester has not been set. A value must be specified for the \"digester\"" +
                " property in service of class " + this.getClass().getName());
    }
    
    if (cookieTokens.length != 3) {
        throw new InvalidCookieException("Wrong number of tokens in cookie");
    }

    final String usernameToken = cookieTokens[0];
    final String expiryToken = cookieTokens[1];
    final String digestedSignature = cookieTokens[2];
    
    long expiryTimestamp = -1;
    try {
        expiryTimestamp = new Long(expiryToken).longValue();
    } catch (NumberFormatException nfe) {
        throw new InvalidCookieException("Invalid cookie expiry token");
    }

    if (expiryTimestamp < System.currentTimeMillis()) {
        // Cookie has expired
        throw new InvalidCookieException("Cookie has expired (expired on '" + new Date(expiryTimestamp) + "'; current time is '" + new Date() + "')");
    }

    // Retrieve user details
    final UserDetails userDetails = 
        getUserDetailsService().loadUserByUsername(usernameToken);
    final String username = userDetails.getUsername();
    final String password = userDetails.getPassword();
    
    // Check signature data
    if (!this.digester.matches(getSignatureData(expiryTimestamp, username, password), digestedSignature)) {
        throw new InvalidCookieException("Cookie signature is not valid");
    }

    return userDetails;
    
}
 
Example 13
Source Project: jasypt   Source File: TokenBasedRememberMeServices.java    License: Apache License 2.0 4 votes vote down vote up
protected UserDetails processAutoLoginCookie(final String[] cookieTokens, 
        final HttpServletRequest request, final HttpServletResponse response) {

    if (this.digester == null) {
        throw new IllegalStateException("Service incorrectly initialized: a " +
                "digester has not been set. A value must be specified for the \"digester\"" +
                " property in service of class " + this.getClass().getName());
    }
    
    if (cookieTokens.length != 3) {
        throw new InvalidCookieException("Wrong number of tokens in cookie");
    }

    final String usernameToken = cookieTokens[0];
    final String expiryToken = cookieTokens[1];
    final String digestedSignature = cookieTokens[2];
    
    long expiryTimestamp = -1;
    try {
        expiryTimestamp = new Long(expiryToken).longValue();
    } catch (NumberFormatException nfe) {
        throw new InvalidCookieException("Invalid cookie expiry token");
    }

    if (expiryTimestamp < System.currentTimeMillis()) {
        // Cookie has expired
        throw new InvalidCookieException("Cookie has expired (expired on '" + new Date(expiryTimestamp) + "'; current time is '" + new Date() + "')");
    }

    // Retrieve user details
    final UserDetails userDetails = 
        getUserDetailsService().loadUserByUsername(usernameToken);
    final String username = userDetails.getUsername();
    final String password = userDetails.getPassword();
    
    // Check signature data
    if (!this.digester.matches(getSignatureData(expiryTimestamp, username, password), digestedSignature)) {
        throw new InvalidCookieException("Cookie signature is not valid");
    }

    return userDetails;
    
}
 
Example 14
Source Project: jasypt   Source File: TokenBasedRememberMeServices.java    License: Apache License 2.0 4 votes vote down vote up
protected UserDetails processAutoLoginCookie(final String[] cookieTokens, 
        final HttpServletRequest request, final HttpServletResponse response) {

    if (this.digester == null) {
        throw new IllegalStateException("Service incorrectly initialized: a " +
                "digester has not been set. A value must be specified for the \"digester\"" +
                " property in service of class " + this.getClass().getName());
    }
    
    if (cookieTokens.length != 3) {
        throw new InvalidCookieException("Wrong number of tokens in cookie");
    }

    final String usernameToken = cookieTokens[0];
    final String expiryToken = cookieTokens[1];
    final String digestedSignature = cookieTokens[2];
    
    long expiryTimestamp = -1;
    try {
        expiryTimestamp = new Long(expiryToken).longValue();
    } catch (NumberFormatException nfe) {
        throw new InvalidCookieException("Invalid cookie expiry token");
    }

    if (expiryTimestamp < System.currentTimeMillis()) {
        // Cookie has expired
        throw new InvalidCookieException("Cookie has expired (expired on '" + new Date(expiryTimestamp) + "'; current time is '" + new Date() + "')");
    }

    // Retrieve user details
    final UserDetails userDetails = 
        getUserDetailsService().loadUserByUsername(usernameToken);
    final String username = userDetails.getUsername();
    final String password = userDetails.getPassword();
    
    // Check signature data
    if (!this.digester.matches(getSignatureData(expiryTimestamp, username, password), digestedSignature)) {
        throw new InvalidCookieException("Cookie signature is not valid");
    }

    return userDetails;
    
}
 
Example 15
/**
 * 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) + "'");
    }

    final String presentedSeries = cookieTokens[0];
    final String presentedToken = cookieTokens[1];

    PersistentToken token = persistentTokenService.getPersistentToken(presentedSeries);

    try {
        if (token == null || token.getTokenValue() == null) {
            // No series match, so we can't authenticate using this cookie
            throw new RememberMeAuthenticationException("No persistent token found for series id: " + presentedSeries);
        }
    } catch (Exception e) {
        throw new RememberMeAuthenticationException("No persistent token found for series id: " + presentedSeries);
    }

    // We have a match for this user/series combination
    if (!presentedToken.equals(token.getTokenValue())) {

        // This could be caused by the opportunity window where the token just has been refreshed, but
        // has not been put into the token cache yet. Invalidate the token and refetch and it the new token value from the db is now returned.

        token = persistentTokenService.getPersistentToken(presentedSeries, true); // Note the 'true' here, which invalidates the cache before fetching
        if (!presentedToken.equals(token.getTokenValue())) {

            // Token doesn't match series value. Delete this session and throw an exception.
            persistentTokenService.delete(token);
            throw new CookieTheftException("Invalid remember-me token (Series/token) mismatch. Implies previous cookie theft attack.");

        }
    }

    if (new Date().getTime() - token.getTokenDate().getTime() > tokenMaxAgeInMilliseconds) {
        throw new RememberMeAuthenticationException("Remember-me login has expired");
    }
    return token;
}
 
Example 16
@Override
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];

    MultiDeviceRememberMeToken token = tokenRepository.getTokenForSeries(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);
    }

    val username = token.getUsername();
    val series = token.getSeries();
    val tokenValue = token.getTokenValue();
    val ipAddress = token.getRemoteAddress();
    val userAgent = token.getUserAgent();

    // We have a match for this user/series combination
    if (!presentedToken.equals(tokenValue)) {
        // Token doesn't match series value. Delete all logins for this user and throw
        // an exception to warn them.
        tokenRepository.removeAllUserTokens(username);

        val message = messages.getMessage("PersistentTokenBasedRememberMeServices.cookieStolen",
                "Invalid remember-me token (Series/token) mismatch. Implies previous cookie theft attack.");
        throw new CookieTheftException(message);
    }

    val lastUsed = DateUtils.toDate(token.getLastUsed());
    if (lastUsed.getTime() + getTokenValiditySeconds() * 1000L < System.currentTimeMillis()) {
        throw new RememberMeAuthenticationException("Remember-me login has expired");
    }

    // Token also matches, so login is valid. Update the token value, keeping the
    // *same* series number.
    if (log.isDebugEnabled()) {
        log.debug("Refreshing persistent login token for user '{}', series '{}'",
                new Object[] { username, series });
    }

    val newTokenValue = generateTokenData();
    val newToken = new MultiDeviceRememberMeToken();
    val newLastUsed = LocalDateTime.now();
    newToken.setUsername(username);
    newToken.setSeries(series);
    newToken.setRemoteAddress(ipAddress);
    newToken.setUserAgent(userAgent);
    newToken.setTokenValue(newTokenValue);
    newToken.setLastUsed(newLastUsed);

    try {
        tokenRepository.updateToken(series, newTokenValue, DateUtils.toDate(newLastUsed));
        addCookie(newToken, request, response);
    } catch (Exception e) {
        log.error("Failed to update token: ", e);
        throw new RememberMeAuthenticationException("Autologin failed due to data access problem");
    }

    return getUserDetailsService().loadUserByUsername(username);
}
 
Example 17
@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");
        }

        // Token also matches, so login is valid. Update the token value, keeping the
        // *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);
    }
}