org.springframework.session.Session Java Examples
The following examples show how to use
org.springframework.session.Session.
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: JdbcIndexedSessionRepositoryTests.java From spring-session with Apache License 2.0 | 7 votes |
@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 #2
Source File: BootGeodeHttpSessionCachingApplicationIntegrationTests.java From spring-boot-data-geode with Apache License 2.0 | 6 votes |
@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 #3
Source File: AutoConfiguredSessionCachingIntegrationTests.java From spring-boot-data-geode with Apache License 2.0 | 6 votes |
@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 #4
Source File: SpringSessionBackedSessionRegistryTest.java From spring-session with Apache License 2.0 | 6 votes |
@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 #5
Source File: ReactiveRedisSessionRepositoryITests.java From spring-session with Apache License 2.0 | 6 votes |
@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 #6
Source File: ReactiveRedisSessionRepositoryITests.java From spring-session with Apache License 2.0 | 6 votes |
@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 #7
Source File: RedisIndexedSessionRepositoryITests.java From spring-session with Apache License 2.0 | 6 votes |
@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 #8
Source File: SessionRepositoryFilterTests.java From spring-session with Apache License 2.0 | 6 votes |
@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 #9
Source File: JdbcIndexedSessionRepositoryTests.java From spring-session with Apache License 2.0 | 6 votes |
@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 #10
Source File: IndexDocTests.java From spring-session with Apache License 2.0 | 6 votes |
@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 #11
Source File: IndexDocTests.java From spring-session with Apache License 2.0 | 6 votes |
@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 #12
Source File: SpringSessionBackedSessionRegistryTest.java From spring-session with Apache License 2.0 | 5 votes |
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 #13
Source File: SpringSessionBackedSessionInformation.java From spring-session-concurrent-session-control with Apache License 2.0 | 5 votes |
/** * 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 #14
Source File: SpringSessionBackedSessionRegistryTest.java From spring-session with Apache License 2.0 | 5 votes |
@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 #15
Source File: SpringSessionBackedSessionRegistryTest.java From spring-session with Apache License 2.0 | 5 votes |
@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 #16
Source File: CookieHttpSessionIdResolverTests.java From spring-session with Apache License 2.0 | 5 votes |
@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 #17
Source File: SessionEventHttpSessionListenerAdapterTests.java From spring-session with Apache License 2.0 | 5 votes |
@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 #18
Source File: SessionRepositoryMessageInterceptorTests.java From spring-session with Apache License 2.0 | 5 votes |
@Test void preSendExpiredSession() { setSessionId("expired"); this.interceptor.preSend(createMessage(), this.channel); verify(this.sessionRepository, times(0)).save(any(Session.class)); }
Example #19
Source File: IndexDocTests.java From spring-session with Apache License 2.0 | 5 votes |
@Test @SuppressWarnings("unused") void mapRepository() { // tag::new-mapsessionrepository[] SessionRepository<? extends Session> repository = new MapSessionRepository(new ConcurrentHashMap<>()); // end::new-mapsessionrepository[] }
Example #20
Source File: SessionSavingZuulPreFilter.java From tutorials with MIT License | 5 votes |
@Override public Object run() { RequestContext context = RequestContext.getCurrentContext(); HttpSession httpSession = context.getRequest().getSession(); Session session = repository.getSession(httpSession.getId()); context.addZuulRequestHeader("Cookie", "SESSION=" + httpSession.getId()); log.info("ZuulPreFilter session proxy: {}", session.getId()); return null; }
Example #21
Source File: SpringSessionBackedSessionRegistryTest.java From spring-session with Apache License 2.0 | 5 votes |
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 #22
Source File: SessionEventHazelcastIndexedSessionRepositoryTests.java From spring-session with Apache License 2.0 | 5 votes |
@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)); }
Example #23
Source File: ClientServerHazelcastIndexedSessionRepositoryITests.java From spring-session with Apache License 2.0 | 5 votes |
@Bean HazelcastInstance hazelcastInstance() { ClientConfig clientConfig = new ClientConfig(); clientConfig.getNetworkConfig() .addAddress(container.getContainerIpAddress() + ":" + container.getFirstMappedPort()); clientConfig.getUserCodeDeploymentConfig().setEnabled(true).addClass(Session.class) .addClass(MapSession.class).addClass(SessionUpdateEntryProcessor.class); return HazelcastClient.newHazelcastClient(clientConfig); }
Example #24
Source File: HazelcastHttpSessionConfigurationTests.java From spring-session with Apache License 2.0 | 5 votes |
@Test void customIndexResolverConfiguration() { registerAndRefresh(CustomIndexResolverConfiguration.class); HazelcastIndexedSessionRepository repository = this.context.getBean(HazelcastIndexedSessionRepository.class); @SuppressWarnings("unchecked") IndexResolver<Session> indexResolver = this.context.getBean(IndexResolver.class); assertThat(repository).isNotNull(); assertThat(indexResolver).isNotNull(); assertThat(repository).hasFieldOrPropertyWithValue("indexResolver", indexResolver); }
Example #25
Source File: JdbcIndexedSessionRepositoryTests.java From spring-session with Apache License 2.0 | 5 votes |
@Test @SuppressWarnings("unchecked") void getSessionExpired() { Session expired = this.repository.createSession(); expired.setLastAccessedTime(Instant.now().minusSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1)); given(this.jdbcOperations.query(isA(String.class), isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class))).willReturn(Collections.singletonList(expired)); JdbcSession session = this.repository.findById(expired.getId()); assertThat(session).isNull(); verify(this.jdbcOperations, times(1)).query(isA(String.class), isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class)); verify(this.jdbcOperations, times(1)).update(startsWith("DELETE"), eq(expired.getId())); }
Example #26
Source File: JdbcHttpSessionConfigurationTests.java From spring-session with Apache License 2.0 | 5 votes |
@Test void customIndexResolverConfiguration() { registerAndRefresh(DataSourceConfiguration.class, CustomIndexResolverConfiguration.class); JdbcIndexedSessionRepository repository = this.context.getBean(JdbcIndexedSessionRepository.class); @SuppressWarnings("unchecked") IndexResolver<Session> indexResolver = this.context.getBean(IndexResolver.class); assertThat(repository).isNotNull(); assertThat(indexResolver).isNotNull(); assertThat(repository).hasFieldOrPropertyWithValue("indexResolver", indexResolver); }
Example #27
Source File: RedisIndexedSessionRepositoryTests.java From spring-session with Apache License 2.0 | 5 votes |
@Test void createSessionCustomMaxInactiveInterval() { int interval = 1; this.redisRepository.setDefaultMaxInactiveInterval(interval); Session session = this.redisRepository.createSession(); assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofSeconds(interval)); }
Example #28
Source File: RedisHttpSessionConfigurationTests.java From spring-session with Apache License 2.0 | 5 votes |
@Test void customIndexResolverConfiguration() { registerAndRefresh(RedisConfig.class, CustomIndexResolverConfiguration.class); RedisIndexedSessionRepository repository = this.context.getBean(RedisIndexedSessionRepository.class); @SuppressWarnings("unchecked") IndexResolver<Session> indexResolver = this.context.getBean(IndexResolver.class); assertThat(repository).isNotNull(); assertThat(indexResolver).isNotNull(); assertThat(repository).hasFieldOrPropertyWithValue("indexResolver", indexResolver); }
Example #29
Source File: PrincipalToRequestHeaderFilterFactory.java From syncope with Apache License 2.0 | 5 votes |
@Override public GatewayFilter apply(final NameConfig config) { return (exchange, chain) -> exchange.getSession(). flatMap(session -> Mono.justOrEmpty(Optional.ofNullable( cacheManager.getCache(SessionConfig.DEFAULT_CACHE).get(session.getId(), Session.class)). map(cachedSession -> { String principal = null; SecurityContext ctx = cachedSession.getAttribute( WebSessionServerSecurityContextRepository.DEFAULT_SPRING_SECURITY_CONTEXT_ATTR_NAME); if (ctx != null && ctx.getAuthentication() != null) { if (ctx.getAuthentication().getPrincipal() instanceof OidcUser) { principal = ((OidcUser) ctx.getAuthentication().getPrincipal()). getIdToken().getTokenValue(); } else if (ctx.getAuthentication().getPrincipal() instanceof OAuth2User) { principal = Objects.toString(((OAuth2User) ctx.getAuthentication().getPrincipal()). getAttributes().get(StandardClaimNames.PREFERRED_USERNAME), null); } else { principal = ctx.getAuthentication().getName(); } } return principal; }))). transform(principal -> principal.flatMap(p -> StringUtils.isEmpty(p) ? chain.filter(exchange) : chain.filter(exchange.mutate(). request(exchange.getRequest().mutate(). headers(headers -> headers.add(config.getName(), p)).build()). build()))). switchIfEmpty(chain.filter(exchange)); }
Example #30
Source File: CookieHttpSessionStrategy.java From lemon with Apache License 2.0 | 5 votes |
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); }