This is an autogenerated Java 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)
The OpenFGA Java SDK is available on Maven Central.
It can be used with the following:
- Gradle (Groovy)
implementation 'dev.openfga:openfga-sdk:0.2.2'
- Gradle (Kotlin)
implementation("dev.openfga:openfga-sdk:0.2.2")
- Apache Maven
<dependency>
<groupId>dev.openfga</groupId>
<artifactId>openfga-sdk</artifactId>
<version>0.2.2</version>
</dependency>
- Ivy
<dependency org="dev.openfga" name="openfga-sdk" rev="0.2.2"/>
- SBT
libraryDependencies += "dev.openfga" % "openfga-sdk" % "0.2.2"
- Leiningen
[dev.openfga/openfga-sdk "0.2.2"]
Learn how to initialize your SDK
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("OPENFGA_API_URL")) // If not specified, will default to "https://localhost:8080"
.storeId(System.getenv("OPENFGA_STORE_ID")) // Not required when calling createStore() or listStores()
.authorizationModelId(System.getenv("OPENFGA_AUTHORIZATION_MODEL_ID")); // Optional, can be overridden per request
var fgaClient = new OpenFgaClient(config);
var response = fgaClient.readAuthorizationModels().get();
}
}
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("OPENFGA_API_URL")) // If not specified, will default to "https://localhost:8080"
.storeId(System.getenv("OPENFGA_STORE_ID")) // Not required when calling createStore() or listStores()
.authorizationModelId(System.getenv("OPENFGA_AUTHORIZATION_MODEL_ID")) // Optional, can be overridden per request
.credentials(new Credentials(
new ApiToken(System.getenv("OPENFGA_API_TOKEN")) // will be passed as the "Authorization: Bearer ${ApiToken}" request header
));
var fgaClient = new OpenFgaClient(config);
var response = fgaClient.readAuthorizationModels().get();
}
}
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("OPENFGA_API_URL")) // If not specified, will default to "https://localhost:8080"
.storeId(System.getenv("OPENFGA_STORE_ID")) // Not required when calling createStore() or listStores()
.authorizationModelId(System.getenv("OPENFGA_AUTHORIZATION_MODEL_ID")) // Optional, can be overridden per request
.credentials(new Credentials(
new ClientCredentials()
.apiTokenIssuer(System.getenv("OPENFGA_API_TOKEN_ISSUER"))
.apiAudience(System.getenv("OPENFGA_API_AUDIENCE"))
.clientId(System.getenv("OPENFGA_CLIENT_ID"))
.clientSecret(System.getenv("OPENFGA_CLIENT_SECRET"))
));
var fgaClient = new OpenFgaClient(config);
var response = fgaClient.readAuthorizationModels().get();
}
}
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.
Get a paginated list of stores.
var options = new ClientListStoresOptions()
.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" }]
Initialize a store.
var request = new CreateStoreRequest().name("FGA Demo");
var store = fgaClient.createStore(request).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 information about the current store.
Requires a client initialized with a storeId
var store = fgaClient.getStore().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 a store.
Requires a client initialized with a storeId
var store = fgaClient.deleteStore().get();
Read all authorization models in the store.
var options = new ClientReadAuthorizationModelsOptions()
.pageSize(10)
.continuationToken("...");
var response = fgaClient.readAuthorizationModels(options).get();
// response.getAuthorizationModels() = [
// { id: "01GXSA8YR785C4FYS3C0RTG7B1", schemaVersion: "1.1", typeDefinitions: [...] },
// { id: "01GXSBM5PVYHCJNRNKXMB4QZTW", schemaVersion: "1.1", typeDefinitions: [...] }];
Create a new authorization model.
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.
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 response = fgaClient.writeAuthorizationModel(request).get();
// response.getAuthorizationModelId() = "01GXSA8YR785C4FYS3C0RTG7B1"
Read a particular authorization model.
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 = fgaClient.readAuthorizationModel(options).get();
// response.getAuthorizationModel().getId() = "01GXSA8YR785C4FYS3C0RTG7B1"
// response.getAuthorizationModel().getSchemaVersion() = "1.1"
// response.getAuthorizationModel().getTypeDefinitions() = [{ "type": "document", "relations": { ... } }, { "type": "user", "relations": { ... }}]
Reads the latest authorization model (note: this ignores the model id in configuration).
var response = fgaClient.readLatestAuthorizationModel().get();
// response.getAuthorizationModel().getId() = "01GXSA8YR785C4FYS3C0RTG7B1"
// response.getAuthorizationModel().SchemaVersion() = "1.1"
// response.getAuthorizationModel().TypeDefinitions() = [{ "type": "document", "relations": { ... } }, { "type": "user", "relations": { ... }}]
Reads the list of historical relationship tuple writes and deletes.
var options = new ClientReadChangesOptions()
.type("document")
.pageSize(10)
.continuationToken("...");
var response = fgaClient.readChanges(options).get();
// response.getContinuationToken() = ...
// response.getChanges() = [
// { tupleKey: { user, relation, object }, operation: TupleOperation.WRITE, timestamp: ... },
// { tupleKey: { user, relation, object }, operation: TupleOperation.DELETE, timestamp: ... }
// ]
Reads the relationship tuples stored in the database. It does not evaluate nor exclude invalid tuples according to the authorization model.
// 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()
.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 }, ...]}
Create and/or delete relationship tuples to update the system state.
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")
));
// You can rely on the model id set in the configuration or override it for this specific request
var options = new ClientWriteOptions()
.authorizationModelId("01GXSA8YR785C4FYS3C0RTG7B1");
var response = fgaClient.write(request, options).get();
Convenience WriteTuples
and DeleteTuples
methods are also available.
The SDK will split the writes into separate requests and send them sequentially to avoid violating rate limits.
// Coming soon
Check if a user has a particular relation with an object.
var request = new ClientCheckRequest()
.user("user:81684243-9356-4421-8fbf-a4f8d36aa31b")
.relation("writer")
._object("document:roadmap");
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 response = fgaClient.check(request, options).get();
// response.getAllowed() = true
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.
// Coming soon
Expands the relationships in userset tree format.
var request = new ClientExpandRequest()
.relation("viewer")
._object("document:roadmap");
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 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 the objects of a particular type a user has access to.
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()
// 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 the relations a user has on an object.
// Coming soon.
Read assertions for a particular authorization model.
var options = new ClientReadAssertionsOptions()
.authorizationModelId("01GXSA8YR785C4FYS3C0RTG7B1");
var response = fgaClient.readAssertions(options).get();
Update the assertions for a particular authorization model.
var options = new ClientWriteAssertionsOptions()
.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();
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 |
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 Java template, licensed under the Apache License 2.0.