title: How to store OAuth token in database?
body: <p>Using Java 8 and Spring Boot 1.5.2</p>
  
  <p>Spring Security: I'm trying to store tokens in Cassandra database. To achieve this I've implemented TokenStore. I ran the program and noticed that <code>getAccessToken(...)</code> method is called before <code>storeAccessToken(...)</code> and due to this token is always null. What do I need to do to first store access token in database and then query for it?</p>
  
  <pre><code>@Override
  public OAuth2AccessToken getAccessToken(final OAuth2Authentication authentication) {
      OAuth2AccessToken accessToken = null;
  
      final String key = authenticationKeyGenerator.extractKey(authentication);
  
      final Select select = QueryBuilder.select("token_body").from("authentication_service", "oauth_access_token");
      select.where(QueryBuilder.eq("authentication_id", key));
      final ByteBuffer token = cassandraOperations.queryForObject(select, ByteBuffer.class);
      if (token != null) {
          accessToken = deserializeAccessToken(token.array());
          if (accessToken != null &amp;&amp; !key.equals(authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) {
              removeAccessToken(accessToken.getValue());
              storeAccessToken(accessToken, authentication);
          }
      }
      return accessToken;
  }
  </code></pre>
  
  <p>storeAccessToken(...)</p>
  
  <pre><code>@Override
  public void storeAccessToken(final OAuth2AccessToken token, final OAuth2Authentication authentication) {
      String refreshToken = null;
      if (token.getRefreshToken() != null) {
          refreshToken = token.getRefreshToken().getValue();
      }
  
      if (readAccessToken(token.getValue()) != null) {
          removeAccessToken(token.getValue());
      }
  
      final AccessTokenBuilder accessTokenBuilder = new AccessTokenBuilder();
      accessTokenRepository.save(accessTokenBuilder
                                         .authenticationId(authenticationKeyGenerator.extractKey(authentication))
                                         .tokenId(extractTokenKey(token.getValue()))
                                         .tokenBody(ByteBuffer.wrap(serializeAccessToken(token)))
                                         .username(authentication.getName())
                                         .clientId(authentication.getOAuth2Request().getClientId())
                                         .authentication(ByteBuffer.wrap(serializeAuthentication(authentication)))
                                         .refreshTokenId(extractTokenKey(refreshToken))
                                         .createAccessToken());
  
  }
  </code></pre>