org.springframework.session.FindByIndexNameSessionRepository Java Examples

The following examples show how to use org.springframework.session.FindByIndexNameSessionRepository. 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: TokenServiceImpl.java    From oauth-server with Apache License 2.0 6 votes vote down vote up
@Override
public void deleteAllUnderUser(String loginName) {
    //筛选token
    AccessTokenDO accessTokenDO = new AccessTokenDO();
    accessTokenDO.setUserName(loginName);
    List<AccessTokenDO> select = accessTokenMapper.select(accessTokenDO);
    //删除loginName下的所有db accessToken
    accessTokenMapper.deleteUsersToken(loginName);
    //删除对应的db refreshToken
    select.forEach(t ->
            refreshTokenMapper.deleteByPrimaryKey(t.getRefreshToken())
    );
    //删除userId下的所有redis session
    Map<String, Object> byIndexNameAndIndexValue = findByIndexNameSessionRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, loginName);
    redisTemplate.delete(byIndexNameAndIndexValue.keySet().stream().map(s -> SESSION_KEY_PREFIX + s).collect(Collectors.toList()));
}
 
Example #2
Source File: JdbcIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: AbstractHazelcastIndexedSessionRepositoryITests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test
void createSessionWithSecurityContextAndFindByPrincipal() {
	Assumptions.assumeTrue(this.hazelcastInstance instanceof HazelcastInstanceProxy,
			"Hazelcast runs in embedded server topology");

	HazelcastSession session = this.repository.createSession();

	String username = "saves-" + System.currentTimeMillis();
	Authentication authentication = new UsernamePasswordAuthenticationToken(username, "password",
			AuthorityUtils.createAuthorityList("ROLE_USER"));
	SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
	securityContext.setAuthentication(authentication);
	session.setAttribute(SPRING_SECURITY_CONTEXT, securityContext);

	this.repository.save(session);

	assertThat(this.repository
			.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username))
					.hasSize(1);
}
 
Example #4
Source File: PrincipalNameExtractor.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void extract(MapSession target, String argument, ValueCollector collector) {
	String principalName = target.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
	if (principalName != null) {
		collector.addObject(principalName);
	}
}
 
Example #5
Source File: RedisIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void findByPrincipalName() {
	Instant lastAccessed = Instant.now().minusMillis(10);
	Instant createdTime = lastAccessed.minusMillis(10);
	Duration maxInactive = Duration.ofHours(1);
	String sessionId = "some-id";
	given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
	given(this.boundSetOperations.members()).willReturn(Collections.singleton(sessionId));
	given(this.redisOperations.boundHashOps(getKey(sessionId))).willReturn(this.boundHashOperations);
	Map map = map(RedisSessionMapper.CREATION_TIME_KEY, createdTime.toEpochMilli(),
			RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, (int) maxInactive.getSeconds(),
			RedisSessionMapper.LAST_ACCESSED_TIME_KEY, lastAccessed.toEpochMilli());
	given(this.boundHashOperations.entries()).willReturn(map);

	Map<String, RedisSession> sessionIdToSessions = this.redisRepository
			.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal");

	assertThat(sessionIdToSessions).hasSize(1);
	RedisSession session = sessionIdToSessions.get(sessionId);
	assertThat(session).isNotNull();
	assertThat(session.getId()).isEqualTo(sessionId);
	assertThat(session.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS))
			.isEqualTo(lastAccessed.truncatedTo(ChronoUnit.MILLIS));
	assertThat(session.getMaxInactiveInterval()).isEqualTo(maxInactive);
	assertThat(session.getCreationTime().truncatedTo(ChronoUnit.MILLIS))
			.isEqualTo(createdTime.truncatedTo(ChronoUnit.MILLIS));
}
 
Example #6
Source File: RedisIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void findByPrincipalNameExpired() {
	String expiredId = "expired-id";
	given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
	given(this.boundSetOperations.members()).willReturn(Collections.singleton(expiredId));
	given(this.redisOperations.boundHashOps(getKey(expiredId))).willReturn(this.boundHashOperations);
	Map map = map(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1, RedisSessionMapper.LAST_ACCESSED_TIME_KEY,
			Instant.now().minus(5, ChronoUnit.MINUTES).toEpochMilli());
	given(this.boundHashOperations.entries()).willReturn(map);

	assertThat(this.redisRepository
			.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, "principal"))
					.isEmpty();
}
 
Example #7
Source File: RedisIndexedSessionRepository.java    From spring-session with Apache License 2.0 5 votes vote down vote up
/**
 * Saves any attributes that have been changed and updates the expiration of this
 * session.
 */
private void saveDelta() {
	if (this.delta.isEmpty()) {
		return;
	}
	String sessionId = getId();
	getSessionBoundHashOperations(sessionId).putAll(this.delta);
	String principalSessionKey = getSessionAttrNameKey(
			FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
	String securityPrincipalSessionKey = getSessionAttrNameKey(SPRING_SECURITY_CONTEXT);
	if (this.delta.containsKey(principalSessionKey) || this.delta.containsKey(securityPrincipalSessionKey)) {
		if (this.originalPrincipalName != null) {
			String originalPrincipalRedisKey = getPrincipalKey(this.originalPrincipalName);
			RedisIndexedSessionRepository.this.sessionRedisOperations.boundSetOps(originalPrincipalRedisKey)
					.remove(sessionId);
		}
		Map<String, String> indexes = RedisIndexedSessionRepository.this.indexResolver.resolveIndexesFor(this);
		String principal = indexes.get(PRINCIPAL_NAME_INDEX_NAME);
		this.originalPrincipalName = principal;
		if (principal != null) {
			String principalRedisKey = getPrincipalKey(principal);
			RedisIndexedSessionRepository.this.sessionRedisOperations.boundSetOps(principalRedisKey)
					.add(sessionId);
		}
	}

	this.delta = new HashMap<>(this.delta.size());

	Long originalExpiration = (this.originalLastAccessTime != null)
			? this.originalLastAccessTime.plus(getMaxInactiveInterval()).toEpochMilli() : null;
	RedisIndexedSessionRepository.this.expirationPolicy.onExpirationUpdated(originalExpiration, this);
}
 
Example #8
Source File: JdbcIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void findByIndexNameAndIndexValuePrincipalIndexNameNotFound() {
	String principal = "username";
	given(this.jdbcOperations.query(isA(String.class), isA(PreparedStatementSetter.class),
			isA(ResultSetExtractor.class))).willReturn(Collections.emptyList());

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

	assertThat(sessions).isEmpty();
	verify(this.jdbcOperations, times(1)).query(isA(String.class), isA(PreparedStatementSetter.class),
			isA(ResultSetExtractor.class));
}
 
Example #9
Source File: SessionEventHazelcastIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@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 #10
Source File: SpringSessionBackedSessionInformation.java    From spring-session with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #11
Source File: FindByIndexNameSessionRepositoryTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
void setUsername() {
	// tag::set-username[]
	String username = "username";
	this.session.setAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username);
	// end::set-username[]
}
 
Example #12
Source File: WebSessionConfiguration.java    From cola with MIT License 4 votes vote down vote up
@Bean
@ConditionalOnBean(FindByIndexNameSessionRepository.class)
public SpringSessionBackedSessionRegistry springSessionBackedSessionRegistry(FindByIndexNameSessionRepository repository) {
	return new SpringSessionBackedSessionRegistry(repository);
}
 
Example #13
Source File: SpringSessionBackedSessionRegistry.java    From spring-session with Apache License 2.0 4 votes vote down vote up
public SpringSessionBackedSessionRegistry(FindByIndexNameSessionRepository<S> sessionRepository) {
	Assert.notNull(sessionRepository, "sessionRepository cannot be null");
	this.sessionRepository = sessionRepository;
}
 
Example #14
Source File: RedissonSessionRepository.java    From redisson with Apache License 2.0 4 votes vote down vote up
String getPrincipalKey(String principalName) {
    return keyPrefix + "index:" + FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME + ":" + principalName;
}
 
Example #15
Source File: RedisIndexedSessionRepository.java    From spring-session with Apache License 2.0 4 votes vote down vote up
String getPrincipalKey(String principalName) {
	return this.namespace + "index:" + FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME + ":"
			+ principalName;
}
 
Example #16
Source File: SpringSessionBackedSessionRegistry.java    From spring-session-concurrent-session-control with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("SpringJavaAutowiringInspection")
@Autowired
public SpringSessionBackedSessionRegistry(FindByIndexNameSessionRepository<? extends ExpiringSession> sessionRepository) {
    this.sessionRepository = sessionRepository;
}
 
Example #17
Source File: CookieController.java    From SpringCloud-Shop with Apache License 2.0 4 votes vote down vote up
@RequestMapping("/test/findByUsername")
@ResponseBody
public Map findByUsername(@RequestParam String username) {
    Map<String, ? extends ExpiringSession> usersSessions = sessionRepository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username);
    return usersSessions;
}
 
Example #18
Source File: TokenServiceImpl.java    From oauth-server with Apache License 2.0 4 votes vote down vote up
public TokenServiceImpl(StringRedisTemplate redisTemplate, FindByIndexNameSessionRepository findByIndexNameSessionRepository, AccessTokenMapper accessTokenMapper, RefreshTokenMapper refreshTokenMapper) {
    this.redisTemplate = redisTemplate;
    this.findByIndexNameSessionRepository = findByIndexNameSessionRepository;
    this.accessTokenMapper = accessTokenMapper;
    this.refreshTokenMapper = refreshTokenMapper;
}