|
| 1 | +// http_client_oauth.go |
| 2 | +/* The http_client_auth package focuses on authentication mechanisms for an HTTP client. |
| 3 | +It provides structures and methods for handling OAuth-based authentication |
| 4 | +*/ |
| 5 | +package http_client |
| 6 | + |
| 7 | +import ( |
| 8 | + "bytes" |
| 9 | + "crypto/tls" |
| 10 | + "crypto/x509" |
| 11 | + "encoding/json" |
| 12 | + "fmt" |
| 13 | + "io" |
| 14 | + "net/http" |
| 15 | + "net/url" |
| 16 | + "os" |
| 17 | + "time" |
| 18 | +) |
| 19 | + |
| 20 | +const Authority = "https://login.microsoftonline.com/" |
| 21 | +const Scope = "https://graph.microsoft.com/.default" |
| 22 | + |
| 23 | +// OAuthResponse represents the response structure when obtaining an OAuth access token. |
| 24 | +type OAuthResponse struct { |
| 25 | + AccessToken string `json:"access_token"` |
| 26 | + ExpiresIn int64 `json:"expires_in"` |
| 27 | + TokenType string `json:"token_type"` |
| 28 | + RefreshToken string `json:"refresh_token,omitempty"` |
| 29 | + Error string `json:"error,omitempty"` |
| 30 | +} |
| 31 | + |
| 32 | +// ObtainOauthTokenWithApp fetches an OAuth access token using client credentials. |
| 33 | +func (c *Client) ObtainOauthTokenWithApp(tenantID, clientID, clientSecret string) (*OAuthResponse, error) { |
| 34 | + endpoint := fmt.Sprintf("%s%s/oauth2/v2.0/token", Authority, tenantID) |
| 35 | + |
| 36 | + data := url.Values{} |
| 37 | + data.Set("client_id", clientID) |
| 38 | + data.Set("scope", Scope) |
| 39 | + data.Set("client_secret", clientSecret) |
| 40 | + data.Set("grant_type", "client_credentials") |
| 41 | + |
| 42 | + req, err := http.NewRequest("POST", endpoint, bytes.NewBufferString(data.Encode())) |
| 43 | + if err != nil { |
| 44 | + return nil, err |
| 45 | + } |
| 46 | + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") |
| 47 | + |
| 48 | + client := &http.Client{} |
| 49 | + resp, err := client.Do(req) |
| 50 | + if err != nil { |
| 51 | + return nil, err |
| 52 | + } |
| 53 | + defer resp.Body.Close() |
| 54 | + |
| 55 | + bodyBytes, err := io.ReadAll(resp.Body) |
| 56 | + if err != nil { |
| 57 | + return nil, err |
| 58 | + } |
| 59 | + |
| 60 | + // Debug: Print the entire raw response body for inspection |
| 61 | + c.logger.Debug("Raw response body: %s\n", string(bodyBytes)) |
| 62 | + |
| 63 | + // Create a new reader from the body bytes for json unmarshalling |
| 64 | + bodyReader := bytes.NewReader(bodyBytes) |
| 65 | + |
| 66 | + oauthResp := &OAuthResponse{} |
| 67 | + err = json.NewDecoder(bodyReader).Decode(oauthResp) |
| 68 | + if err != nil { |
| 69 | + return nil, err |
| 70 | + } |
| 71 | + |
| 72 | + if oauthResp.Error != "" { |
| 73 | + return nil, fmt.Errorf("error obtaining OAuth token: %s", oauthResp.Error) |
| 74 | + } |
| 75 | + |
| 76 | + // Calculate and format token expiration time |
| 77 | + expiresIn := time.Duration(oauthResp.ExpiresIn) * time.Second |
| 78 | + expirationTime := time.Now().Add(expiresIn) |
| 79 | + formattedExpirationTime := expirationTime.Format(time.RFC1123) |
| 80 | + |
| 81 | + // Log the token life expiry details in a human-readable format |
| 82 | + c.logger.Debug("The OAuth token obtained is: ", |
| 83 | + "Valid for", expiresIn.String(), |
| 84 | + "Expires at", formattedExpirationTime) |
| 85 | + |
| 86 | + return oauthResp, nil |
| 87 | +} |
| 88 | + |
| 89 | +// ObtainOauthTokenWithCertificate fetches an OAuth access token using a certificate. |
| 90 | +func (c *Client) ObtainOauthTokenWithCertificate(tenantID, clientID, thumbprint, keyFile string) (*OAuthResponse, error) { |
| 91 | + endpoint := fmt.Sprintf("%s%s/oauth2/v2.0/token", Authority, tenantID) |
| 92 | + |
| 93 | + // Load the certificate |
| 94 | + certData, err := os.ReadFile(keyFile) |
| 95 | + if err != nil { |
| 96 | + return nil, fmt.Errorf("failed to read certificate file: %v", err) |
| 97 | + } |
| 98 | + |
| 99 | + cert, err := tls.X509KeyPair(certData, certData) |
| 100 | + if err != nil { |
| 101 | + return nil, fmt.Errorf("failed to parse certificate: %v", err) |
| 102 | + } |
| 103 | + |
| 104 | + // Create a custom HTTP client with the certificate |
| 105 | + certPool := x509.NewCertPool() |
| 106 | + certPool.AppendCertsFromPEM(certData) |
| 107 | + tlsConfig := &tls.Config{ |
| 108 | + Certificates: []tls.Certificate{cert}, |
| 109 | + RootCAs: certPool, |
| 110 | + InsecureSkipVerify: true, // Depending on your requirements, you might want to adjust this |
| 111 | + } |
| 112 | + client := &http.Client{ |
| 113 | + Transport: &http.Transport{ |
| 114 | + TLSClientConfig: tlsConfig, |
| 115 | + }, |
| 116 | + } |
| 117 | + |
| 118 | + // Prepare request data |
| 119 | + data := url.Values{} |
| 120 | + data.Set("client_id", clientID) |
| 121 | + data.Set("scope", Scope) |
| 122 | + data.Set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer") |
| 123 | + data.Set("client_assertion", thumbprint) // You might need to adjust this according to your requirements |
| 124 | + data.Set("grant_type", "client_credentials") |
| 125 | + |
| 126 | + req, err := http.NewRequest("POST", endpoint, bytes.NewBufferString(data.Encode())) |
| 127 | + if err != nil { |
| 128 | + return nil, err |
| 129 | + } |
| 130 | + req.Header.Add("Content-Type", "application/x-www-form-urlencoded") |
| 131 | + |
| 132 | + resp, err := client.Do(req) |
| 133 | + if err != nil { |
| 134 | + return nil, err |
| 135 | + } |
| 136 | + defer resp.Body.Close() |
| 137 | + |
| 138 | + bodyBytes, err := io.ReadAll(resp.Body) |
| 139 | + if err != nil { |
| 140 | + return nil, err |
| 141 | + } |
| 142 | + |
| 143 | + // Debug: Print the entire raw response body for inspection |
| 144 | + c.logger.Debug("Raw response body: %s\n", string(bodyBytes)) |
| 145 | + |
| 146 | + bodyReader := bytes.NewReader(bodyBytes) |
| 147 | + oauthResp := &OAuthResponse{} |
| 148 | + err = json.NewDecoder(bodyReader).Decode(oauthResp) |
| 149 | + if err != nil { |
| 150 | + return nil, err |
| 151 | + } |
| 152 | + |
| 153 | + if oauthResp.Error != "" { |
| 154 | + return nil, fmt.Errorf("error obtaining OAuth token: %s", oauthResp.Error) |
| 155 | + } |
| 156 | + |
| 157 | + expiresIn := time.Duration(oauthResp.ExpiresIn) * time.Second |
| 158 | + expirationTime := time.Now().Add(expiresIn) |
| 159 | + formattedExpirationTime := expirationTime.Format(time.RFC1123) |
| 160 | + c.logger.Debug("The OAuth token obtained is: ", |
| 161 | + "Valid for", expiresIn.String(), |
| 162 | + "Expires at", formattedExpirationTime) |
| 163 | + |
| 164 | + return oauthResp, nil |
| 165 | +} |
| 166 | + |
| 167 | +// GetOAuthCredentials retrieves the current OAuth credentials (Client ID and Client Secret) |
| 168 | +// set for the client instance. Used for test cases. |
| 169 | +func (c *Client) GetOAuthCredentials() OAuthCredentials { |
| 170 | + return c.OAuthCredentials |
| 171 | +} |
0 commit comments