-
Notifications
You must be signed in to change notification settings - Fork 0
/
iap.go
65 lines (51 loc) · 1.75 KB
/
iap.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Package iapgo helps authenticating access to endpoints behind Google Cloud
// Identity-Aware Proxy (IAP). It provides a Transport which implements
// http.RoundTripper.
package iapgo
import (
"context"
"errors"
"net/http"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
var credentialsFinder = google.FindDefaultCredentials
var errUninitialized = errors.New("iapgo: unitialized Transport")
// Transport implements http.RoundTripper that can be used to access endpoints
// behind Google Cloud Identity-Aware Proxy.
type Transport struct {
oauthTransport *oauth2.Transport
}
// NewTransport returns an initialized Transport. It requires OAuth Client ID
// of the IAP resource target of the Transport. It finds the service account
// key using Application Default Credentials (ADC) strategy described in
// https://cloud.google.com/docs/authentication/production.
func NewTransport(iapClientID string) (*Transport, error) {
transport := &Transport{}
creds, err := credentialsFinder(context.Background())
if err != nil {
return nil, err
}
conf, err := google.JWTConfigFromJSON(creds.JSON)
if err != nil {
return nil, err
}
conf.PrivateClaims = map[string]interface{}{
"target_audience": iapClientID,
}
conf.UseIDToken = true
transport.oauthTransport = &oauth2.Transport{
Source: conf.TokenSource(context.Background()),
Base: http.DefaultTransport,
}
return transport, nil
}
// RoundTrip authenticates an HTTP request using an ID token. This ID token is
// retrieved using two-legged authentication with a Google endpoint defined in
// the service account key.
func (t *Transport) RoundTrip(r *http.Request) (*http.Response, error) {
if t.oauthTransport == nil {
return nil, errUninitialized
}
return t.oauthTransport.RoundTrip(r)
}