Source File
jwt.go
Belonging Package
golang.org/x/oauth2/jwt
package jwt
import (
)
var (
defaultGrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer"
defaultHeader = &jws.Header{Algorithm: "RS256", Typ: "JWT"}
)
PrivateClaims map[string]interface{}
func ( *Config) ( context.Context) oauth2.TokenSource {
return oauth2.ReuseTokenSource(nil, jwtSource{, })
}
type jwtSource struct {
ctx context.Context
conf *Config
}
func ( jwtSource) () (*oauth2.Token, error) {
, := internal.ParseKey(.conf.PrivateKey)
if != nil {
return nil,
}
:= oauth2.NewClient(.ctx, nil)
:= &jws.ClaimSet{
Iss: .conf.Email,
Scope: strings.Join(.conf.Scopes, " "),
Aud: .conf.TokenURL,
PrivateClaims: .conf.PrivateClaims,
}
if := .conf.Subject; != "" {
.Prn =
}
if := .conf.Expires; > 0 {
.Exp = time.Now().Add().Unix()
}
if := .conf.Audience; != "" {
.Aud =
}
:= *defaultHeader
.KeyID = .conf.PrivateKeyID
, := jws.Encode(&, , )
if != nil {
return nil,
}
:= url.Values{}
.Set("grant_type", defaultGrantType)
.Set("assertion", )
, := .PostForm(.conf.TokenURL, )
if != nil {
return nil, fmt.Errorf("oauth2: cannot fetch token: %v", )
}
defer .Body.Close()
, := ioutil.ReadAll(io.LimitReader(.Body, 1<<20))
if != nil {
return nil, fmt.Errorf("oauth2: cannot fetch token: %v", )
}
if := .StatusCode; < 200 || > 299 {
return nil, &oauth2.RetrieveError{
Response: ,
Body: ,
}
var struct {
string `json:"access_token"`
string `json:"token_type"`
string `json:"id_token"`
int64 `json:"expires_in"` // relative seconds from now
}
if := json.Unmarshal(, &); != nil {
return nil, fmt.Errorf("oauth2: cannot fetch token: %v", )
}
:= &oauth2.Token{
AccessToken: .,
TokenType: .,
}
:= make(map[string]interface{})
json.Unmarshal(, &) // no error checks for optional fields
= .WithExtra()
if := .; > 0 {
.Expiry = time.Now().Add(time.Duration() * time.Second)
}
![]() |
The pages are generated with Golds v0.3.2-preview. (GOOS=darwin GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds. |