.NET SDK for OpenFGA

This is an autogenerated SDK for OpenFGA. It provides a wrapper around the OpenFGA API definition.
Table of Contents
About
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.
Resources
Installation
The OpenFGA .NET SDK is available on NuGet.
You can install it using:
dotnet add package OpenFga.Sdk
Install-Package OpenFga.Sdk
Search for and install OpenFga.Sdk
in each of their respective package manager UIs.
Getting Started
Initializing the API Client
Learn how to initialize your SDK
We strongly recommend you initialize the OpenFgaClient
only once and then re-use it throughout your app, otherwise you will incur the cost of having to re-initialize multiple times or at every request, the cost of reduced connection pooling and re-use, and would be particularly costly in the client credentials flow, as that flow will be preformed on every request.
The OpenFga.SdkClient
will by default retry API requests up to 3 times on 429 and 5xx errors.
No Credentials
using OpenFga.Sdk.Client;
using OpenFga.Sdk.Client.Model;
using OpenFga.Sdk.Model;
namespace Example {
public class Example {
public static async Task Main() {
try {
var configuration = new ClientConfiguration() {
ApiUrl = Environment.GetEnvironmentVariable("FGA_API_URL") ?? "http://localhost:8080",
StoreId = Environment.GetEnvironmentVariable("FGA_STORE_ID"),
AuthorizationModelId = Environment.GetEnvironmentVariable("FGA_MODEL_ID"),
};
var fgaClient = new OpenFgaClient(configuration);
var response = await fgaClient.ReadAuthorizationModels();
} catch (ApiException e) {
Debug.Print("Error: "+ e);
}
}
}
}
API Token
using OpenFga.Sdk.Client;
using OpenFga.Sdk.Client.Model;
using OpenFga.Sdk.Model;
namespace Example {
public class Example {
public static async Task Main() {
try {
var configuration = new ClientConfiguration() {
ApiUrl = Environment.GetEnvironmentVariable("FGA_API_URL") ?? "http://localhost:8080",
StoreId = Environment.GetEnvironmentVariable("FGA_STORE_ID"),
AuthorizationModelId = Environment.GetEnvironmentVariable("FGA_MODEL_ID"),
Credentials = new Credentials() {
Method = CredentialsMethod.ApiToken,
Config = new CredentialsConfig() {
ApiToken = Environment.GetEnvironmentVariable("FGA_API_TOKEN"),
}
}
};
var fgaClient = new OpenFgaClient(configuration);
var response = await fgaClient.ReadAuthorizationModels();
} catch (ApiException e) {
Debug.Print("Error: "+ e);
}
}
}
}
Client Credentials
using OpenFga.Sdk.Client;
using OpenFga.Sdk.Client.Model;
using OpenFga.Sdk.Model;
namespace Example {
public class Example {
public static async Task Main() {
try {
var configuration = new ClientConfiguration() {
ApiUrl = Environment.GetEnvironmentVariable("FGA_API_URL") ?? "http://localhost:8080",
StoreId = Environment.GetEnvironmentVariable("FGA_STORE_ID"),
AuthorizationModelId = Environment.GetEnvironmentVariable("FGA_MODEL_ID"),
Credentials = new Credentials() {
Method = CredentialsMethod.ClientCredentials,
Config = new CredentialsConfig() {
ApiTokenIssuer = Environment.GetEnvironmentVariable("FGA_API_TOKEN_ISSUER"),
ApiAudience = Environment.GetEnvironmentVariable("FGA_API_AUDIENCE"),
ClientId = Environment.GetEnvironmentVariable("FGA_CLIENT_ID"),
ClientSecret = Environment.GetEnvironmentVariable("FGA_CLIENT_SECRET"),
}
}
};
var fgaClient = new OpenFgaClient(configuration);
var response = await fgaClient.ReadAuthorizationModels();
} catch (ApiException e) {
Debug.Print("Error: "+ e);
}
}
}
}
Get your Store ID
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.
Calling the API
Stores
List Stores
Get a paginated list of stores.
API Documentation
var options = new ClientListStoresOptions {
PageSize = 10,
ContinuationToken = "...",
};
var response = await fgaClient.ListStores(options);
Create Store
Initialize a store.
API Documentation
var store = await fgaClient.CreateStore(new ClientCreateStoreRequest(){Name = "FGA Demo"})
fgaClient.StoreId = storeId;
Get Store
Get information about the current store.
API Documentation
Requires a client initialized with a storeId
var store = await fgaClient.GetStore();
Delete Store
Delete a store.
API Documentation
Requires a client initialized with a storeId
var store = await fgaClient.DeleteStore();
Authorization Models
Read Authorization Models
Read all authorization models in the store.
API Documentation
var options = new ClientReadAuthorizationModelsOptions {
PageSize = 10,
ContinuationToken = "...",
};
var response = await fgaClient.ReadAuthorizationModels(options);
Write Authorization Model
Create a new authorization model.
API Documentation
Note: To learn how to build your authorization model, check the Docs at https://openfga.dev/docs.
Learn more about the OpenFGA configuration language.
You can use the OpenFGA Syntax Transformer to convert between the friendly DSL and the JSON authorization model.
var body = new ClientWriteAuthorizationModelRequest {
SchemaVersion = "1.1",
TypeDefinitions = new List<TypeDefinition> {
new() {Type = "user", Relations = new Dictionary<string, Userset>()},
new() {Type = "document",
Relations = new Dictionary<string, Userset> {
{"writer", new Userset {This = new object()}}, {
"viewer", new Userset {
Union = new Usersets {
Child = new List<Userset> {
new() {This = new object()},
new() {ComputedUserset = new ObjectRelation {Relation = "writer"}}
}
}
}
}
},
Metadata = new Metadata {
Relations = new Dictionary<string, RelationMetadata> {
{"writer", new RelationMetadata {
DirectlyRelatedUserTypes = new List<RelationReference> {
new() {Type = "user"}
}
}}, {"viewer", new RelationMetadata {
DirectlyRelatedUserTypes = new List<RelationReference> {
new() {Type = "user"}
}
}}
}
}
}
}
};
var response = await fgaClient.WriteAuthorizationModel(body);
Read a Single Authorization Model
Read a particular authorization model.
API Documentation
var options = new ClientReadAuthorizationModelOptions {
AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1",
};
var response = await fgaClient.ReadAuthorizationModel(options);
Read the Latest Authorization Model
Reads the latest authorization model (note: this ignores the model id in configuration).
API Documentation
var response = await fgaClient.ReadLatestAuthorizationModel();
Relationship Tuples
Read Relationship Tuple Changes (Watch)
Reads the list of historical relationship tuple writes and deletes.
API Documentation
var startTime = DateTime.Parse("2022-01-01T00:00:00Z");
var body = new ClientReadChangesRequest { Type = "document", StartTime = startTime };
var options = new ClientReadChangesOptions {
PageSize = 10,
ContinuationToken = "...",
};
var response = await fgaClient.ReadChanges(body, options);
Read Relationship Tuples
Reads the relationship tuples stored in the database. It does not evaluate nor exclude invalid tuples according to the authorization model.
API Documentation
var body = new ClientReadRequest() {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "viewer",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
};
var body = new ClientReadRequest() {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
};
var body = new ClientReadRequest() {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "viewer",
Object = "document:",
};
var body = new ClientReadRequest() {
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
};
var body = new ClientReadRequest();
var options = new ClientReadOptions {
PageSize = 10,
ContinuationToken = "...",
};
var response = await fgaClient.Read(body, options);
Write (Create and Delete) Relationship Tuples
Create and/or delete relationship tuples to update the system state.
API Documentation
Transaction mode (default)
By default, write runs in a transaction mode where any invalid operation (deleting a non-existing tuple, creating an existing tuple, one of the tuples was invalid) or a server error will fail the entire operation.
var body = new ClientWriteRequest() {
Writes = new List<ClientTupleKey> {
new() {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "viewer",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
},
new() {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "viewer",
Object = "document:0192ab2d-d36e-7cb3-a4a8-5d1d67a300c5",
}
},
Deletes = new List<ClientTupleKeyWithoutCondition> {
new() {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "writer",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
}
},
};
var options = new ClientWriteOptions {
AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1",
};
var response = await fgaClient.Write(body, options);
Convenience WriteTuples
and DeleteTuples
methods are also available.
Non-transaction mode
The SDK will split the writes into separate requests and send them sequentially to avoid violating rate limits.
var body = new ClientWriteRequest() {
Writes = new List<ClientTupleKey> {
new() {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "viewer",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
},
new() {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "viewer",
Object = "document:0192ab2d-d36e-7cb3-a4a8-5d1d67a300c5",
}
},
Deletes = new List<ClientTupleKeyWithoutCondition> {
new() {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "writer",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
}
},
};
var options = new ClientWriteOptions {
AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1",
Transaction = new TransactionOptions() {
Disable = true,
MaxParallelRequests = 5,
MaxPerChunk = 1,
}
};
var response = await fgaClient.Write(body, options);
Relationship Queries
Check
Check if a user has a particular relation with an object.
API Documentation
var options = new ClientCheckOptions {
AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1",
};
var body = new ClientCheckRequest {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "writer",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a"
};
var response = await fgaClient.Check(body, options);
Batch Check
Run a set of checks. Batch Check will return allowed: false
if it encounters an error, and will return the error in the body.
If 429s or 5xxs are encountered, the underlying check will retry up to 3 times before giving up.
var options = new ClientBatchCheckOptions {
AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1",
MaxParallelRequests = 5,
};
var body = new List<ClientCheckRequest>(){
new() {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "viewer",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
ContextualTuples = new List<ClientTupleKey>() {
new() {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "editor",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
}
},
},
new() {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "admin",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
ContextualTuples = new List<ClientTupleKey>() {
new() {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "editor",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
}
},
},
new() {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "creator",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
},
new() {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "deleter",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
}
};
var response = await fgaClient.BatchCheck(body, options);
Expand
Expands the relationships in userset tree format.
API Documentation
var options = new ClientCheckOptions {
AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1",
};
var body = new ClientExpandRequest {
Relation = "viewer",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
};
var response = await fgaClient.Expand(body, options);
List Objects
List the objects of a particular type a user has access to.
API Documentation
var options = new ClientListObjectsOptions {
AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1",
};
var body = new ClientListObjectsRequest {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "viewer",
Type = "document",
ContextualTuples = new List<ClientTupleKey> {
new() {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "writer",
Object = "document:0192ab2d-d36e-7cb3-a4a8-5d1d67a300c5",
},
},
};
var response = await fgaClient.ListObjects(body, options);
List Relations
List the relations a user has on an object.
ListRelationsRequest body =
new ListRelationsRequest() {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
Relations = new List<string> {"can_view", "can_edit", "can_delete", "can_rename"},
ContextualTuples = new List<ClientTupleKey>() {
new ClientTupleKey {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "editor",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
}
}
};
var response = await fgaClient.ListRelations(body);
List Users
List the users who have a certain relation to a particular type.
API Documentation
const options = {};
options.authorization_model_id = "1uHxCSuTP0VKPYSnkq1pbb1jeZw";
const userFilters = [{type: "user"}];
const response = await fgaClient.listUsers({
object: {
type: "document",
id: "roadmap"
},
relation: "can_read",
user_filters: userFilters,
context: {
"view_count": 100
},
contextualTuples:
[{
user: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
relation: "editor",
object: "folder:product"
}, {
user: "folder:product",
relation: "parent",
object: "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a"
}]
}, options);
Assertions
Read Assertions
Read assertions for a particular authorization model.
API Documentation
var options = new ClientReadAssertionsOptions {
AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1",
};
var response = await fgaClient.ReadAssertions(options);
Write Assertions
Update the assertions for a particular authorization model.
API Documentation
var options = new ClientWriteAssertionsOptions {
AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1",
};
var body = new List<ClientAssertion>() {new ClientAssertion() {
User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
Relation = "viewer",
Object = "document:0192ab2a-d83f-756d-9397-c5ed9f3cb69a",
Expectation = true,
}};
await fgaClient.WriteAssertions(body, options);
Retries
If a network request fails with a 429 or 5xx error from the server, the SDK will automatically retry the request up to 3 times with a minimum wait time of 100 milliseconds between each attempt.
To customize this behavior, create a RetryParams
instance and assign values to the MaxRetry
and MinWaitInMs
constructor parameters. MaxRetry
determines the maximum number of retries (up to 15), while MinWaitInMs
sets the minimum wait time between retries in milliseconds.
Apply your custom retry values by passing the object to the ClientConfiguration
constructor's RetryParams
parameter.
using OpenFga.Sdk.Client;
using OpenFga.Sdk.Client.Model;
using OpenFga.Sdk.Model;
namespace Example {
public class Example {
public static async Task Main() {
try {
var configuration = new ClientConfiguration() {
ApiUrl = Environment.GetEnvironmentVariable("FGA_API_URL") ?? "http://localhost:8080",
StoreId = Environment.GetEnvironmentVariable("FGA_STORE_ID"),
AuthorizationModelId = Environment.GetEnvironmentVariable("FGA_MODEL_ID"),
RetryParams = new RetryParams() {
MaxRetry = 3,
MinWaitInMs = 250
}
};
var fgaClient = new OpenFgaClient(configuration);
var response = await fgaClient.ReadAuthorizationModels();
} catch (ApiException e) {
Debug.Print("Error: "+ e);
}
}
}
}
API Endpoints
BatchCheck | POST /stores/{store_id}/batch-check | Send a list of `check` operations in a single request |
Check | POST /stores/{store_id}/check | Check whether a user is authorized to access an object |
CreateStore | POST /stores | Create a store |
DeleteStore | DELETE /stores/{store_id} | Delete a store |
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 |
GetStore | GET /stores/{store_id} | Get a store |
ListObjects | POST /stores/{store_id}/list-objects | List all objects of the given type that the user has a relation with |
ListStores | GET /stores | List all stores |
ListUsers | POST /stores/{store_id}/list-users | List the users matching the provided filter who have a certain relation to a particular type. |
Read | POST /stores/{store_id}/read | Get tuples from the store that matches a query, without following userset rewrite rules |
ReadAssertions | GET /stores/{store_id}/assertions/{authorization_model_id} | Read assertions for an authorization model ID |
ReadAuthorizationModel | GET /stores/{store_id}/authorization-models/{id} | Return a particular version of an authorization model |
ReadAuthorizationModels | GET /stores/{store_id}/authorization-models | Return all the authorization models for a particular store |
ReadChanges | GET /stores/{store_id}/changes | Return a list of all the tuple changes |
Write | POST /stores/{store_id}/write | Add or delete tuples from the store |
WriteAssertions | PUT /stores/{store_id}/assertions/{authorization_model_id} | Upsert assertions for an authorization model ID |
WriteAuthorizationModel | POST /stores/{store_id}/authorization-models | Create a new authorization model |
Models
OpenTelemetry
This SDK supports producing metrics that can be consumed as part of an OpenTelemetry setup. For more information, please see the documentation
Contributing
Issues
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.
Pull Requests
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.
Author
OpenFGA
License
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 csharp-netcore template, licensed under the Apache License 2.0.