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

The following examples show how to use org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException. 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 6 votes vote down vote up
/**
 * 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
Source File: ProfileRememberMeServices.java    From engine with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void logout(final HttpServletRequest request, final HttpServletResponse response,
                   final Authentication authentication) {
    super.logout(request, response, authentication);

    // Needed because the super class expects to work only with the username
    String cookie = extractRememberMeCookie(request);
    if (authentication != null && isNotEmpty(cookie)) {
        String persistentLoginId = decodeCookie(cookie)[0];
        try {
            authenticationService.deletePersistentLogin(persistentLoginId);
        } catch (ProfileException e) {
            throw new RememberMeAuthenticationException(
                "Error deleting persistent login " + persistentLoginId, e);
        }
    }
}
 
Example #3
Source File: CustomPersistentRememberMeServices.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #4
Source File: CustomPersistentRememberMeServices.java    From eds-starter6-jpa with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #5
Source File: PersistentTokenRememberMeService.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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 #6
Source File: CustomPersistentRememberMeServices.java    From ServiceCutter with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #7
Source File: CustomPersistentRememberMeServices.java    From ServiceCutter with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional
protected UserDetails processAutoLoginCookie(final String[] cookieTokens, final HttpServletRequest request, final HttpServletResponse response) {

	PersistentToken token = getPersistentToken(cookieTokens);
	String login = token.getUser().getLogin();

	// Token also matches, so login is valid. Update the token value,
	// keeping the *same* series number.
	log.debug("Refreshing persistent login token for user '{}', series '{}'", login, token.getSeries());
	token.setTokenDate(new LocalDate());
	token.setTokenValue(generateTokenData());
	token.setIpAddress(request.getRemoteAddr());
	token.setUserAgent(request.getHeader("User-Agent"));
	try {
		persistentTokenRepository.saveAndFlush(token);
		addCookie(token, request, response);
	} catch (DataAccessException e) {
		log.error("Failed to update token: ", e);
		throw new RememberMeAuthenticationException("Autologin failed due to data access problem", e);
	}
	return getUserDetailsService().loadUserByUsername(login);
}
 
Example #8
Source File: CustomPersistentRememberMeServices.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #9
Source File: CustomPersistentRememberMeServices.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) {

    Token token = getPersistentToken(cookieTokens);

    // Refresh token if refresh period has been passed
    if (new Date().getTime() - token.getTokenDate().getTime() > tokenRefreshDurationInMilliseconds) {

        // log.info("Refreshing persistent login token for user '{}', series '{}'", token.getUserId(), token.getSeries());
        try {

            // Refreshing: creating a new token to be used for subsequent calls

            token = persistentTokenService.createToken(identityService.createUserQuery().userId(token.getUserId()).singleResult(),
                    request.getRemoteAddr(), request.getHeader("User-Agent"));
            addCookie(token, request, response);

        } catch (DataAccessException e) {
            LOGGER.error("Failed to update token: ", e);
            throw new RememberMeAuthenticationException("Autologin failed due to data access problem: " + e.getMessage());
        }

    }

    return customUserDetailService.loadByUserId(token.getUserId());
}
 
Example #10
Source File: ProfileRememberMeServices.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
@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);
    }
}
 
Example #11
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 #12
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 #13
Source File: PersistentTokenRememberMeServices.java    From TeamDojo with Apache License 2.0 5 votes vote down vote up
@Override
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request,
                                             HttpServletResponse response) {

    synchronized (this) { // prevent 2 authentication requests from the same user in parallel
        String login = null;
        UpgradedRememberMeToken upgradedToken = upgradedTokenCache.getIfPresent(cookieTokens[0]);
        if (upgradedToken != null) {
            login = upgradedToken.getUserLoginIfValidAndRecentUpgrade(cookieTokens);
            log.debug("Detected previously upgraded login token for user '{}'", login);
        }

        if (login == null) {
            PersistentToken token = getPersistentToken(cookieTokens);
            login = token.getUser().getLogin();

            // Token also matches, so login is valid. Update the token value, keeping the *same* series number.
            log.debug("Refreshing persistent login token for user '{}', series '{}'", login, token.getSeries());
            token.setTokenDate(LocalDate.now());
            token.setTokenValue(RandomUtil.generateTokenData());
            token.setIpAddress(request.getRemoteAddr());
            token.setUserAgent(request.getHeader("User-Agent"));
            try {
                persistentTokenRepository.saveAndFlush(token);
            } catch (DataAccessException e) {
                log.error("Failed to update token: ", e);
                throw new RememberMeAuthenticationException("Autologin failed due to data access problem", e);
            }
            addCookie(token, request, response);
            upgradedTokenCache.put(cookieTokens[0], new UpgradedRememberMeToken(cookieTokens, login));
        }
        return getUserDetailsService().loadUserByUsername(login);
    }
}
 
Example #14
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 #15
Source File: PersistentTokenRememberMeService.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request,
											 HttpServletResponse response) {
	// prevent 2 authentication requests from the same user in parallel
	synchronized (this) {
		if (cookieTokens == null) {
			return null;
		}
		String login = null;
		UpgradedRememberMeToken upgradedToken = upgradedTokenCache.get(cookieTokens[0]);
		if (upgradedToken != null) {
			login = upgradedToken.getUserLoginIfValid(cookieTokens);
			log.debug("Detected previously upgraded login token for user '{}'", login);
		}

		if (login == null) {
			PersistentToken persistentToken = getToken(cookieTokens);
			User user = userRepository.selectById(persistentToken.getUserId());
			login = user.getUsername();

			// Token also matches, so login is valid. Update the token value, keeping the *same* series number.
			log.debug("Refreshing persistent login token for user '{}', series '{}'", login, persistentToken.getSeries());
			persistentToken.setTokenDate(LocalDateTime.now());
			persistentToken.setTokenValue(RandomUtil.generateTokenData());
			persistentToken.setIpAddress(WebUtil.getIp(request));
			persistentToken.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
			try {
				persistentTokenRepository.updateById(persistentToken);
			} catch (DataAccessException e) {
				log.error("Failed to update token: ", e);
				throw new RememberMeAuthenticationException("Autologin failed due to data access problem", e);
			}
			addCookie(persistentToken, request, response);
			upgradedTokenCache.put(cookieTokens[0], new UpgradedRememberMeToken(cookieTokens, login));
		}
		return getUserDetailsService().loadUserByUsername(login);
	}
}
 
Example #16
Source File: CustomPersistentRememberMeServices.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) {

    PersistentToken token = getPersistentToken(cookieTokens);

    // Refresh token if refresh period has been passed
    if (new Date().getTime() - token.getTokenDate().getTime() > tokenRefreshDurationInMilliseconds) {

        // log.info("Refreshing persistent login token for user '{}', series '{}'", token.getUserId(), token.getSeries());
        try {

            // Refreshing: creating a new token to be used for subsequent calls

            token = persistentTokenService.createToken(identityService.createUserQuery().userId(token.getUser()).singleResult(),
                    request.getRemoteAddr(), request.getHeader("User-Agent"));
            addCookie(token, request, response);

        } catch (DataAccessException e) {
            log.error("Failed to update token: ", e);
            throw new RememberMeAuthenticationException("Autologin failed due to data access problem: " + e.getMessage());
        }

    }

    return customUserDetailService.loadByUserId(token.getUser());
}
 
Example #17
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 #18
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 #19
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 #20
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);
    }
}