func doTokenRequest()

in pkg/proxy/proxy.go [196:226]


func doTokenRequest(ctx context.Context, clientID, resource, tenantID, authorityHost string) (*token, error) {
	tokenFilePath := os.Getenv(webhook.AzureFederatedTokenFileEnvVar)
	cred := confidential.NewCredFromAssertionCallback(func(context.Context, confidential.AssertionRequestOptions) (string, error) {
		return readJWTFromFS(tokenFilePath)
	})
	authority, err := url.JoinPath(authorityHost, tenantID)
	if err != nil {
		return nil, errors.Wrap(err, "failed to construct authority URL")
	}

	confidentialClientApp, err := confidential.New(authority, clientID, cred)
	if err != nil {
		return nil, errors.Wrap(err, "failed to create confidential client app")
	}

	result, err := confidentialClientApp.AcquireTokenByCredential(ctx, []string{getScope(resource)})
	if err != nil {
		return nil, errors.Wrap(err, "failed to acquire token")
	}
	return &token{
		AccessToken: result.AccessToken,
		Resource:    resource,
		Type:        "Bearer",
		// -10s is to account for current time changes between the calls
		ExpiresIn: json.Number(strconv.FormatInt(int64(time.Until(result.ExpiresOn)/time.Second)-10, 10)),
		// There is a difference in parsing between the azure sdks and how azure-cli works
		// Using the unix time to be consistent with response from IMDS which works with
		// all the clients.
		ExpiresOn: strconv.FormatInt(result.ExpiresOn.UTC().Unix(), 10),
	}, nil
}