Skip to content

Commit

Permalink
Add usage examples to README
Browse files Browse the repository at this point in the history
Signed-off-by: Han Verstraete (OpenFaaS Ltd) <[email protected]>
  • Loading branch information
welteki authored and alexellis committed Jun 30, 2023
1 parent 02a8d16 commit 4960a69
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,66 @@ For use within functions:
* ReadSecret() - Read a named secret from within an OpenFaaS Function
* ReadSecrets() - Read all available secrets returning a queryable map

## Usage

```go
import "github.com/openfaas/go-sdk"
```

Construct a new OpenFaaS client and use it to access the OpenFaaS gateway API.

```go
gatewayURL, _ := url.Parse("http://127.0.0.1:8080")
auth := &sdk.BasicAuth{
Username: username,
Password: password,
}

client := sdk.NewClient(gatewayURL, auth, http.DefaultClient)

namespace, err := client.GetNamespaces()
```

### Authentication with IAM

To authenticate with an OpenFaaS deployment that has [Identity and Access Management (IAM)](https://docs.openfaas.com/openfaas-pro/iam/overview/) enabled, the client needs to exchange an ID token for an OpenFaaS ID token.

To get a token that can be exchanged for an OpenFaaS token you need to implement the `TokenSource` interface.

This is an example of a token source that gets a service account token mounted into a pod with [ServiceAccount token volume projection](https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/#serviceaccount-token-volume-projection).

```go
type ServiceAccountTokenSource struct{}

func (ts *ServiceAccountTokenSource) Token() (string, error) {
tokenMountPath := getEnv("token_mount_path", "/var/secrets/tokens")
if len(tokenMountPath) == 0 {
return "", fmt.Errorf("invalid token_mount_path specified for reading the service account token")
}

idTokenPath := path.Join(tokenMountPath, "openfaas-token")
idToken, err := os.ReadFile(idTokenPath)
if err != nil {
return "", fmt.Errorf("unable to load service account token: %s", err)
}

return string(idToken), nil
}
```

The service account token returned by the `TokenSource` is automatically exchanged for an OpenFaaS token that is then used in the Authorization header for all requests made to the API.

If the OpenFaaS token is expired the `TokenSource` is asked for a token and the token exchange will run again.

```go
gatewayURL, _ := url.Parse("https://gw.openfaas.example.com")

auth := &sdk.TokenAuth{
TokenURL "https://gw.openfaas.example.com/oauth/token",
TokenSource: &ServiceAccountTokenSource{}
}

client := sdk.NewClient(gatewayURL, auth, http.DefaultClient)
```

License: MIT

0 comments on commit 4960a69

Please sign in to comment.