### Question:
CustomTokenServices implements ResourceServerTokenServices { @Override public OAuth2Authentication loadAuthentication(String tokenString) { OAuth2AccessToken token = readAccessToken(tokenString); if (token == null) { logToAuditLogAndThrow("Invalid access token"); } if (token.isExpired() && token.getRefreshToken() == null) { tokenStore.removeAccessToken(token); logToAuditLogAndThrow(MessageFormat.format("The access token has expired on {0}", token.getExpiration())); } OAuth2Authentication auth = tokenStore.readAuthentication(token); if (auth == null) { TokenProperties tokenProperties = TokenProperties.fromToken(token); auth = SecurityUtil.createAuthentication(tokenProperties.getClientId(), token.getScope(), SecurityUtil.getTokenUserInfo(token)); try { LOGGER.info(MessageFormat.format(Messages.STORING_TOKEN_FOR_USER_0_WITH_EXPIRATION_TIME_1, tokenProperties.getUserName(), token.getExpiresIn())); tokenStore.storeAccessToken(token, auth); } catch (DataIntegrityViolationException e) { LOGGER.debug(Messages.ERROR_STORING_TOKEN_DUE_TO_INTEGRITY_VIOLATION, e); } } return auth; } @Inject  CustomTokenServices(TokenStore tokenStore, ApplicationConfiguration configuration, TokenParserChain tokenParserChain); @Override OAuth2Authentication loadAuthentication(String tokenString); @Override OAuth2AccessToken readAccessToken(String tokenString);  }### Answer:
@Test void testGetTokenFromCache() { OAuth2AccessToken token = buildValidToken(); OAuth2Authentication auth = buildAuthentication(token); prepareTokenParserChain(token); prepareTokenStore(token, auth); OAuth2Authentication loadedAuthentication = customTokenServices.loadAuthentication(DUMMY_TOKEN_STRING); assertEquals(auth.getAuthorities(), loadedAuthentication.getAuthorities()); assertEquals(auth.getCredentials(), loadedAuthentication.getCredentials()); assertEquals(auth.getOAuth2Request(), loadedAuthentication.getOAuth2Request()); }
@Test void testHandleExceptionForInvalidToken() { assertThrows(InvalidTokenException.class, () -> customTokenServices.loadAuthentication(DUMMY_TOKEN_STRING)); }
@Test void testWithExpiredToken() { OAuth2AccessToken token = buildInvalidToken(); prepareTokenParserChain(token); assertThrows(InvalidTokenException.class, () -> customTokenServices.loadAuthentication(DUMMY_TOKEN_STRING)); verify(tokenStore).removeAccessToken(eq(token)); }
@Test void testPersistTokenInCache() { OAuth2AccessToken token = buildValidToken(); prepareTokenParserChain(token); OAuth2Authentication auth = customTokenServices.loadAuthentication(DUMMY_TOKEN_STRING); assertNotNull(auth.getAuthorities()); assertNotNull(auth.getCredentials()); assertNotNull(auth.getOAuth2Request()); verify(tokenStore).storeAccessToken(token, auth); }