View Javadoc
1   package com.guinetik.rr.auth;
2   
3   import java.util.HashMap;
4   import java.util.Map;
5   
6   /**
7    * Authentication strategy that implements OAuth 2.0 client credentials flow.
8    * This strategy gets and refreshes OAuth 2.0 access tokens using client credentials.
9    */
10  public class OAuth2ClientCredentialsStrategy extends AbstractOAuth2Strategy {
11  
12      private final String clientId;
13      private final String clientSecret;
14  
15      /**
16       * Creates a new OAuth 2.0 client credentials strategy.
17       *
18       * @param clientId     the OAuth 2.0 client ID
19       * @param clientSecret the OAuth 2.0 client secret
20       * @param tokenUrl     the OAuth 2.0 token endpoint URL
21       */
22      public OAuth2ClientCredentialsStrategy(String clientId, String clientSecret, String tokenUrl) {
23          this(clientId, clientSecret, tokenUrl, new HashMap<>());
24      }
25  
26      /**
27       * Creates a new OAuth 2.0 client credentials strategy with additional parameters.
28       *
29       * @param clientId         the OAuth 2.0 client ID
30       * @param clientSecret     the OAuth 2.0 client secret
31       * @param tokenUrl         the OAuth 2.0 token endpoint URL
32       * @param additionalParams additional parameters to include in the token request
33       */
34      public OAuth2ClientCredentialsStrategy(String clientId, String clientSecret, String tokenUrl,
35                                             Map<String, String> additionalParams) {
36          super(tokenUrl, additionalParams);
37          this.clientId = clientId;
38          this.clientSecret = clientSecret;
39      }
40  
41      @Override
42      public AuthType getType() {
43          return AuthType.OAUTH_CLIENT_CREDENTIALS;
44      }
45  
46      /**
47       * {@inheritDoc}
48       * @throws TokenRefreshException if the client ID or client secret is not provided.
49       */
50      @Override
51      protected void validateCredentials() {
52          if (clientId == null || clientSecret == null) {
53              throw new TokenRefreshException("Client ID and Client Secret are required for OAuth2 client credentials flow");
54          }
55      }
56  
57      /**
58       * {@inheritDoc}
59       * <p>
60       * Prepares parameters for the client credentials grant type, including
61       * grant_type, client_id, and client_secret.
62       */
63      @Override
64      protected Map<String, String> prepareTokenRequestParams() {
65          Map<String, String> formParams = new HashMap<>();
66          formParams.put("grant_type", "client_credentials");
67          formParams.put("client_id", clientId);
68          formParams.put("client_secret", clientSecret);
69          return formParams;
70      }
71  }