org.springframework.security.web.authentication.rememberme.CookieTheftException Java Examples

The following examples show how to use org.springframework.security.web.authentication.rememberme.CookieTheftException. 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
Source File: PersistentTokenRememberMeServices.java    From TeamDojo with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #2
Source File: SpringSecurityWebErrorHandlerTest.java    From errors-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
private Object[] provideParamsForHandle() {
    return p(
        p(new AccessDeniedException(""), ACCESS_DENIED, FORBIDDEN),
        p(new LockedException(""), USER_LOCKED, BAD_REQUEST),
        p(new DisabledException(""), USER_DISABLED, BAD_REQUEST),
        p(new UsernameNotFoundException(""), BAD_CREDENTIALS, BAD_REQUEST),
        p(new BadCredentialsException(""), BAD_CREDENTIALS, BAD_REQUEST),
        p(new AccountExpiredException(""), ACCOUNT_EXPIRED, BAD_REQUEST),
        p(new AuthenticationServiceException(""), INTERNAL_ERROR, INTERNAL_SERVER_ERROR),
        p(new InsufficientAuthenticationException(""), AUTH_REQUIRED, UNAUTHORIZED),
        p(new AuthenticationCredentialsNotFoundException(""), AUTH_REQUIRED, UNAUTHORIZED),
        p(new CookieTheftException(""), "unknown_error", INTERNAL_SERVER_ERROR)
    );
}
 
Example #3
Source File: PersistentTokenRememberMeService.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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 #4
Source File: CustomPersistentRememberMeServices.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #5
Source File: CustomPersistentRememberMeServices.java    From ServiceCutter with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #6
Source File: CustomPersistentRememberMeServices.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
/**
 * 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 #7
Source File: MultiDeviceRememberMeServices.java    From spring-boot-doma2-sample with Apache License 2.0 4 votes vote down vote up
@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 #8
Source File: ProfileRememberMeServices.java    From engine with GNU General Public License v3.0 4 votes vote down vote up
@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);
    }
}