Search in sources :

Example 1 with PersistentToken

use of de.tum.in.www1.artemis.domain.PersistentToken in project ArTEMiS by ls1intum.

the class AccountResourceIntTest method testInvalidateSession.

@Test
@Transactional
@WithMockUser("invalidate-session")
public void testInvalidateSession() throws Exception {
    User user = new User();
    user.setPassword(RandomStringUtils.random(60));
    user.setLogin("invalidate-session");
    user.setEmail("invalidate-session@example.com");
    userRepository.saveAndFlush(user);
    PersistentToken token = new PersistentToken();
    token.setSeries("invalidate-session");
    token.setUser(user);
    token.setTokenValue("invalidate-data");
    token.setTokenDate(LocalDate.of(2017, 3, 23));
    token.setIpAddress("127.0.0.1");
    token.setUserAgent("Test agent");
    persistentTokenRepository.saveAndFlush(token);
    assertThat(persistentTokenRepository.findByUser(user)).hasSize(1);
    restMvc.perform(delete("/api/account/sessions/invalidate-session")).andExpect(status().isOk());
    assertThat(persistentTokenRepository.findByUser(user)).isEmpty();
}
Also used : User(de.tum.in.www1.artemis.domain.User) WithMockUser(org.springframework.security.test.context.support.WithMockUser) PersistentToken(de.tum.in.www1.artemis.domain.PersistentToken) WithMockUser(org.springframework.security.test.context.support.WithMockUser) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Transactional(org.springframework.transaction.annotation.Transactional)

Example 2 with PersistentToken

use of de.tum.in.www1.artemis.domain.PersistentToken in project ArTEMiS by ls1intum.

the class AccountResourceIntTest method testGetCurrentSessions.

@Test
@Transactional
@WithMockUser("current-sessions")
public void testGetCurrentSessions() throws Exception {
    User user = new User();
    user.setPassword(RandomStringUtils.random(60));
    user.setLogin("current-sessions");
    user.setEmail("current-sessions@example.com");
    userRepository.saveAndFlush(user);
    PersistentToken token = new PersistentToken();
    token.setSeries("current-sessions");
    token.setUser(user);
    token.setTokenValue("current-session-data");
    token.setTokenDate(LocalDate.of(2017, 3, 23));
    token.setIpAddress("127.0.0.1");
    token.setUserAgent("Test agent");
    persistentTokenRepository.saveAndFlush(token);
    restMvc.perform(get("/api/account/sessions")).andExpect(status().isOk()).andExpect(jsonPath("$.[*].series").value(hasItem(token.getSeries()))).andExpect(jsonPath("$.[*].ipAddress").value(hasItem(token.getIpAddress()))).andExpect(jsonPath("$.[*].userAgent").value(hasItem(token.getUserAgent()))).andExpect(jsonPath("$.[*].tokenDate").value(hasItem(token.getTokenDate().toString())));
}
Also used : User(de.tum.in.www1.artemis.domain.User) WithMockUser(org.springframework.security.test.context.support.WithMockUser) PersistentToken(de.tum.in.www1.artemis.domain.PersistentToken) WithMockUser(org.springframework.security.test.context.support.WithMockUser) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Transactional(org.springframework.transaction.annotation.Transactional)

Example 3 with PersistentToken

use of de.tum.in.www1.artemis.domain.PersistentToken in project ArTEMiS by ls1intum.

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) Arrays(java.util.Arrays) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) PersistentToken(de.tum.in.www1.artemis.domain.PersistentToken) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) PersistentTokenRepository(de.tum.in.www1.artemis.repository.PersistentTokenRepository) RandomUtil(de.tum.in.www1.artemis.service.util.RandomUtil) HttpServletRequest(javax.servlet.http.HttpServletRequest) UserRepository(de.tum.in.www1.artemis.repository.UserRepository) Service(org.springframework.stereotype.Service) UserDetails(org.springframework.security.core.userdetails.UserDetails) RememberMeAuthenticationException(org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException) CookieTheftException(org.springframework.security.web.authentication.rememberme.CookieTheftException) Logger(org.slf4j.Logger) HttpServletResponse(javax.servlet.http.HttpServletResponse) InvalidCookieException(org.springframework.security.web.authentication.rememberme.InvalidCookieException) Serializable(java.io.Serializable) TimeUnit(java.util.concurrent.TimeUnit) LocalDate(java.time.LocalDate) AbstractRememberMeServices(org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices) CacheBuilder(com.google.common.cache.CacheBuilder) Cache(com.google.common.cache.Cache) Authentication(org.springframework.security.core.Authentication) JHipsterProperties(io.github.jhipster.config.JHipsterProperties) Transactional(org.springframework.transaction.annotation.Transactional) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) PersistentToken(de.tum.in.www1.artemis.domain.PersistentToken) DataAccessException(org.springframework.dao.DataAccessException)

Example 4 with PersistentToken

use of de.tum.in.www1.artemis.domain.PersistentToken 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;
}
Also used : RememberMeAuthenticationException(org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException) InvalidCookieException(org.springframework.security.web.authentication.rememberme.InvalidCookieException) CookieTheftException(org.springframework.security.web.authentication.rememberme.CookieTheftException) PersistentToken(de.tum.in.www1.artemis.domain.PersistentToken)

Example 5 with PersistentToken

use of de.tum.in.www1.artemis.domain.PersistentToken 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);
}
Also used : RememberMeAuthenticationException(org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException) InvalidCookieException(org.springframework.security.web.authentication.rememberme.InvalidCookieException) PersistentToken(de.tum.in.www1.artemis.domain.PersistentToken) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

PersistentToken (de.tum.in.www1.artemis.domain.PersistentToken)7 RememberMeAuthenticationException (org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException)4 Transactional (org.springframework.transaction.annotation.Transactional)4 InvalidCookieException (org.springframework.security.web.authentication.rememberme.InvalidCookieException)3 User (de.tum.in.www1.artemis.domain.User)2 Test (org.junit.Test)2 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)2 DataAccessException (org.springframework.dao.DataAccessException)2 WithMockUser (org.springframework.security.test.context.support.WithMockUser)2 CookieTheftException (org.springframework.security.web.authentication.rememberme.CookieTheftException)2 Cache (com.google.common.cache.Cache)1 CacheBuilder (com.google.common.cache.CacheBuilder)1 PersistentTokenRepository (de.tum.in.www1.artemis.repository.PersistentTokenRepository)1 UserRepository (de.tum.in.www1.artemis.repository.UserRepository)1 RandomUtil (de.tum.in.www1.artemis.service.util.RandomUtil)1 JHipsterProperties (io.github.jhipster.config.JHipsterProperties)1 Serializable (java.io.Serializable)1 LocalDate (java.time.LocalDate)1 Arrays (java.util.Arrays)1 Date (java.util.Date)1