This is an autogenerated Go SDK for OpenFGA. It provides a wrapper around the OpenFGA API definition.
- About OpenFGA
- Resources
- Installation
- Getting Started
- Contributing
- License
OpenFGA is an open source Fine-Grained Authorization solution inspired by Google's Zanzibar paper. It was created by the FGA team at Auth0 based on Auth0 Fine-Grained Authorization (FGA), available under a permissive license (Apache-2) and welcomes community contributions.
OpenFGA is designed to make it easy for application builders to model their permission layer, and to add and integrate fine-grained authorization into their applications. OpenFGA’s design is optimized for reliability and low latency at a high scale.
- OpenFGA Documentation
- OpenFGA API Documentation
- OpenFGA Discord Community
- Zanzibar Academy
- Google's Zanzibar Paper (2019)
To install:
go get -u github.com/openfga/go-sdk
In your code, import the module and use it:
import "github.com/openfga/go-sdk"
func Main() {
configuration, err := openfga.NewConfiguration(openfga.Configuration{})
}
You can then run
go mod tidy
to update go.mod
and go.sum
if you are using them.
Learn how to initialize your SDK
import (
openfga "github.com/openfga/go-sdk"
"os"
)
func main() {
configuration, err := openfga.NewConfiguration(openfga.Configuration{
ApiScheme: os.Getenv("OPENFGA_API_SCHEME"), // optional, defaults to "https"
ApiHost: os.Getenv("OPENFGA_API_HOST"), // required, define without the scheme (e.g. api.fga.example instead of https://api.fga.example)
StoreId: os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores`
})
if err != nil {
// .. Handle error
}
apiClient := openfga.NewAPIClient(configuration)
}
import (
openfga "github.com/openfga/go-sdk"
"os"
)
func main() {
configuration, err := openfga.NewConfiguration(openfga.Configuration{
ApiScheme: os.Getenv("OPENFGA_API_SCHEME"), // optional, defaults to "https"
ApiHost: os.Getenv("OPENFGA_API_HOST"), // required, define without the scheme (e.g. api.fga.example instead of https://api.fga.example)
StoreId: os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores`
Credentials: &credentials.Credentials{
Method: credentials.CredentialsMethodApiToken,
Config: &credentials.Config{
ApiToken: os.Getenv("OPENFGA_API_TOKEN"), // will be passed as the "Authorization: Bearer ${ApiToken}" request header
},
},
})
if err != nil {
// .. Handle error
}
apiClient := openfga.NewAPIClient(configuration)
}
import (
openfga "github.com/openfga/go-sdk"
"os"
)
func main() {
configuration, err := openfga.NewConfiguration(openfga.Configuration{
ApiScheme: os.Getenv("OPENFGA_API_SCHEME"), // optional, defaults to "https"
ApiHost: os.Getenv("OPENFGA_API_HOST"), // required, define without the scheme (e.g. api.fga.example instead of https://api.fga.example)
StoreId: os.Getenv("OPENFGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores`
Credentials: &credentials.Credentials{
Method: credentials.CredentialsMethodClientCredentials,
Config: &credentials.Config{
ClientCredentialsClientId: os.Getenv("OPENFGA_CLIENT_ID"),
ClientCredentialsClientSecret: os.Getenv("OPENFGA_CLIENT_SECRET"),
ClientCredentialsApiAudience: os.Getenv("OPENFGA_API_AUDIENCE"),
ClientCredentialsApiTokenIssuer: os.Getenv("OPENFGA_API_TOKEN_ISSUER"),
},
},
})
if err != nil {
// .. Handle error
}
apiClient := openfga.NewAPIClient(configuration)
}
You need your store id to call the OpenFGA API (unless it is to call the CreateStore or ListStores methods).
If your server is configured with authentication enabled, you also need to have your credentials ready.
configuration, err := openfga.NewConfiguration(openfga.Configuration{
ApiHost: "api.fga.example"
})
if err != nil {
// .. Handle error
}
apiClient := openfga.NewAPIClient(configuration)
stores, response, err := apiClient.OpenFgaApi.ListStores(context.Background()).Execute();
// stores = [{ "id": "01FQH7V8BEG3GPQW93KTRFR8JB", "name": "FGA Demo Store", "created_at": "2022-01-01T00:00:00.000Z", "updated_at": "2022-01-01T00:00:00.000Z" }]
configuration, err := openfga.NewConfiguration(openfga.Configuration{
ApiHost: "api.fga.example"
})
if err != nil {
// .. Handle error
}
apiClient := openfga.NewAPIClient(configuration)
store, _, err := apiClient.OpenFgaApi.CreateStore(context.Background()).Body(openfga.CreateStoreRequest{Name: "FGA Demo"}).Execute()
if err != nil {
// handle error
}
// store.Id = "01FQH7V8BEG3GPQW93KTRFR8JB"
// store store.Id in database
// update the storeId of the current instance
apiClient.SetStoreId(*store.Id)
// continue calling the API normally
Requires a client initialized with a storeId
store, _, err := apiClient.OpenFgaApi.GetStore(context.Background()).Execute()
if err != nil {
// handle error
}
// store = { "id": "01FQH7V8BEG3GPQW93KTRFR8JB", "name": "FGA Demo Store", "created_at": "2022-01-01T00:00:00.000Z", "updated_at": "2022-01-01T00:00:00.000Z" }
Requires a client initialized with a storeId
_, err := apiClient.OpenFgaApi.DeleteStore(context.Background()).Execute()
if err != nil {
// handle error
}
Note: To learn how to build your authorization model, check the Docs at https://openfga.dev/docs.
Learn more about the OpenFGA configuration language.
body := openfga.WriteAuthorizationModelRequest{TypeDefinitions: []openfga.TypeDefinition{
{
Type: "user",
},
{
Type: "document",
Relations: &map[string]openfga.Userset{
"writer": {This: &map[string]interface{}{}},
"viewer": {Union: &openfga.Usersets{
Child: &[]openfga.Userset{
{This: &map[string]interface{}{}},
{ComputedUserset: &openfga.ObjectRelation{
Object: openfga.PtrString(""),
Relation: openfga.PtrString("writer"),
}},
},
}},
},
},
}}
data, response, err := apiClient.OpenFgaApi.WriteAuthorizationModel(context.Background()).Body(body).Execute()
fmt.Printf("%s", data.AuthorizationModelId) // 1uHxCSuTP0VKPYSnkq1pbb1jeZw
// Assuming `1uHxCSuTP0VKPYSnkq1pbb1jeZw` is an id of a single model
data, response, err := apiClient.OpenFgaApi.ReadAuthorizationModel(context.Background(), "1uHxCSuTP0VKPYSnkq1pbb1jeZw").Execute()
// data = {"authorization_model":{"id":"1uHxCSuTP0VKPYSnkq1pbb1jeZw","schema_version":"1.1","type_definitions":[{"type":"document","relations":{"writer":{"this":{}},"viewer":{ ... }}},{"type":"user"}]}} // JSON
fmt.Printf("%s", data.AuthorizationModel.Id) // 1uHxCSuTP0VKPYSnkq1pbb1jeZw
data, response, err := apiClient.OpenFgaApi.ReadAuthorizationModels(context.Background()).Execute()
// data = {"authorization_model_ids":["1uHxCSuTP0VKPYSnkq1pbb1jeZw","GtQpMohWezFmIbyXxVEocOCxxgq"]} // in JSON
fmt.Printf("%s", (*data.AuthorizationModelIds)[0]) // 1uHxCSuTP0VKPYSnkq1pbb1jeZw
Provide a tuple and ask the OpenFGA API to check for a relationship
body := openfga.CheckRequest{
TupleKey: openfga.TupleKey{
User: openfga.PtrString("user:81684243-9356-4421-8fbf-a4f8d36aa31b"),
Relation: openfga.PtrString("viewer"),
Object: openfga.PtrString("document:roadmap"),
},
AuthorizationModelId: openfga.PtrString("1uHxCSuTP0VKPYSnkq1pbb1jeZw"),
}
data, response, err := apiClient.OpenFgaApi.Check(context.Background()).Body(body).Execute()
// data = {"allowed":true,"resolution":""} // in JSON
fmt.Printf("%t", *data.Allowed) // True
body := openfga.WriteRequest{
Writes: &openfga.TupleKeys{
TupleKeys: []openfga.TupleKey{
{
User: openfga.PtrString("user:81684243-9356-4421-8fbf-a4f8d36aa31b"),
Relation: openfga.PtrString("viewer"),
Object: openfga.PtrString("document:roadmap"),
},
},
},
AuthorizationModelId: openfga.PtrString("1uHxCSuTP0VKPYSnkq1pbb1jeZw"),
}
_, response, err := apiClient.OpenFgaApi.Write(context.Background()).Body(body).Execute()
body := openfga.WriteRequest{
Deletes: &openfga.TupleKeys{
TupleKeys: []openfga.TupleKey{
{
User: openfga.PtrString("user:81684243-9356-4421-8fbf-a4f8d36aa31b"),
Relation: openfga.PtrString("viewer"),
Object: openfga.PtrString("document:roadmap"),
},
},
},
AuthorizationModelId: openfga.PtrString("1uHxCSuTP0VKPYSnkq1pbb1jeZw"),
}
_, response, err := apiClient.OpenFgaApi.Write(context.Background()).Body(body).Execute()
body := openfga.ExpandRequest{
TupleKey: openfga.TupleKey{
Relation: openfga.PtrString("viewer"),
Object: openfga.PtrString("document:roadmap"),
},
AuthorizationModelId: openfga.PtrString("1uHxCSuTP0VKPYSnkq1pbb1jeZw"),
}
data, response, err := apiClient.OpenFgaApi.Expand(context.Background()).Body(body).Execute()
// data = {"tree":{"root":{"name":"document:roadmap#viewer","leaf":{"users":{"users":["user:81684243-9356-4421-8fbf-a4f8d36aa31b","user:f52a4f7a-054d-47ff-bb6e-3ac81269988f"]}}}}} // JSON
// Find if a relationship tuple stating that a certain user is a viewer of a certain document
body := openfga.ReadRequest{
TupleKey: &openfga.TupleKey{
User: openfga.PtrString("user:81684243-9356-4421-8fbf-a4f8d36aa31b"),
Relation: openfga.PtrString("viewer"),
Object: openfga.PtrString("document:roadmap"),
},
}
// Find all relationship tuples where a certain user has a relationship as any relation to a certain document
body := openfga.ReadRequest{
TupleKey: &openfga.TupleKey{
User: openfga.PtrString("user:81684243-9356-4421-8fbf-a4f8d36aa31b"),
Object: openfga.PtrString("document:roadmap"),
},
}
// Find all relationship tuples where a certain user is a viewer of any document
body := openfga.ReadRequest{
TupleKey: &openfga.TupleKey{
User: openfga.PtrString("user:81684243-9356-4421-8fbf-a4f8d36aa31b"),
Relation: openfga.PtrString("viewer"),
Object: openfga.PtrString("document:"),
},
}
// Find all relationship tuples where any user has a relationship as any relation with a particular document
body := openfga.ReadRequest{
TupleKey: &openfga.TupleKey{
Object: openfga.PtrString("document:roadmap"),
},
}
// Read all stored relationship tuples
body := openfga.ReadRequest{}
data, response, err := apiClient.OpenFgaApi.Read(context.Background()).Body(body).Execute()
// In all the above situations, the response will be of the form:
// data = {"tuples":[{"key":{"user":"...","relation":"...","object":"..."},"timestamp":"..."}]} // JSON
data, response, err := apiClient.OpenFgaApi.ReadChanges(context.Background()).
Type_("document").
PageSize(25).
ContinuationToken("eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==").
Execute()
// response.continuation_token = ...
// response.changes = [
// { tuple_key: { user, relation, object }, operation: "writer", timestamp: ... },
// { tuple_key: { user, relation, object }, operation: "viewer", timestamp: ... }
// ]
Requires a client initialized with a storeId
body := openfga.ListObjectsRequest{
AuthorizationModelId: openfga.PtrString("1uHxCSuTP0VKPYSnkq1pbb1jeZw"),
User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation: "viewer",
Type: "document",
ContextualTuples: &ContextualTupleKeys{
TupleKeys: []TupleKey{{
User: PtrString("user:81684243-9356-4421-8fbf-a4f8d36aa31b"),
Relation: PtrString("writer"),
Object: PtrString("document:budget"),
}},
},
}
data, response, err := apiClient.OpenFgaApi.ListObjects(context.Background()).Body(body).Execute()
// response.objects = ["document:roadmap"]
Class | Method | HTTP request | Description |
---|---|---|---|
OpenFgaApi | Check | Post /stores/{store_id}/check | Check whether a user is authorized to access an object |
OpenFgaApi | CreateStore | Post /stores | Create a store |
OpenFgaApi | DeleteStore | Delete /stores/{store_id} | Delete a store |
OpenFgaApi | Expand | Post /stores/{store_id}/expand | Expand all relationships in userset tree format, and following userset rewrite rules. Useful to reason about and debug a certain relationship |
OpenFgaApi | GetStore | Get /stores/{store_id} | Get a store |
OpenFgaApi | ListObjects | Post /stores/{store_id}/list-objects | Get all objects of the given type that the user has a relation with |
OpenFgaApi | ListStores | Get /stores | List all stores |
OpenFgaApi | Read | Post /stores/{store_id}/read | Get tuples from the store that matches a query, without following userset rewrite rules |
OpenFgaApi | ReadAssertions | Get /stores/{store_id}/assertions/{authorization_model_id} | Read assertions for an authorization model ID |
OpenFgaApi | ReadAuthorizationModel | Get /stores/{store_id}/authorization-models/{id} | Return a particular version of an authorization model |
OpenFgaApi | ReadAuthorizationModels | Get /stores/{store_id}/authorization-models | Return all the authorization models for a particular store |
OpenFgaApi | ReadChanges | Get /stores/{store_id}/changes | Return a list of all the tuple changes |
OpenFgaApi | Write | Post /stores/{store_id}/write | Add or delete tuples from the store |
OpenFgaApi | WriteAssertions | Put /stores/{store_id}/assertions/{authorization_model_id} | Upsert assertions for an authorization model ID |
OpenFgaApi | WriteAuthorizationModel | Post /stores/{store_id}/authorization-models | Create a new authorization model |
- Any
- Assertion
- AuthorizationModel
- CheckRequest
- CheckResponse
- Computed
- ContextualTupleKeys
- CreateStoreRequest
- CreateStoreResponse
- Difference
- ErrorCode
- ExpandRequest
- ExpandResponse
- GetStoreResponse
- InternalErrorCode
- InternalErrorMessageResponse
- Leaf
- ListObjectsRequest
- ListObjectsResponse
- ListStoresResponse
- Metadata
- Node
- Nodes
- NotFoundErrorCode
- ObjectRelation
- PathUnknownErrorMessageResponse
- ReadAssertionsResponse
- ReadAuthorizationModelResponse
- ReadAuthorizationModelsResponse
- ReadChangesResponse
- ReadRequest
- ReadResponse
- RelationMetadata
- RelationReference
- Status
- Store
- Tuple
- TupleChange
- TupleKey
- TupleKeys
- TupleOperation
- TupleToUserset
- TypeDefinition
- Users
- Userset
- UsersetTree
- UsersetTreeDifference
- UsersetTreeTupleToUserset
- Usersets
- ValidationErrorMessageResponse
- WriteAssertionsRequest
- WriteAuthorizationModelRequest
- WriteAuthorizationModelResponse
- WriteRequest
If you have found a bug or if you have a feature request, please report them on the sdk-generator repo issues section. Please do not report security vulnerabilities on the public GitHub issue tracker.
All changes made to this repo will be overwritten on the next generation, so we kindly ask that you send all pull requests related to the SDKs to the sdk-generator repo instead.
This project is licensed under the Apache-2.0 license. See the LICENSE file for more info.
The code in this repo was auto generated by OpenAPI Generator from a template based on the go template, licensed under the Apache License 2.0.
This repo bundles some code from the golang.org/x/oauth2 package. You can find the code here and corresponding BSD-3 License.