-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
makeAuthenticatedReq to snap service
- Loading branch information
1 parent
589fecc
commit cdd2248
Showing
3 changed files
with
39 additions
and
25 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
package gcloud | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"io" | ||
"net/http" | ||
"os" | ||
|
||
"google.golang.org/api/idtoken" | ||
) | ||
|
||
// MakeAuthenticatedReq makes an HTTP request using Google Service Account credentials. | ||
// https://cloud.google.com/run/docs/authenticating/service-to-service#acquire-token | ||
func MakeAuthenticatedReq(ctx context.Context, method string, url string, body io.Reader) (*http.Request, error) { | ||
audience := url | ||
creds := os.Getenv("GCP_SA_CREDS_JSON") | ||
opts := idtoken.WithCredentialsJSON([]byte(creds)) | ||
|
||
if creds == "" { | ||
opts = idtoken.WithCredentialsFile("../creds.json") | ||
} | ||
ts, err := idtoken.NewTokenSource(ctx, audience, opts) | ||
if err != nil { | ||
return nil, fmt.Errorf("newTokenSource: %w", err) | ||
} | ||
token, err := ts.Token() | ||
if err != nil { | ||
return nil, fmt.Errorf("token: %w", err) | ||
} | ||
req, err := http.NewRequestWithContext(ctx, method, audience, body) | ||
token.SetAuthHeader(req) | ||
return req, err | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters