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
}
});
}
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);
}
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;
}
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);
}
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);
}
}
Aggregations