OpenFga.Sdk 0.3.1

dotnet add package OpenFga.Sdk --version 0.3.1
NuGet\Install-Package OpenFga.Sdk -Version 0.3.1
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="OpenFga.Sdk" Version="0.3.1" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add OpenFga.Sdk --version 0.3.1
#r "nuget: OpenFga.Sdk, 0.3.1"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install OpenFga.Sdk as a Cake Addin
#addin nuget:?package=OpenFga.Sdk&version=0.3.1

// Install OpenFga.Sdk as a Cake Tool
#tool nuget:?package=OpenFga.Sdk&version=0.3.1

.NET SDK for OpenFGA

Nuget Release License FOSSA Status Discord Server Twitter

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

The documentation below refers to the OpenFga.SdkClient, to read the documentation for OpenFga.SdkApi, check out the v0.2.1 documentation.

The OpenFga.SdkClient will by default retry API requests up to 15 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", // required, e.g. https://api.fga.example
                    StoreId = Environment.GetEnvironmentVariable("FGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores`
                    AuthorizationModelId = Environment.GetEnvironmentVariable("FGA_AUTHORIZATION_MODEL_ID"), // Optional, can be overridden per request
                };
                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", // required, e.g. https://api.fga.example
                    StoreId = Environment.GetEnvironmentVariable("FGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores`
                    AuthorizationModelId = Environment.GetEnvironmentVariable("FGA_AUTHORIZATION_MODEL_ID"), // Optional, can be overridden per request
                    Credentials = new Credentials() {
                        Method = CredentialsMethod.ApiToken,
                        Config = new CredentialsConfig() {
                            ApiToken = Environment.GetEnvironmentVariable("FGA_API_TOKEN"),  // will be passed as the "Authorization: Bearer ${ApiToken}" request header
                        }
                    }
                };
                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", // required, e.g. https://api.fga.example
                    StoreId = Environment.GetEnvironmentVariable("FGA_STORE_ID"), // not needed when calling `CreateStore` or `ListStores`
                    AuthorizationModelId = Environment.GetEnvironmentVariable("FGA_AUTHORIZATION_MODEL_ID"), // Optional, can be overridden per request
                    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);

// stores = [{ "id": "01FQH7V8BEG3GPQW93KTRFR8JB", "name": "FGA Demo Store", "created_at": "2022-01-01T00:00:00.000Z", "updated_at": "2022-01-01T00:00:00.000Z" }]
Create Store

Initialize a store.

API Documentation

var store = await fgaClient.CreateStore(new ClientCreateStoreRequest(){Name = "FGA Demo"})

// store.Id = "01FQH7V8BEG3GPQW93KTRFR8JB"

// store store.Id in database

// update the storeId of the current instance
fgaClient.StoreId = storeId;

// continue calling the API normally
Get Store

Get information about the current store.

API Documentation

Requires a client initialized with a storeId

var store = await fgaClient.GetStore();

// store = { "id": "01FQH7V8BEG3GPQW93KTRFR8JB", "name": "FGA Demo Store", "created_at": "2022-01-01T00:00:00.000Z", "updated_at": "2022-01-01T00:00:00.000Z" }
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);

// response.AuthorizationModels = [
// { Id: "01GXSA8YR785C4FYS3C0RTG7B1", SchemaVersion: "1.1", TypeDefinitions: [...] },
// { Id: "01GXSBM5PVYHCJNRNKXMB4QZTW", SchemaVersion: "1.1", TypeDefinitions: [...] }];
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);

// response.AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1"
Read a Single Authorization Model

Read a particular authorization model.

API Documentation

var options = new ClientReadAuthorizationModelOptions {
    // You can rely on the model id set in the configuration or override it for this specific request
    AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1",
};

var response = await fgaClient.ReadAuthorizationModel(options);

// response.AuthorizationModel.Id = "01GXSA8YR785C4FYS3C0RTG7B1"
// response.AuthorizationModel.SchemaVersion = "1.1"
// response.AuthorizationModel.TypeDefinitions = [{ "type": "document", "relations": { ... } }, { "type": "user", "relations": { ... }}]
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();

// response.AuthorizationModel.Id = "01GXSA8YR785C4FYS3C0RTG7B1"
// response.AuthorizationModel.SchemaVersion = "1.1"
// response.AuthorizationModel.TypeDefinitions = [{ "type": "document", "relations": { ... } }, { "type": "user", "relations": { ... }}]
Relationship Tuples
Read Relationship Tuple Changes (Watch)

Reads the list of historical relationship tuple writes and deletes.

API Documentation

var body = new ClientReadChangesRequest { Type = "document" };
var options = new ClientReadChangesOptions {
    PageSize = 10,
    ContinuationToken = "...",
};

var response = await fgaClient.ReadChanges(body, options);

// response.ContinuationToken = ...
// response.Changes = [
//   { TupleKey: { User, Relation, Object }, Operation: TupleOperation.WRITE, Timestamp: ... },
//   { TupleKey: { User, Relation, Object }, Operation: TupleOperation.DELETE, Timestamp: ... }
// ]
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

// Find if a relationship tuple stating that a certain user is a viewer of a certain document
var body = new ClientReadRequest() {
    User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    Relation = "viewer",
    Object = "document:roadmap",
};

// Find all relationship tuples where a certain user has a relationship as any relation to a certain document
var body = new ClientReadRequest() {
    User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    Object = "document:roadmap",
};

// Find all relationship tuples where a certain user is a viewer of any document
var body = new ClientReadRequest() {
    User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    Relation = "viewer",
    Object = "document:",
};

// Find all relationship tuples where any user has a relationship as any relation with a particular document

var body = new ClientReadRequest() {
    Object = "document:roadmap",
};

// Read all stored relationship tuples
var body = new ClientReadRequest();

var options = new ClientReadOptions {
    PageSize = 10,
    ContinuationToken = "...",
};

var response = await fgaClient.Read(body, options);

// In all the above situations, the response will be of the form:
// response = { Tuples: [{ Key: { User, Relation, Object }, Timestamp }, ...]}
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:roadmap",
        },
        new() {
            User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
            Relation = "viewer",
            Object = "document:budget",
        }
    },
    Deletes = new List<ClientTupleKeyWithoutCondition> {
        new() {
            User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
            Relation = "writer",
            Object = "document:roadmap",
        }
    },
};
var options = new ClientWriteOptions {
    // You can rely on the model id set in the configuration or override it for this specific request
    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:roadmap",
        },
        new() {
            User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
            Relation = "viewer",
            Object = "document:budget",
        }
    },
    Deletes = new List<ClientTupleKeyWithoutCondition> {
        new() {
            User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
            Relation = "writer",
            Object = "document:roadmap",
        }
    },
};
var options = new ClientWriteOptions {
    // You can rely on the model id set in the configuration or override it for this specific request
    AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1",
    Transaction = new TransactionOptions() {
        Disable = true,
        MaxParallelRequests = 5, // Maximum number of requests to issue in parallel
        MaxPerChunk = 1, // Maximum number of requests to be sent in a transaction in a particular chunk
    }
};
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 {
    // You can rely on the model id set in the configuration or override it for this specific request
    AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1",
};
var body = new ClientCheckRequest {
    User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    Relation = "writer",
    Object = "document:roadmap"
};
var response = await fgaClient.Check(body, options);
// response.Allowed = true
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 15 times before giving up.

var options = new ClientBatchCheckOptions {
    // You can rely on the model id set in the configuration or override it for this specific request
    AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1",
    MaxParallelRequests = 5, // Max number of requests to issue in parallel, defaults to 10
};
var body = new List<ClientCheckRequest>(){
    new() {
        User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
        Relation = "viewer",
        Object = "document:roadmap",
        ContextualTuples = new List<ClientTupleKey>() {
            new() {
                User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
                Relation = "editor",
                Object = "document:roadmap",
            }
        },
    },
    new() {
        User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
        Relation = "admin",
        Object = "document:roadmap",
        ContextualTuples = new List<ClientTupleKey>() {
            new() {
                User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
                Relation = "editor",
                Object = "document:roadmap",
            }
        },
    },
    new() {
        User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
        Relation = "creator",
        Object = "document:roadmap",
    },
    new() {
        User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
        Relation = "deleter",
        Object = "document:roadmap",
    }
};

var response = await fgaClient.BatchCheck(body, options);

/*
response.Responses = [{
  Allowed: false,
  Request: {
    User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    Relation: "viewer",
    Object: "document:roadmap",
    ContextualTuples: [{
      User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
      Relation: "editor",
      Object: "document:roadmap"
    }]
  }
}, {
  Allowed: false,
  Request: {
    User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    Relation: "admin",
    Object: "document:roadmap",
    ContextualTuples: [{
      User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
      Relation: "editor",
      Object: "document:roadmap"
    }]
  }
}, {
  Allowed: false,
  Request: {
    User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    Relation: "creator",
    Object: "document:roadmap",
  },
  Error: <FgaError ...>
}, {
  Allowed: true,
  Request: {
    User: "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    Relation: "deleter",
    Object: "document:roadmap",
  }},
]
*/
Expand

Expands the relationships in userset tree format.

API Documentation

var options = new ClientCheckOptions {
    // You can rely on the model id set in the configuration or override it for this specific request
    AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1",
};
var body = new ClientExpandRequest {
    Relation = "viewer",
    Object = "document:roadmap",
};
var response = await fgaClient.Expand(body, options);

// response.Tree.Root = {"name":"document:roadmap#viewer","leaf":{"users":{"users":["user:81684243-9356-4421-8fbf-a4f8d36aa31b","user:f52a4f7a-054d-47ff-bb6e-3ac81269988f"]}}}
List Objects

List the objects of a particular type a user has access to.

API Documentation

var options = new ClientListObjectsOptions {
    // You can rely on the model id set in the configuration or override it for this specific request
    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:budget",
        },
    },
};
var response = await fgaClient.ListObjects(body, options);

// response.Objects = ["document:roadmap"]
List Relations

List the relations a user has on an object.

ListRelationsRequest body =
    new ListRelationsRequest() {
        User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
        Object = "document:roadmap",
        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:roadmap",
            }
        }
    };
var response = await fgaClient.ListRelations(body);

// response.Relations = ["can_view", "can_edit"]
Assertions
Read Assertions

Read assertions for a particular authorization model.

API Documentation

var options = new ClientReadAssertionsOptions {
    // You can rely on the model id set in the configuration or override it for this specific request
    AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1",
};
var response = await fgaClient.ReadAssertions(options);
Write Assertions

Update the assertions for a particular authorization model.

API Documentation

var options = new ClientWriteAssertionsOptions {
    // You can rely on the model id set in the configuration or override it for this specific request
    AuthorizationModelId = "01GXSA8YR785C4FYS3C0RTG7B1",
};
var body = new List<ClientAssertion>() {new ClientAssertion() {
    User = "user:81684243-9356-4421-8fbf-a4f8d36aa31b",
    Relation = "viewer",
    Object = "document:roadmap",
    Expectation = true,
}};
await fgaClient.WriteAssertions(body, options);

API Endpoints

Method HTTP request Description
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
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

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.

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net6.0

    • No dependencies.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on OpenFga.Sdk:

Package Downloads
Fga.Net.DependencyInjection

Auth0 Fine Grained Authorization for .NET. This package includes DI collection extensions for the FGA Client.

FlowtideDotNet.Connector.OpenFGA

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
0.3.1 2,053 2/13/2024
0.3.0 9,378 12/20/2023
0.2.5 745 12/1/2023
0.2.4 30,840 5/1/2023
0.2.3 1,244 4/13/2023
0.2.2 381 4/12/2023
0.2.1 3,326 1/17/2023
0.2.0 2,229 12/15/2022
0.1.2 925 11/16/2022
0.1.1 906 10/7/2022
0.1.0 1,780 9/30/2022
0.0.3 600 9/9/2022
0.0.2 741 8/16/2022
0.0.1 627 6/17/2022