Skip to content

Commit 4960a69

Browse files
weltekialexellis
authored andcommitted
Add usage examples to README
Signed-off-by: Han Verstraete (OpenFaaS Ltd) <[email protected]>
1 parent 02a8d16 commit 4960a69

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

README.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,66 @@ For use within functions:
1111
* ReadSecret() - Read a named secret from within an OpenFaaS Function
1212
* ReadSecrets() - Read all available secrets returning a queryable map
1313

14+
## Usage
15+
16+
```go
17+
import "github.com/openfaas/go-sdk"
18+
```
19+
20+
Construct a new OpenFaaS client and use it to access the OpenFaaS gateway API.
21+
22+
```go
23+
gatewayURL, _ := url.Parse("http://127.0.0.1:8080")
24+
auth := &sdk.BasicAuth{
25+
Username: username,
26+
Password: password,
27+
}
28+
29+
client := sdk.NewClient(gatewayURL, auth, http.DefaultClient)
30+
31+
namespace, err := client.GetNamespaces()
32+
```
33+
34+
### Authentication with IAM
35+
36+
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.
37+
38+
To get a token that can be exchanged for an OpenFaaS token you need to implement the `TokenSource` interface.
39+
40+
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).
41+
42+
```go
43+
type ServiceAccountTokenSource struct{}
44+
45+
func (ts *ServiceAccountTokenSource) Token() (string, error) {
46+
tokenMountPath := getEnv("token_mount_path", "/var/secrets/tokens")
47+
if len(tokenMountPath) == 0 {
48+
return "", fmt.Errorf("invalid token_mount_path specified for reading the service account token")
49+
}
50+
51+
idTokenPath := path.Join(tokenMountPath, "openfaas-token")
52+
idToken, err := os.ReadFile(idTokenPath)
53+
if err != nil {
54+
return "", fmt.Errorf("unable to load service account token: %s", err)
55+
}
56+
57+
return string(idToken), nil
58+
}
59+
```
60+
61+
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.
62+
63+
If the OpenFaaS token is expired the `TokenSource` is asked for a token and the token exchange will run again.
64+
65+
```go
66+
gatewayURL, _ := url.Parse("https://gw.openfaas.example.com")
67+
68+
auth := &sdk.TokenAuth{
69+
TokenURL "https://gw.openfaas.example.com/oauth/token",
70+
TokenSource: &ServiceAccountTokenSource{}
71+
}
72+
73+
client := sdk.NewClient(gatewayURL, auth, http.DefaultClient)
74+
```
75+
1476
License: MIT

0 commit comments

Comments
 (0)