Search in sources :

Example 11 with PersistentToken

use of io.github.jhipster.sample.domain.PersistentToken in project jhipster-sample-app-websocket by jhipster.

the class UserServiceIntTest method generateUserToken.

private void generateUserToken(User user, String tokenSeries, LocalDate localDate) {
    PersistentToken token = new PersistentToken();
    token.setSeries(tokenSeries);
    token.setUser(user);
    token.setTokenValue(tokenSeries + "-data");
    token.setTokenDate(localDate);
    token.setIpAddress("127.0.0.1");
    token.setUserAgent("Test agent");
    persistentTokenRepository.saveAndFlush(token);
}
Also used : PersistentToken(io.github.jhipster.sample.domain.PersistentToken)

Example 12 with PersistentToken

use of io.github.jhipster.sample.domain.PersistentToken in project jhipster-sample-app-websocket by jhipster.

the class PersistentTokenRememberMeServices method onLoginSuccess.

@Override
protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {
    String login = successfulAuthentication.getName();
    log.debug("Creating new persistent login for user {}", login);
    PersistentToken token = userRepository.findOneByLogin(login).map(u -> {
        PersistentToken t = new PersistentToken();
        t.setSeries(RandomUtil.generateSeriesData());
        t.setUser(u);
        t.setTokenValue(RandomUtil.generateTokenData());
        t.setTokenDate(LocalDate.now());
        t.setIpAddress(request.getRemoteAddr());
        t.setUserAgent(request.getHeader("User-Agent"));
        return t;
    }).orElseThrow(() -> new UsernameNotFoundException("User " + login + " was not found in the database"));
    try {
        persistentTokenRepository.saveAndFlush(token);
        addCookie(token, request, response);
    } catch (DataAccessException e) {
        log.error("Failed to save persistent token ", e);
    }
}
Also used : DataAccessException(org.springframework.dao.DataAccessException) java.util(java.util) UserRepository(io.github.jhipster.sample.repository.UserRepository) Logger(org.slf4j.Logger) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) LoggerFactory(org.slf4j.LoggerFactory) HttpServletResponse(javax.servlet.http.HttpServletResponse) PersistentToken(io.github.jhipster.sample.domain.PersistentToken) PersistentTokenRepository(io.github.jhipster.sample.repository.PersistentTokenRepository) Serializable(java.io.Serializable) TimeUnit(java.util.concurrent.TimeUnit) HttpServletRequest(javax.servlet.http.HttpServletRequest) Service(org.springframework.stereotype.Service) LocalDate(java.time.LocalDate) UserDetails(org.springframework.security.core.userdetails.UserDetails) RandomUtil(io.github.jhipster.sample.service.util.RandomUtil) CacheBuilder(com.google.common.cache.CacheBuilder) Cache(com.google.common.cache.Cache) Authentication(org.springframework.security.core.Authentication) org.springframework.security.web.authentication.rememberme(org.springframework.security.web.authentication.rememberme) JHipsterProperties(io.github.jhipster.config.JHipsterProperties) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) PersistentToken(io.github.jhipster.sample.domain.PersistentToken) DataAccessException(org.springframework.dao.DataAccessException)

Example 13 with PersistentToken

use of io.github.jhipster.sample.domain.PersistentToken in project jhipster-sample-app-websocket by jhipster.

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];
    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;
}
Also used : PersistentToken(io.github.jhipster.sample.domain.PersistentToken)

Example 14 with PersistentToken

use of io.github.jhipster.sample.domain.PersistentToken in project jhipster-sample-app-websocket by jhipster.

the class PersistentTokenRememberMeServices method processAutoLoginCookie.

@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);
    }
}
Also used : PersistentToken(io.github.jhipster.sample.domain.PersistentToken) DataAccessException(org.springframework.dao.DataAccessException)

Example 15 with PersistentToken

use of io.github.jhipster.sample.domain.PersistentToken in project jhipster-sample-app-hazelcast by jhipster.

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];
    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;
}
Also used : PersistentToken(io.github.jhipster.sample.domain.PersistentToken)

Aggregations

PersistentToken (io.github.jhipster.sample.domain.PersistentToken)21 User (io.github.jhipster.sample.domain.User)6 Test (org.junit.Test)6 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)6 DataAccessException (org.springframework.dao.DataAccessException)6 WithMockUser (org.springframework.security.test.context.support.WithMockUser)6 Transactional (org.springframework.transaction.annotation.Transactional)6 Cache (com.google.common.cache.Cache)3 CacheBuilder (com.google.common.cache.CacheBuilder)3 JHipsterProperties (io.github.jhipster.config.JHipsterProperties)3 PersistentTokenRepository (io.github.jhipster.sample.repository.PersistentTokenRepository)3 UserRepository (io.github.jhipster.sample.repository.UserRepository)3 RandomUtil (io.github.jhipster.sample.service.util.RandomUtil)3 Serializable (java.io.Serializable)3 LocalDate (java.time.LocalDate)3 java.util (java.util)3 TimeUnit (java.util.concurrent.TimeUnit)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 Logger (org.slf4j.Logger)3