Java Code Examples for org.springframework.session.Session

The following examples show how to use org.springframework.session.Session. These examples are extracted from open source projects. 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
@Test
@SuppressWarnings("unchecked")
public void createdSessionStoredInAndRetrievableFromCacheRegion() {

	Instant now = Instant.now();

	Session session = this.sessionRepository.createSession();

	assertThat(session).isInstanceOf(AbstractGemFireOperationsSessionRepository.GemFireSession.class);
	assertThat(session.getId()).isNotEmpty();
	assertThat(session.isExpired()).isFalse();
	assertThat(session.getCreationTime()).isAfterOrEqualTo(now);
	assertThat(this.sessions).doesNotContainKey(session.getId());

	this.sessionRepository.save(session);

	assertThat(this.sessions).containsKey(session.getId());
	assertThat(this.sessions.get(session.getId())).isEqualTo(session);
}
 
Example 2
@Test
@SuppressWarnings("unchecked")
public void sessionRegionExists() {

	assertThat(this.applicationContext.containsBean(GemFireHttpSessionConfiguration.DEFAULT_SESSION_REGION_NAME))
		.isTrue();

	Region<Object, Session> sessionRegion =
		this.applicationContext.getBean(GemFireHttpSessionConfiguration.DEFAULT_SESSION_REGION_NAME, Region.class);

	assertThat(sessionRegion).isNotNull();
	assertThat(sessionRegion.getName()).isEqualTo(GemFireHttpSessionConfiguration.DEFAULT_SESSION_REGION_NAME);
	assertThat(sessionRegion.getFullPath())
		.isEqualTo(RegionUtils.toRegionPath(GemFireHttpSessionConfiguration.DEFAULT_SESSION_REGION_NAME));
	assertThat(sessionRegion.getAttributes()).isNotNull();
	assertThat(sessionRegion.getAttributes().getPoolName()).isNotEqualTo("gemfirePool");

	RegionAttributes<Object, Session> sessionRegionAttributes = sessionRegion.getAttributes();

	assertThat(sessionRegionAttributes).isNotNull();
	assertThat(sessionRegionAttributes.getDataPolicy()).isEqualTo(DataPolicy.EMPTY);
}
 
Example 3
Source Project: spring-session   Source File: IndexDocTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unused")
void newReactiveRedisSessionRepository() {
	LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory();
	RedisSerializationContext<String, Object> serializationContext = RedisSerializationContext
			.<String, Object>newSerializationContext(new JdkSerializationRedisSerializer()).build();

	// tag::new-reactiveredissessionrepository[]
	// ... create and configure connectionFactory and serializationContext ...

	ReactiveRedisTemplate<String, Object> redisTemplate = new ReactiveRedisTemplate<>(connectionFactory,
			serializationContext);

	ReactiveSessionRepository<? extends Session> repository = new ReactiveRedisSessionRepository(redisTemplate);
	// end::new-reactiveredissessionrepository[]
}
 
Example 4
Source Project: spring-session   Source File: IndexDocTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unused")
void newJdbcIndexedSessionRepository() {
	// tag::new-jdbcindexedsessionrepository[]
	JdbcTemplate jdbcTemplate = new JdbcTemplate();

	// ... configure jdbcTemplate ...

	TransactionTemplate transactionTemplate = new TransactionTemplate();

	// ... configure transactionTemplate ...

	SessionRepository<? extends Session> repository = new JdbcIndexedSessionRepository(jdbcTemplate,
			transactionTemplate);
	// end::new-jdbcindexedsessionrepository[]
}
 
Example 5
@Test
void doFilterAdapterOnNewSession() throws Exception {
	this.filter.setHttpSessionIdResolver(this.strategy);

	doFilter(new DoInFilter() {
		@Override
		public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) {
			wrappedRequest.getSession();
		}
	});

	HttpServletRequest request = (HttpServletRequest) this.chain.getRequest();
	Session session = this.sessionRepository.findById(request.getSession().getId());
	verify(this.strategy).setSessionId(any(HttpServletRequest.class), any(HttpServletResponse.class),
			eq(session.getId()));
}
 
Example 6
@Test
void expireNow() {
	Session session = createSession(SESSION_ID, USER_NAME, NOW);
	when(this.sessionRepository.findById(SESSION_ID)).thenReturn(session);

	SessionInformation sessionInfo = this.sessionRegistry.getSessionInformation(SESSION_ID);
	assertThat(sessionInfo.isExpired()).isFalse();

	sessionInfo.expireNow();

	assertThat(sessionInfo.isExpired()).isTrue();
	ArgumentCaptor<Session> captor = ArgumentCaptor.forClass(Session.class);
	verify(this.sessionRepository).save(captor.capture());
	assertThat(captor.getValue().<Boolean>getAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR))
			.isEqualTo(Boolean.TRUE);
}
 
Example 7
@Test
@SuppressWarnings("unchecked")
void getSessionFound() {
	Session saved = this.repository.new JdbcSession(new MapSession(), "primaryKey", false);
	saved.setAttribute("savedName", "savedValue");
	given(this.jdbcOperations.query(isA(String.class), isA(PreparedStatementSetter.class),
			isA(ResultSetExtractor.class))).willReturn(Collections.singletonList(saved));

	JdbcSession session = this.repository.findById(saved.getId());

	assertThat(session.getId()).isEqualTo(saved.getId());
	assertThat(session.isNew()).isFalse();
	assertThat(session.<String>getAttribute("savedName")).isEqualTo("savedValue");
	verify(this.jdbcOperations, times(1)).query(isA(String.class), isA(PreparedStatementSetter.class),
			isA(ResultSetExtractor.class));
}
 
Example 8
@Test
@SuppressWarnings("unchecked")
void findByIndexNameAndIndexValuePrincipalIndexNameFound() {
	String principal = "username";
	Authentication authentication = new UsernamePasswordAuthenticationToken(principal, "notused",
			AuthorityUtils.createAuthorityList("ROLE_USER"));
	List<Session> saved = new ArrayList<>(2);
	Session saved1 = this.repository.createSession();
	saved1.setAttribute(SPRING_SECURITY_CONTEXT, authentication);
	saved.add(saved1);
	Session saved2 = this.repository.createSession();
	saved2.setAttribute(SPRING_SECURITY_CONTEXT, authentication);
	saved.add(saved2);
	given(this.jdbcOperations.query(isA(String.class), isA(PreparedStatementSetter.class),
			isA(ResultSetExtractor.class))).willReturn(saved);

	Map<String, JdbcSession> sessions = this.repository
			.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal);

	assertThat(sessions).hasSize(2);
	verify(this.jdbcOperations, times(1)).query(isA(String.class), isA(PreparedStatementSetter.class),
			isA(ResultSetExtractor.class));
}
 
Example 9
@Test
void putAllOnSingleAttrDoesNotRemoveOld() {
	RedisSession toSave = this.repository.createSession();
	toSave.setAttribute("a", "b");

	this.repository.save(toSave);
	toSave = this.repository.findById(toSave.getId());

	toSave.setAttribute("1", "2");

	this.repository.save(toSave);
	toSave = this.repository.findById(toSave.getId());

	Session session = this.repository.findById(toSave.getId());
	assertThat(session.getAttributeNames().size()).isEqualTo(2);
	assertThat(session.<String>getAttribute("a")).isEqualTo("b");
	assertThat(session.<String>getAttribute("1")).isEqualTo("2");

	this.repository.deleteById(toSave.getId());
}
 
Example 10
@Test
void saves() {
	RedisSession toSave = this.repository.createSession().block();

	String expectedAttributeName = "a";
	String expectedAttributeValue = "b";

	toSave.setAttribute(expectedAttributeName, expectedAttributeValue);
	this.repository.save(toSave).block();

	Session session = this.repository.findById(toSave.getId()).block();

	assertThat(session.getId()).isEqualTo(toSave.getId());
	assertThat(session.getAttributeNames()).isEqualTo(toSave.getAttributeNames());
	assertThat(session.<String>getAttribute(expectedAttributeName))
			.isEqualTo(toSave.getAttribute(expectedAttributeName));

	this.repository.deleteById(toSave.getId()).block();

	assertThat(this.repository.findById(toSave.getId()).block()).isNull();
}
 
Example 11
@Test
void putAllOnSingleAttrDoesNotRemoveOld() {
	RedisSession toSave = this.repository.createSession().block();
	toSave.setAttribute("a", "b");

	this.repository.save(toSave).block();
	toSave = this.repository.findById(toSave.getId()).block();

	toSave.setAttribute("1", "2");

	this.repository.save(toSave).block();
	toSave = this.repository.findById(toSave.getId()).block();

	Session session = this.repository.findById(toSave.getId()).block();
	assertThat(session.getAttributeNames().size()).isEqualTo(2);
	assertThat(session.<String>getAttribute("a")).isEqualTo("b");
	assertThat(session.<String>getAttribute("1")).isEqualTo("2");

	this.repository.deleteById(toSave.getId()).block();
}
 
Example 12
/**
 * Tries to determine the principal's name from the given Session.
 *
 * @param session
 * @return the principal's name, or empty String if it couldn't be determined
 */
private static String resolvePrincipal(Session session) {
    String principalName = session.getAttribute(PRINCIPAL_NAME_INDEX_NAME);
    if (principalName != null) {
        return principalName;
    }
    SecurityContext securityContext = session.getAttribute("SPRING_SECURITY_CONTEXT");
    if (securityContext != null && securityContext.getAuthentication() != null) {
        return securityContext.getAuthentication().getName();
    }
    return "";
}
 
Example 13
public void onNewSession(Session session, HttpServletRequest request, HttpServletResponse response) {
	Set<String> sessionIdsWritten = getSessionIdsWritten(request);
	if(sessionIdsWritten.contains(session.getId())) {
		return;
	}
	sessionIdsWritten.add(session.getId());

	Map<String,String> sessionIds = getSessionIds(request);
	String sessionAlias = getCurrentSessionAlias(request);
	sessionIds.put(sessionAlias, session.getId());
	Cookie sessionCookie = createSessionCookie(request, sessionIds);
	response.addCookie(sessionCookie);
}
 
Example 14
Source Project: redisson   Source File: RedissonSessionRepository.java    License: Apache License 2.0 5 votes vote down vote up
String resolvePrincipal(Session session) {
    String principalName = session.getAttribute(PRINCIPAL_NAME_INDEX_NAME);
    if (principalName != null) {
        return principalName;
    }
    
    Object auth = session.getAttribute(SPRING_SECURITY_CONTEXT);
    if (auth == null) {
        return null;
    }
    
    Expression expression = SPEL_PARSER.parseExpression("authentication?.name");
    return expression.getValue(auth, String.class);
}
 
Example 15
@Test
@SuppressWarnings("unused")
void findByUsername() {
	// tag::findby-username[]
	String username = "username";
	Map<String, Session> sessionIdToSession = this.sessionRepository.findByPrincipalName(username);
	// end::findby-username[]
}
 
Example 16
Source Project: spring-session   Source File: IndexDocTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unused")
void newRedisIndexedSessionRepository() {
	// tag::new-redisindexedsessionrepository[]
	RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();

	// ... configure redisTemplate ...

	SessionRepository<? extends Session> repository = new RedisIndexedSessionRepository(redisTemplate);
	// end::new-redisindexedsessionrepository[]
}
 
Example 17
Source Project: spring-session   Source File: IndexDocTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unused")
void mapRepository() {
	// tag::new-mapsessionrepository[]
	SessionRepository<? extends Session> repository = new MapSessionRepository(new ConcurrentHashMap<>());
	// end::new-mapsessionrepository[]
}
 
Example 18
@Test
void springSessionDestroyedTranslatedToSpringSecurityDestroyed() {
	Session session = new MapSession();

	this.publisher.publishEvent(new org.springframework.session.events.SessionDestroyedEvent(this, session));

	assertThat(this.listener.getEvent().getId()).isEqualTo(session.getId());
}
 
Example 19
Source Project: spring-session   Source File: Initializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
	this.instance = createHazelcastInstance();
	Map<String, Session> sessions = this.instance.getMap(SESSION_MAP_NAME);

	MapSessionRepository sessionRepository = new MapSessionRepository(sessions);
	SessionRepositoryFilter<? extends Session> filter = new SessionRepositoryFilter<>(sessionRepository);

	Dynamic fr = sce.getServletContext().addFilter("springSessionFilter", filter);
	fr.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
}
 
Example 20
/**
 * Tries to determine the principal's name from the given Session.
 * @param session the session
 * @return the principal's name, or empty String if it couldn't be determined
 */
private static String resolvePrincipal(Session session) {
	String principalName = session.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
	if (principalName != null) {
		return principalName;
	}
	SecurityContext securityContext = session.getAttribute(SPRING_SECURITY_CONTEXT);
	if (securityContext != null && securityContext.getAuthentication() != null) {
		return securityContext.getAuthentication().getName();
	}
	return "";
}
 
Example 21
@Bean
public <S extends Session> SessionRepositoryFilter<? extends Session> springSessionRepositoryFilter(
		SessionRepository<S> sessionRepository) {
	SessionRepositoryFilter<S> sessionRepositoryFilter = new SessionRepositoryFilter<>(sessionRepository);
	sessionRepositoryFilter.setHttpSessionIdResolver(this.httpSessionIdResolver);
	return sessionRepositoryFilter;
}
 
Example 22
/**
 * Configure a {@link WebSessionManager} using a provided
 * {@link ReactiveSessionRepository}.
 * @param repository a bean that implements {@link ReactiveSessionRepository}.
 * @return a configured {@link WebSessionManager} registered with a preconfigured
 * name.
 */
@Bean(WebHttpHandlerBuilder.WEB_SESSION_MANAGER_BEAN_NAME)
public WebSessionManager webSessionManager(ReactiveSessionRepository<? extends Session> repository) {
	SpringSessionWebSessionStore<? extends Session> sessionStore = new SpringSessionWebSessionStore<>(repository);
	DefaultWebSessionManager manager = new DefaultWebSessionManager();
	manager.setSessionStore(sessionStore);

	if (this.webSessionIdResolver != null) {
		manager.setSessionIdResolver(this.webSessionIdResolver);
	}

	return manager;
}
 
Example 23
@Test
void preSendExpiredSession() {
	setSessionId("expired");

	this.interceptor.preSend(createMessage(), this.channel);

	verify(this.sessionRepository, times(0)).save(any(Session.class));
}
 
Example 24
@BeforeEach
void setup() {
	MockitoAnnotations.initMocks(this);
	this.listener = new SessionEventHttpSessionListenerAdapter(Arrays.asList(this.listener1, this.listener2));
	this.listener.setServletContext(new MockServletContext());

	Session session = new MapSession();
	this.destroyed = new SessionDestroyedEvent(this, session);
	this.created = new SessionCreatedEvent(this, session);
}
 
Example 25
@Test
void onNewSessionTwiceNewId() {
	Session newSession = new MapSession();

	this.strategy.setSessionId(this.request, this.response, this.session.getId());
	this.strategy.setSessionId(this.request, this.response, newSession.getId());

	Cookie[] cookies = this.response.getCookies();
	assertThat(cookies).hasSize(2);

	assertThat(base64Decode(cookies[0].getValue())).isEqualTo(this.session.getId());
	assertThat(base64Decode(cookies[1].getValue())).isEqualTo(newSession.getId());
}
 
Example 26
@Test
void sessionInformationForExistingSession() {
	Session session = createSession(SESSION_ID, USER_NAME, NOW);
	when(this.sessionRepository.findById(SESSION_ID)).thenReturn(session);

	SessionInformation sessionInfo = this.sessionRegistry.getSessionInformation(SESSION_ID);

	assertThat(sessionInfo.getSessionId()).isEqualTo(SESSION_ID);
	assertThat(sessionInfo.getLastRequest().toInstant().truncatedTo(ChronoUnit.MILLIS))
			.isEqualTo(NOW.truncatedTo(ChronoUnit.MILLIS));
	assertThat(sessionInfo.getPrincipal()).isEqualTo(USER_NAME);
	assertThat(sessionInfo.isExpired()).isFalse();
}
 
Example 27
@Test
void sessionInformationForExpiredSession() {
	Session session = createSession(SESSION_ID, USER_NAME, NOW);
	session.setAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR, Boolean.TRUE);
	when(this.sessionRepository.findById(SESSION_ID)).thenReturn(session);

	SessionInformation sessionInfo = this.sessionRegistry.getSessionInformation(SESSION_ID);

	assertThat(sessionInfo.getSessionId()).isEqualTo(SESSION_ID);
	assertThat(sessionInfo.getLastRequest().toInstant().truncatedTo(ChronoUnit.MILLIS))
			.isEqualTo(NOW.truncatedTo(ChronoUnit.MILLIS));
	assertThat(sessionInfo.getPrincipal()).isEqualTo(USER_NAME);
	assertThat(sessionInfo.isExpired()).isTrue();
}
 
Example 28
private Session createSession(String sessionId, String userName, Instant lastAccessed) {
	MapSession session = new MapSession(sessionId);
	session.setLastAccessedTime(lastAccessed);
	Authentication authentication = mock(Authentication.class);
	when(authentication.getName()).thenReturn(userName);
	SecurityContextImpl securityContext = new SecurityContextImpl();
	securityContext.setAuthentication(authentication);
	session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
	return session;
}
 
Example 29
private void setUpSessions() {
	Session session1 = createSession(SESSION_ID, USER_NAME, NOW);
	session1.setAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR, Boolean.TRUE);
	Session session2 = createSession(SESSION_ID2, USER_NAME, NOW);
	Map<String, Session> sessions = new LinkedHashMap<>();
	sessions.put(session1.getId(), session1);
	sessions.put(session2.getId(), session2);
	when(this.sessionRepository.findByPrincipalName(USER_NAME)).thenReturn(sessions);
}
 
Example 30
@Test
void saveSessionTest() throws InterruptedException {
	String username = "saves-" + System.currentTimeMillis();

	S sessionToSave = this.repository.createSession();

	String expectedAttributeName = "a";
	String expectedAttributeValue = "b";
	sessionToSave.setAttribute(expectedAttributeName, expectedAttributeValue);
	Authentication toSaveToken = new UsernamePasswordAuthenticationToken(username, "password",
			AuthorityUtils.createAuthorityList("ROLE_USER"));
	SecurityContext toSaveContext = SecurityContextHolder.createEmptyContext();
	toSaveContext.setAuthentication(toSaveToken);
	sessionToSave.setAttribute("SPRING_SECURITY_CONTEXT", toSaveContext);
	sessionToSave.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username);

	this.repository.save(sessionToSave);

	assertThat(this.registry.receivedEvent(sessionToSave.getId())).isTrue();
	assertThat(this.registry.<SessionCreatedEvent>getEvent(sessionToSave.getId()))
			.isInstanceOf(SessionCreatedEvent.class);

	Session session = this.repository.findById(sessionToSave.getId());

	assertThat(session.getId()).isEqualTo(sessionToSave.getId());
	assertThat(session.getAttributeNames()).isEqualTo(sessionToSave.getAttributeNames());
	assertThat(session.<String>getAttribute(expectedAttributeName))
			.isEqualTo(sessionToSave.getAttribute(expectedAttributeName));
}