...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package idtoken_test
16
17 import (
18 "context"
19 "log"
20 "net/http"
21 "os"
22 "strings"
23 "testing"
24
25 "cloud.google.com/go/auth/credentials/idtoken"
26 "cloud.google.com/go/auth/httptransport"
27 "cloud.google.com/go/auth/internal/credsfile"
28 "cloud.google.com/go/auth/internal/testutil"
29 )
30
31 const (
32 aud = "http://example.com"
33 )
34
35 func TestNewCredentials_CredentialsFile(t *testing.T) {
36 testutil.IntegrationTestCheck(t)
37 ctx := context.Background()
38 ts, err := idtoken.NewCredentials(&idtoken.Options{
39 Audience: "http://example.com",
40 CredentialsFile: os.Getenv(credsfile.GoogleAppCredsEnvVar),
41 })
42 if err != nil {
43 t.Fatalf("unable to create credentials: %v", err)
44 }
45 tok, err := ts.Token(ctx)
46 if err != nil {
47 t.Fatalf("unable to retrieve Token: %v", err)
48 }
49 req := &http.Request{Header: make(http.Header)}
50 httptransport.SetAuthHeader(tok, req)
51 if !strings.HasPrefix(req.Header.Get("Authorization"), "Bearer ") {
52 t.Fatalf("token should sign requests with Bearer Authorization header")
53 }
54 validTok, err := idtoken.Validate(context.Background(), tok.Value, aud)
55 if err != nil {
56 t.Fatalf("token validation failed: %v", err)
57 }
58 if validTok.Audience != aud {
59 t.Fatalf("got %q, want %q", validTok.Audience, aud)
60 }
61 }
62
63 func TestNewCredentials_CredentialsJSON(t *testing.T) {
64 testutil.IntegrationTestCheck(t)
65 ctx := context.Background()
66 b, err := os.ReadFile(os.Getenv(credsfile.GoogleAppCredsEnvVar))
67 if err != nil {
68 log.Fatal(err)
69 }
70 creds, err := idtoken.NewCredentials(&idtoken.Options{
71 Audience: aud,
72 CredentialsJSON: b,
73 })
74 if err != nil {
75 t.Fatalf("unable to create Client: %v", err)
76 }
77 tok, err := creds.Token(ctx)
78 if err != nil {
79 t.Fatalf("unable to retrieve Token: %v", err)
80 }
81 validTok, err := idtoken.Validate(context.Background(), tok.Value, aud)
82 if err != nil {
83 t.Fatalf("token validation failed: %v", err)
84 }
85 if validTok.Audience != aud {
86 t.Fatalf("got %q, want %q", validTok.Audience, aud)
87 }
88 }
89
View as plain text