| 106 | } |
| 107 | |
| 108 | func (js jwtSource) Token() (*oauth2.Token, error) { |
| 109 | pk, err := jwt.ParseRSAPrivateKeyFromPEM(js.conf.PrivateKey) |
| 110 | if err != nil { |
| 111 | return nil, err |
| 112 | } |
| 113 | hc := oauth2.NewClient(js.ctx, nil) |
| 114 | audience := js.conf.TokenURL |
| 115 | if aud := js.conf.Audience; aud != "" { |
| 116 | audience = aud |
| 117 | } |
| 118 | expiration := time.Now().Add(10 * time.Minute) |
| 119 | if t := js.conf.Expires; t > 0 { |
| 120 | expiration = time.Now().Add(t) |
| 121 | } |
| 122 | scopes := strings.Join(js.conf.Scopes, " ") |
| 123 | |
| 124 | claims := jwt.MapClaims{ |
| 125 | "iss": js.conf.Iss, |
| 126 | "sub": js.conf.Subject, |
| 127 | "jti": uuid.New(), |
| 128 | "aud": audience, |
| 129 | "iat": jwt.NewNumericDate(time.Now()), |
| 130 | "exp": jwt.NewNumericDate(expiration), |
| 131 | } |
| 132 | |
| 133 | if len(scopes) > 0 { |
| 134 | claims["scope"] = scopes |
| 135 | } |
| 136 | |
| 137 | maps.Copy(claims, js.conf.PrivateClaims) |
| 138 | |
| 139 | assertion := jwt.NewWithClaims(js.conf.SigningAlgorithm, claims) |
| 140 | if js.conf.PrivateKeyID != "" { |
| 141 | assertion.Header["kid"] = js.conf.PrivateKeyID |
| 142 | } |
| 143 | payload, err := assertion.SignedString(pk) |
| 144 | if err != nil { |
| 145 | return nil, err |
| 146 | } |
| 147 | v := url.Values{} |
| 148 | v.Set("grant_type", defaultGrantType) |
| 149 | v.Set("assertion", payload) |
| 150 | if len(scopes) > 0 { |
| 151 | v.Set("scope", scopes) |
| 152 | } |
| 153 | |
| 154 | for k, p := range js.conf.EndpointParams { |
| 155 | // Allow grant_type to be overridden to allow interoperability with |
| 156 | // non-compliant implementations. |
| 157 | if _, ok := v[k]; ok && k != "grant_type" { |
| 158 | return nil, fmt.Errorf("oauth2: cannot overwrite parameter %q", k) |
| 159 | } |
| 160 | v[k] = p |
| 161 | } |
| 162 | |
| 163 | resp, err := hc.PostForm(js.conf.TokenURL, v) |
| 164 | if err != nil { |
| 165 | return nil, fmt.Errorf("oauth2: cannot fetch token: %w", err) |