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.
It allows in-memory data storage for quick development, as well as pluggable database modules - with initial support for PostgreSQL.
It offers an HTTP API and has SDKs for programming languages including Node.js/JavaScript, GoLang and .NET.
More SDKs and integrations such as Rego are planned for the future.
- 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.UserConfiguration{})
}
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
Without an API Token
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)
}
With an API Token
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: {
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)
}
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(CreateStoreRequest{Name: PtrString("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.TypeDefinitions{TypeDefinitions: &[]openfga.TypeDefinition{
{
Type: "repo",
Relations: map[string]openfga.Userset{
"writer": {This: &map[string]interface{}{}},
"reader": {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","type_definitions":[{"type":"repo","relations":{"writer":{"this":{}},"reader":{ ... }}}]}} // 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("81684243-9356-4421-8fbf-a4f8d36aa31b"),
Relation: openfga.PtrString("admin"),
Object: openfga.PtrString("workspace:675bcac4-ad38-4fb1-a19a-94a5648c91d6"),
},
}
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("81684243-9356-4421-8fbf-a4f8d36aa31b"),
Relation: openfga.PtrString("admin"),
Object: openfga.PtrString("workspace:675bcac4-ad38-4fb1-a19a-94a5648c91d6"),
},
},
},
}
_, response, err := apiClient.OpenFgaApi.Write(context.Background()).Body(body).Execute()
body := openfga.WriteRequest{
Deletes: &openfga.TupleKeys{
TupleKeys: []openfga.TupleKey{
{
User: openfga.PtrString("81684243-9356-4421-8fbf-a4f8d36aa31b"),
Relation: openfga.PtrString("admin"),
Object: openfga.PtrString("workspace:675bcac4-ad38-4fb1-a19a-94a5648c91d6"),
},
},
},
}
_, response, err := apiClient.OpenFgaApi.Write(context.Background()).Body(body).Execute()
body := openfga.ExpandRequest{
TupleKey: &openfga.TupleKey{
Relation: openfga.PtrString("admin"),
Object: openfga.PtrString("workspace:675bcac4-ad38-4fb1-a19a-94a5648c91d6"),
},
}
data, response, err := apiClient.OpenFgaApi.Expand(context.Background()).Body(body).Execute()
// data = {"tree":{"root":{"name":"workspace:675bcac4-ad38-4fb1-a19a-94a5648c91d6#admin","leaf":{"users":{"users":["anne","beth"]}}}}} // JSON
// Find if a relationship tuple stating that a certain user is an admin on a certain workspace
body := openfga.ReadRequest{
TupleKey: &openfga.TupleKey{
User: openfga.PtrString("81684243-9356-4421-8fbf-a4f8d36aa31b"),
Relation: openfga.PtrString("admin"),
Object: openfga.PtrString("workspace:675bcac4-ad38-4fb1-a19a-94a5648c91d6"),
},
}
// Find all relationship tuples where a certain user has a relationship as any relation to a certain workspace
body := openfga.ReadRequest{
TupleKey: &openfga.TupleKey{
User: openfga.PtrString("81684243-9356-4421-8fbf-a4f8d36aa31b"),
Object: openfga.PtrString("workspace:675bcac4-ad38-4fb1-a19a-94a5648c91d6"),
},
}
// Find all relationship tuples where a certain user is an admin on any workspace
body := openfga.ReadRequest{
TupleKey: &openfga.TupleKey{
User: openfga.PtrString("81684243-9356-4421-8fbf-a4f8d36aa31b"),
Relation: openfga.PtrString("admin"),
Object: openfga.PtrString("workspace:"),
},
}
// Find all relationship tuples where any user has a relationship as any relation with a particular workspace
body := openfga.ReadRequest{
TupleKey: &openfga.TupleKey{
Object: openfga.PtrString("workspace:675bcac4-ad38-4fb1-a19a-94a5648c91d6"),
},
}
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_("workspace").
PageSize(25).
ContinuationToken("eyJwayI6IkxBVEVTVF9OU0NPTkZJR19hdXRoMHN0b3JlIiwic2siOiIxem1qbXF3MWZLZExTcUoyN01MdTdqTjh0cWgifQ==").
Execute()
// response.continuation_token = ...
// response.changes = [
// { tuple_key: { user, relation, object }, operation: "write", timestamp: ... },
// { tuple_key: { user, relation, object }, operation: "delete", timestamp: ... }
// ]
Requires a client initialized with a storeId
body := openfga.ListObjectsRequest{
AuthorizationModelId: PtrString("01GAHCE4YVKPQEKZQHT2R89MQV"),
User: PtrString("anne"),
Relation: PtrString("can_read"),
Type: PtrString("document"),
ContextualTuples: &ContextualTupleKeys{
TupleKeys: []TupleKey{{
User: PtrString("anne"),
Relation: PtrString("editor"),
Object: PtrString("folder:product"),
}, {
User: PtrString("folder:product"),
Relation: PtrString("parent"),
Object: PtrString("document:roadmap"),
}},
},
}
data, response, err := apiClient.OpenFgaApi.ListObjects(context.Background()).Body(body).Execute()
// response.object_ids = ["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 | ListObjects lists all of the object ids for objects of the provided type that the given user has a specific relation with. |
OpenFgaApi | ListStores | Get /stores | Get 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
- Node
- Nodes
- NotFoundErrorCode
- ObjectRelation
- PathUnknownErrorMessageResponse
- ReadAssertionsResponse
- ReadAuthorizationModelResponse
- ReadAuthorizationModelsResponse
- ReadChangesResponse
- ReadRequest
- ReadResponse
- Status
- Store
- Tuple
- TupleChange
- TupleKey
- TupleKeys
- TupleOperation
- TupleToUserset
- TypeDefinition
- TypeDefinitions
- Users
- Userset
- UsersetTree
- UsersetTreeDifference
- UsersetTreeTupleToUserset
- Usersets
- ValidationErrorMessageResponse
- WriteAssertionsRequest
- 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.