title: What is the correct way of retrieving an OAuth2 Bearer token in Spring
body: <p>I am making service to service requests using Spring's <code>WebClient</code> that require an <code>OAuth2</code> bearer token to be added as a header to the request.  I Can do this relatively easily by creating an <code>ExchangeFilterFunction</code> that intercepts the request, retrieves an access token, adds it to the header, and continues on.  Since this is not a user request, the <code>SecurityContextHolder</code> does not contain an Authentication that would hold an access token for me, so instead of retrieving from that, I would like to get an access token based on my Spring security configuration (currently defined in the <code>spring.security.oauth2.client.registration</code> and provider properties).</p>
  <p>The way I'm doing this now is by <code>Autowiring</code> an <code>OAuth2ClientContext</code> and then getting the <code>AccessToken</code> from it.  Reducing the code only to what I care about for this question, I have:</p>
  <pre><code>@Component
  public class OAuth2WebClientFilter implements ExchangeFilterFunction {
  
      @Autowired
      private OAuth2ClientContext oAuth2ClientContext;
  
      public Mono&lt;ClientResponse&gt; filter(ClientRequest request, ExchangeFunction next) {
          // simple retrieval of the token
          String oAuth2Token = oAuth2ClientContext.getAccessToken().getValue();
  
          // adding the token to the header of the request
          request = ClientRequest.from(request).header(HttpHeaders.AUTHORIZATION, &quot;Bearer &quot; + oAuth2Token).build();
      
          return next.exchange(request);
      }
  }
  
  </code></pre>
  <p>This does exactly what I want it to.  However, I have recently upgraded <code>spring-security-oauth2</code> to <code>2.5.0.RELEASE</code>, and it is saying the <code>OAuth2ClientContext</code> is deprecated, but I haven't found a simple replacement for this process.  So is there still a way to get an access token in a relatively simple fashion like above, and if so, how?</p>
  <p>Also note: this concept is used elsewhere in the project and not just for the <code>WebClient</code>, so I'm looking to see how to properly replace an injected <code>OAuth2ClientContext</code>. Thanks!</p>