Last active
January 27, 2023 13:01
-
-
Save kramarz/6d132c34372614570fd5808335ba4a9c to your computer and use it in GitHub Desktop.
Get domain wide delegation token using credentials API.
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
// Copyright 2014 The Go Authors. All rights reserved. | |
// Use of this source code is governed by a BSD-style | |
// license that can be found in the LICENSE file. | |
package jwt | |
import ( | |
"context" | |
"encoding/json" | |
"fmt" | |
"io" | |
"io/ioutil" | |
"net/url" | |
"strings" | |
"time" | |
credentialspb "cloud.google.com/go/iam/credentials/apiv1/credentialspb" | |
credentials "cloud.google.com/go/iam/credentials/apiv1" | |
"golang.org/x/oauth2" | |
"golang.org/x/oauth2/jws" | |
) | |
const GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token" | |
const DEFAULT_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer" | |
// provide an email of a service account that your default credentials has permission to call signJWT: | |
// https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signJwt | |
func TokenSource(ctx context.Context, email string, scopes []string, subject string) oauth2.TokenSource { | |
return oauth2.ReuseTokenSource(nil, jwtSource{ctx, email, scopes, subject}) | |
} | |
type jwtSource struct { | |
ctx context.Context | |
email string | |
scopes []string | |
subject string | |
} | |
func (js jwtSource) Token() (*oauth2.Token, error) { | |
hc := oauth2.NewClient(js.ctx, nil) | |
iamc, err := credentials.NewIamCredentialsClient(js.ctx) | |
if err != nil { | |
return nil, err | |
} | |
defer iamc.Close() | |
iat := time.Now() | |
exp := iat.Add(time.Hour) | |
claimSet := map[string]interface{}{ | |
"iss": js.email, | |
"scope": strings.Join(js.scopes, " "), | |
"aud": GOOGLE_OAUTH2_TOKEN_ENDPOINT, | |
"iat": iat.Unix(), | |
"exp": exp.Unix(), | |
} | |
if subject := js.subject; subject != "" { | |
claimSet["sub"] = subject | |
claimSet["prn"] = subject | |
} | |
payload, _ := json.Marshal(claimSet) | |
req := &credentialspb.SignJwtRequest{ | |
Name: "projects/-/serviceAccounts/" + js.email, | |
Payload: string(payload), | |
} | |
signResp, err := iamc.SignJwt(js.ctx, req) | |
if err != nil { | |
return nil, err | |
} | |
v := url.Values{} | |
v.Set("grant_type", DEFAULT_GRANT_TYPE) | |
v.Set("assertion", signResp.SignedJwt) | |
resp, err := hc.PostForm(GOOGLE_OAUTH2_TOKEN_ENDPOINT, v) | |
if err != nil { | |
return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err) | |
} | |
defer resp.Body.Close() | |
body, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1<<20)) | |
if err != nil { | |
return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err) | |
} | |
if c := resp.StatusCode; c < 200 || c > 299 { | |
return nil, &oauth2.RetrieveError{ | |
Response: resp, | |
Body: body, | |
} | |
} | |
var tokenRes struct { | |
AccessToken string `json:"access_token"` | |
TokenType string `json:"token_type"` | |
IDToken string `json:"id_token"` | |
ExpiresIn int64 `json:"expires_in"` // relative seconds from now | |
} | |
if err := json.Unmarshal(body, &tokenRes); err != nil { | |
return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err) | |
} | |
token := &oauth2.Token{ | |
AccessToken: tokenRes.AccessToken, | |
TokenType: tokenRes.TokenType, | |
} | |
raw := make(map[string]interface{}) | |
json.Unmarshal(body, &raw) // no error checks for optional fields | |
token = token.WithExtra(raw) | |
if secs := tokenRes.ExpiresIn; secs > 0 { | |
token.Expiry = time.Now().Add(time.Duration(secs) * time.Second) | |
} | |
if v := tokenRes.IDToken; v != "" { | |
claimSet, err := jws.Decode(v) | |
if err != nil { | |
return nil, fmt.Errorf("oauth2: error decoding JWT token: %v", err) | |
} | |
token.Expiry = time.Unix(claimSet.Exp, 0) | |
} | |
return token, nil | |
} |
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
Copyright (c) 2009 The Go Authors. All rights reserved. | |
Redistribution and use in source and binary forms, with or without | |
modification, are permitted provided that the following conditions are | |
met: | |
* Redistributions of source code must retain the above copyright | |
notice, this list of conditions and the following disclaimer. | |
* Redistributions in binary form must reproduce the above | |
copyright notice, this list of conditions and the following disclaimer | |
in the documentation and/or other materials provided with the | |
distribution. | |
* Neither the name of Google Inc. nor the names of its | |
contributors may be used to endorse or promote products derived from | |
this software without specific prior written permission. | |
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | |
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | |
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | |
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | |
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment