Skip to content

Latest commit

 

History

History
1091 lines (784 loc) · 44.1 KB

README.md

File metadata and controls

1091 lines (784 loc) · 44.1 KB

Java SDK for OpenFGA

Maven Central Javadoc Release License FOSSA Status Join our community Twitter

This is an autogenerated Java 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 Java SDK is available on Maven Central.

The OpenFGA Java SDK currently supports Java11 as the minimum JDK version.

It can be used with the following:

  • Gradle (Groovy)
implementation 'dev.openfga:openfga-sdk:0.7.1'
  • Gradle (Kotlin)
implementation("dev.openfga:openfga-sdk:0.7.1")
  • Apache Maven
<dependency>
    <groupId>dev.openfga</groupId>
    <artifactId>openfga-sdk</artifactId>
    <version>0.7.1</version>
</dependency>
  • Ivy
<dependency org="dev.openfga" name="openfga-sdk" rev="0.7.1"/>
  • SBT
libraryDependencies += "dev.openfga" % "openfga-sdk" % "0.7.1"
  • Leiningen
[dev.openfga/openfga-sdk "0.7.1"]

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 Client will by default retry API requests up to 15 times on 429 and 5xx errors.

No Credentials

import com.fasterxml.jackson.databind.ObjectMapper;
import dev.openfga.sdk.api.client.OpenFgaClient;
import dev.openfga.sdk.api.configuration.ClientConfiguration;
import java.net.http.HttpClient;

public class Example {
    public static void main(String[] args) throws Exception {
        var config = new ClientConfiguration()
                .apiUrl(System.getenv("FGA_API_URL")) // If not specified, will default to "http://localhost:8080"
                .storeId(System.getenv("FGA_STORE_ID")) // Not required when calling createStore() or listStores()
                .authorizationModelId(System.getenv("FGA_MODEL_ID")); // Optional, can be overridden per request

        var fgaClient = new OpenFgaClient(config);
        var response = fgaClient.readAuthorizationModels().get();
    }
}

API Token

import com.fasterxml.jackson.databind.ObjectMapper;
import dev.openfga.sdk.api.client.OpenFgaClient;
import dev.openfga.sdk.api.configuration.ApiToken;
import dev.openfga.sdk.api.configuration.ClientConfiguration;
import dev.openfga.sdk.api.configuration.Credentials;
import java.net.http.HttpClient;

public class Example {
    public static void main(String[] args) throws Exception {
        var config = new ClientConfiguration()
                .apiUrl(System.getenv("FGA_API_URL")) // If not specified, will default to "http://localhost:8080"
                .storeId(System.getenv("FGA_STORE_ID")) // Not required when calling createStore() or listStores()
                .authorizationModelId(System.getenv("FGA_MODEL_ID")) // Optional, can be overridden per request
                .credentials(new Credentials(
                    new ApiToken(System.getenv("FGA_API_TOKEN")) // will be passed as the "Authorization: Bearer ${ApiToken}" request header
                ));

        var fgaClient = new OpenFgaClient(config);
        var response = fgaClient.readAuthorizationModels().get();
    }
}

Auth0 Client Credentials

import com.fasterxml.jackson.databind.ObjectMapper;
import dev.openfga.sdk.api.client.OpenFgaClient;
import dev.openfga.sdk.api.configuration.ClientConfiguration;
import dev.openfga.sdk.api.configuration.ClientCredentials;
import dev.openfga.sdk.api.configuration.Credentials;
import java.net.http.HttpClient;

public class Example {
    public static void main(String[] args) throws Exception {
        var config = new ClientConfiguration()
                .apiUrl(System.getenv("FGA_API_URL")) // If not specified, will default to "http://localhost:8080"
                .storeId(System.getenv("FGA_STORE_ID")) // Not required when calling createStore() or listStores()
                .authorizationModelId(System.getenv("FGA_MODEL_ID")) // Optional, can be overridden per request
                .credentials(new Credentials(
                    new ClientCredentials()
                            .apiTokenIssuer(System.getenv("FGA_API_TOKEN_ISSUER"))
                            .apiAudience(System.getenv("FGA_API_AUDIENCE"))
                            .clientId(System.getenv("FGA_CLIENT_ID"))
                            .clientSecret(System.getenv("FGA_CLIENT_SECRET"))
                ));

        var fgaClient = new OpenFgaClient(config);
        var response = fgaClient.readAuthorizationModels().get();
    }
}

Oauth2 Credentials

import com.fasterxml.jackson.databind.ObjectMapper;
import dev.openfga.sdk.api.client.OpenFgaClient;
import dev.openfga.sdk.api.configuration.ClientConfiguration;
import dev.openfga.sdk.api.configuration.ClientCredentials;
import dev.openfga.sdk.api.configuration.Credentials;
import java.net.http.HttpClient;

public class Example {
    public static void main(String[] args) throws Exception {
        var config = new ClientConfiguration()
                .apiUrl(System.getenv("FGA_API_URL")) // If not specified, will default to "http://localhost:8080"
                .storeId(System.getenv("FGA_STORE_ID")) // Not required when calling createStore() or listStores()
                .authorizationModelId(System.getenv("FGA_MODEL_ID")) // Optional, can be overridden per request
                .credentials(new Credentials(
                    new ClientCredentials()
                            .apiTokenIssuer(System.getenv("FGA_API_TOKEN_ISSUER"))
                            .scopes(System.getenv("FGA_API_SCOPES")) // optional space separated scopes
                            .clientId(System.getenv("FGA_CLIENT_ID"))
                            .clientSecret(System.getenv("FGA_CLIENT_SECRET"))
                ));

        var fgaClient = new OpenFgaClient(config);
        var response = fgaClient.readAuthorizationModels().get();
    }
}

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

Passing ClientListStoresOptions is optional. All fields of ClientListStoresOptions are optional.

var options = new ClientListStoresOptions()
    .additionalHeaders(Map.of("Some-Http-Header", "Some value"))
    .pageSize(10)
    .continuationToken("...");
var stores = 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

Passing ClientCreateStoreOptions is optional. All fields of ClientCreateStoreOptions are optional.

var request = new CreateStoreRequest().name("FGA Demo");
var options = new ClientCreateStoreOptions().additionalHeaders(Map.of("Some-Http-Header", "Some value"));
var store = fgaClient.createStore(request, options).get();

// store.getId() = "01FQH7V8BEG3GPQW93KTRFR8JB"

// store the store.getId() in database

// update the storeId of the client instance
fgaClient.setStoreId(store.getId());

// continue calling the API normally
Get Store

Get information about the current store.

API Documentation

Requires a client initialized with a storeId

Passing ClientGetStoreOptions is optional. All fields of ClientGetStoreOptions are optional.

var options = new ClientGetStoreOptions().additionalHeaders(Map.of("Some-Http-Header", "Some value"));
var store = fgaClient.getStore(options).get();

// 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

Passing ClientDeleteStoreOptions is optional. All fields of ClientDeleteStoreOptions are optional.

var options = new ClientDeleteStoreOptions().additionalHeaders(Map.of("Some-Http-Header", "Some value"));
var store = fgaClient.deleteStore(options).get();

Authorization Models

Read Authorization Models

Read all authorization models in the store.

API Documentation

Passing ClientReadAuthorizationModelsOptions is optional. All fields of ClientReadAuthorizationModelsOptions are optional.

var options = new ClientReadAuthorizationModelsOptions()
    .additionalHeaders(Map.of("Some-Http-Header", "Some value"))
    .pageSize(10)
    .continuationToken("...");
var response = fgaClient.readAuthorizationModels(options).get();

// response.getAuthorizationModels() = [
// { 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 CLI or Syntax Transformer to convert between the OpenFGA DSL and the JSON authorization model.

Passing ClientWriteAuthorizationModelOptions is optional. All fields of ClientWriteAuthorizationModelOptions are optional.

var request = new WriteAuthorizationModelRequest()
    .schemaVersion("1.1")
    .typeDefinitions(List.of(
        new TypeDefinition().type("user").relations(Map.of()),
        new TypeDefinition()
            .type("document")
            .relations(Map.of(
                "writer", new Userset(),
                "viewer", new Userset().union(new Usersets()
                    .child(List.of(
                        new Userset(),
                        new Userset().computedUserset(new ObjectRelation().relation("writer"))
                    ))
                )
            ))
            .metadata(new Metadata()
                .relations(Map.of(
                    "writer", new RelationMetadata().directlyRelatedUserTypes(
                        List.of(new RelationReference().type("user"))
                    ),
                    "viewer", new RelationMetadata().directlyRelatedUserTypes(
                        List.of(new RelationReference().type("user"))
                    )
                ))
            )
    ));
var options = new ClientWriteAuthorizationModelOptions().additionalHeaders(Map.of("Some-Http-Header", "Some value"));

var response = fgaClient.writeAuthorizationModel(request, options).get();

// response.getAuthorizationModelId() = "01GXSA8YR785C4FYS3C0RTG7B1"

Read a Single Authorization Model

Read a particular authorization model.

API Documentation

Passing ClientReadAuthorizationModelOptions is optional. All fields of ClientReadAuthorizationModelOptions are optional.

var options = new ClientReadAuthorizationModelOptions()
    .additionalHeaders(Map.of("Some-Http-Header", "Some value"))
    // You can rely on the model id set in the configuration or override it for this specific request
    .authorizationModelId("01GXSA8YR785C4FYS3C0RTG7B1");

var response = fgaClient.readAuthorizationModel(options).get();

// response.getAuthorizationModel().getId() = "01GXSA8YR785C4FYS3C0RTG7B1"
// response.getAuthorizationModel().getSchemaVersion() = "1.1"
// response.getAuthorizationModel().getTypeDefinitions() = [{ "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

Passing ClientReadLatestAuthorizationModelOptions is optional. All fields of ClientReadLatestAuthorizationModelOptions are optional.

var options = new ClientReadLatestAuthorizationModelOptions().additionalHeaders(Map.of("Some-Http-Header", "Some value"));
var response = fgaClient.readLatestAuthorizationModel(options).get();

// response.getAuthorizationModel().getId() = "01GXSA8YR785C4FYS3C0RTG7B1"
// response.getAuthorizationModel().SchemaVersion() = "1.1"
// response.getAuthorizationModel().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

Passing ClientReadChangesOptions is optional. All fields of ClientReadChangesOptions are optional.

var request = new ClientReadChangesRequest().type("document");
var options = new ClientReadChangesOptions()
    .additionalHeaders(Map.of("Some-Http-Header", "Some value"))
    .pageSize(10)
    .continuationToken("...");

var response = fgaClient.readChanges(request, options).get();

// response.getContinuationToken() = ...
// response.getChanges() = [
//   { 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

Passing ClientReadOptions is optional. All fields of ClientReadOptions are optional.

// Find if a relationship tuple stating that a certain user is a viewer of a certain document
var request = 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 request = 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 request = 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 request = new ClientReadRequest()
    ._object("document:roadmap");

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

var options = new ClientReadOptions()
    .additionalHeaders(Map.of("Some-Http-Header", "Some value"))
    .pageSize(10)
    .continuationToken("...");

var response = fgaClient.read(request, options).get();

// 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

Passing ClientWriteOptions is optional. All fields of ClientWriteOptions are optional.

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 request = new ClientWriteRequest()
    .writes(List.of(
        new TupleKey()
            .user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
            .relation("viewer")
            ._object("document:roadmap"),
        new TupleKey()
            .user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
            .relation("viewer")
            ._object("document:budget")
    ))
    .deletes(List.of(
        new TupleKey()
            .user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
            .relation("writer")
            ._object("document:roadmap")
    ));

var options = new ClientWriteOptions()
    .additionalHeaders(Map.of("Some-Http-Header", "Some value"))
    // You can rely on the model id set in the configuration or override it for this specific request
    .authorizationModelId("01GXSA8YR785C4FYS3C0RTG7B1")
    .disableTransactions(false);

var response = fgaClient.write(request, options).get();

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.

Passing ClientWriteOptions with .disableTransactions(true) is required to use non-transaction mode. All other fields of ClientWriteOptions are optional.

var request = new ClientWriteRequest()
    .writes(List.of(
        new ClientTupleKey()
            .user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
            .relation("viewer")
            ._object("document:roadmap"),
        new ClientTupleKey()
            .user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
            .relation("viewer")
            ._object("document:budget")
    ))
    .deletes(List.of(
        new ClientTupleKeyWithoutCondition()
            .user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
            .relation("writer")
            ._object("document:roadmap")
    ));
var options = new ClientWriteOptions()
    .additionalHeaders(Map.of("Some-Http-Header", "Some value"))
    // You can rely on the model id set in the configuration or override it for this specific request
    .authorizationModelId("01GXSA8YR785C4FYS3C0RTG7B1")
    .disableTransactions(true)
    .transactionChunkSize(5); // Maximum number of requests to be sent in a transaction in a particular chunk

var response = fgaClient.write(request, options).get();

Relationship Queries

Check

Check if a user has a particular relation with an object.

API Documentation

Passing ClientCheckOptions is optional. All fields of ClientCheckOptions are optional.

var request = new ClientCheckRequest()
    .user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
    .relation("writer")
    ._object("document:roadmap");
var options = new ClientCheckOptions()
    .additionalHeaders(Map.of("Some-Http-Header", "Some value"))
    // You can rely on the model id set in the configuration or override it for this specific request
    .authorizationModelId("01GXSA8YR785C4FYS3C0RTG7B1");

var response = fgaClient.check(request, options).get();
// response.getAllowed() = 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.

Passing ClientBatchCheckOptions is optional. All fields of ClientBatchCheckOptions are optional.

var request = List.of(
    new ClientCheckRequest()
        .user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
        .relation("viewer")
        ._object("document:roadmap")
        .contextualTuples(List.of(
            new ClientTupleKey()
                .user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
                .relation("editor")
                ._object("document:roadmap")
        )),
    new ClientCheckRequest()
        .user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
        .relation("admin")
        ._object("document:roadmap"),
        .contextualTuples(List.of(
            new ClientTupleKey()
                .user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
                .relation("editor")
                ._object("document:roadmap")
        )),
    new ClientCheckRequest()
        .user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
        .relation("creator")
        ._object("document:roadmap"),
    new ClientCheckRequest()
        .user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
        .relation("deleter")
        ._object("document:roadmap")
);
var options = new ClientBatchCheckOptions()
    .additionalHeaders(Map.of("Some-Http-Header", "Some value"))
    // 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 response = fgaClient.batchCheck(request, options).get();

/*
response.getResponses() = [{
  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

Passing ClientExpandOptions is optional. All fields of ClientExpandOptions are optional.

var request = new ClientExpandRequest()
    .relation("viewer")
    ._object("document:roadmap");
var options = new ClientExpandOptions()
    .additionalHeaders(Map.of("Some-Http-Header", "Some value"))
    // You can rely on the model id set in the configuration or override it for this specific request
    .authorizationModelId("01GXSA8YR785C4FYS3C0RTG7B1");

var response = fgaClient.expand(request, options).get();

// response.getTree().getRoot() = {"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

Passing ClientListObjectsOptions is optional. All fields of ClientListObjectsOptions are optional.

var request = new ClientListObjectsRequest()
    .user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
    .relation("viewer")
    .type("document")
    .contextualTuples(List.of(
        new ClientTupleKey()
            .user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
            .relation("writer")
            ._object("document:budget")
    ));
var options = new ClientListObjectsOptions()
    .additionalHeaders(Map.of("Some-Http-Header", "Some value"))
    // You can rely on the model id set in the configuration or override it for this specific request
    .authorizationModelId("01GXSA8YR785C4FYS3C0RTG7B1");

var response = fgaClient.listObjects(request, options).get();

// response.getObjects() = ["document:roadmap"]
List Relations

List the relations a user has on an object.

Passing ClientListRelationsOptions is optional. All fields of ClientListRelationsOptions are optional.

var request = new ClientListRelationsRequest()
    .user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
    ._object("document:roadmap")
    .relations(List.of("can_view", "can_edit", "can_delete", "can_rename"))
    .contextualTuples(List.of(
        new ClientTupleKey()
            .user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
            .relation("editor")
            ._object("document:roadmap")
        )
    );
var options = new ClientListRelationsOptions()
    .additionalHeaders(Map.of("Some-Http-Header", "Some value"))
    // When unspecified, defaults to 10
    .maxParallelRequests()
    // You can rely on the model id set in the configuration or override it for this specific request
    .authorizationModelId(DEFAULT_AUTH_MODEL_ID);

var response = fgaClient.listRelations(request, options).get();

// response.getRelations() = ["can_view", "can_edit"]
List Users

List the users who have a certain relation to a particular type.

API Documentation

// Only a single filter is allowed for the time being
var userFilters = new ArrayList<UserTypeFilter>() {
    {
        add(new UserTypeFilter().type("user"));
        // user filters can also be of the form
        // add(new UserTypeFilter().type("team").relation("member"));
    }
};

var request = new ClientListUsersRequest()
    ._object(new FgaObject().type("document").id("roadmap"))
    .relation("can_read")
    .userFilters(userFilters)
    .context(Map.of("view_count", 100))
    .contextualTupleKeys(List.of(
        new ClientTupleKey()
            .user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
            .relation("editor")
            ._object("folder:product"),
        new ClientTupleKey()
            .user("folder:product")
            .relation("parent")
            ._object("document:roadmap")
));

var options = new ClientListUsersOptions()
    .additionalHeaders(Map.of("Some-Http-Header", "Some value"))
    // You can rely on the model id set in the configuration or override it for this specific request
    .authorizationModelId("01GXSA8YR785C4FYS3C0RTG7B1");

var response = fgaClient.listUsers(request, options).get();

// response.getUsers() = [{object: {type: "user", id: "81684243-9356-4421-8fbf-a4f8d36aa31b"}}, {userset: { type: "user" }}, ...]

Assertions

Read Assertions

Read assertions for a particular authorization model.

API Documentation

Passing ClientReadAssertionsOptions is optional. All fields of ClientReadAssertionsOptions are optional.

var options = new ClientReadAssertionsOptions()
    .additionalHeaders(Map.of("Some-Http-Header", "Some value"))
    // You can rely on the model id set in the configuration or override it for this specific request
    .authorizationModelId("01GXSA8YR785C4FYS3C0RTG7B1");
var response = fgaClient.readAssertions(options).get();
Write Assertions

Update the assertions for a particular authorization model.

API Documentation

Passing ClientWriteAssertionsOptions is optional. All fields of ClientWriteAssertionsOptions are optional.

var options = new ClientWriteAssertionsOptions()
    .additionalHeaders(Map.of("Some-Http-Header", "Some value"))
    .authorizationModelId("01GXSA8YR785C4FYS3C0RTG7B1");
var assertions = List.of(
    new ClientAssertion()
        .user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
        .relation("viewer")
        ._object("document:roadmap")
        .expectation(true)
);
fgaClient.writeAssertions(assertions, options).get();

Retries

If a network request fails with a 429 or 5xx error from the server, the SDK will automatically retry the request up to 15 times with a minimum wait time of 100 milliseconds between each attempt.

To customize this behavior, call maxRetries and minimumRetryDelay on the ClientConfiguration builder. maxRetries determines the maximum number of retries (up to 15), while minimumRetryDelay sets the minimum wait time between retries in milliseconds.

import com.fasterxml.jackson.databind.ObjectMapper;
import dev.openfga.sdk.api.client.OpenFgaClient;
import dev.openfga.sdk.api.configuration.ClientConfiguration;
import java.net.http.HttpClient;

public class Example {
    public static void main(String[] args) throws Exception {
        var config = new ClientConfiguration()
                .apiUrl(System.getenv("FGA_API_URL")) // If not specified, will default to "http://localhost:8080"
                .storeId(System.getenv("FGA_STORE_ID")) // Not required when calling createStore() or listStores()
                .authorizationModelId(System.getenv("FGA_MODEL_ID")) // Optional, can be overridden per request
                .maxRetries(3) // retry up to 3 times on API requests
                .minimumRetryDelay(250); // wait a minimum of 250 milliseconds between requests

        var fgaClient = new OpenFgaClient(config);
        var response = fgaClient.readAuthorizationModels().get();
    }
}

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
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 Java template, licensed under the Apache License 2.0.