View Javadoc
1   package com.guinetik.rr.auth;
2   
3   import com.guinetik.rr.http.RocketHeaders;
4   
5   /**
6    * Authentication strategy that uses HTTP Basic authentication.
7    *
8    * <p>This strategy adds an {@code Authorization: Basic <base64>} header to all requests,
9    * where the base64 value is the encoded {@code username:password} string.
10   *
11   * <h2>Usage</h2>
12   * <pre class="language-java"><code>
13   * // Create via factory (recommended)
14   * AuthStrategy auth = AuthStrategyFactory.createBasicAuth("username", "password");
15   *
16   * // Configure client
17   * RocketRestConfig config = RocketRestConfig.builder("https://api.example.com")
18   *     .authStrategy(auth)
19   *     .build();
20   *
21   * RocketRest client = new RocketRest(config);
22   * </code></pre>
23   *
24   * <p><b>Security Note:</b> Basic authentication transmits credentials in base64 encoding
25   * (not encryption). Always use HTTPS when using basic authentication.
26   *
27   * @author guinetik &lt;guinetik@gmail.com&gt;
28   * @see AuthStrategy
29   * @see AuthStrategyFactory#createBasicAuth(String, String)
30   * @since 1.0.0
31   */
32  public class BasicAuthStrategy implements AuthStrategy {
33  
34      private final String username;
35      private final String password;
36  
37      /**
38       * Creates a new BasicAuthStrategy.
39       *
40       * @param username the username for basic authentication
41       * @param password the password for basic authentication
42       */
43      public BasicAuthStrategy(String username, String password) {
44          this.username = username;
45          this.password = password;
46      }
47  
48      @Override
49      public AuthType getType() {
50          return AuthType.BASIC;
51      }
52  
53      @Override
54      public RocketHeaders applyAuthHeaders(RocketHeaders headers) {
55          if (username != null && password != null) {
56              headers.basicAuth(username, password);
57          }
58          return headers;
59      }
60  
61      @Override
62      public boolean needsTokenRefresh() {
63          return false;
64      }
65  
66      @Override
67      public boolean refreshCredentials() {
68          // Basic auth doesn't require credential refresh
69          return true;
70      }
71  }