Code Monkey home page Code Monkey logo

spring-boot-starter's Introduction

OpenFGA Spring Boot Starter

License FOSSA Status Join our community Twitter

A Spring Boot Starter for OpenFGA.

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 Spring Boot Starter is available on Maven Central.

It can be used with the following:

  • Gradle (Groovy)
implementation 'dev.openfga:openfga-spring-boot-starter:0.0.1'
  • Gradle (Kotlin)
implementation("dev.openfga:openfga-spring-boot-starter:0.0.1")
  • Apache Maven
<dependency>
    <groupId>dev.openfga</groupId>
    <artifactId>openfga-spring-boot-starter</artifactId>
    <version>0.0.1</version>
</dependency>

Getting Started

Requirements

Java 17 and Spring Boot 3

Configuring the starter

The OpenFGA Spring Boot Starter can be configured via standard Spring configuration. The configuration properties are used to create an OpenFgaClient instance.

No Credentials

# src/main/resources/application.yaml

openfga:
  api-url: YOUR_FGA_API_URL
  store-id: YOUR_FGA_STORE_ID
  authorization-model-id: YOUR_FGA_AUTHORIZATION_MODEL_ID

API Token

# src/main/resources/application.yaml

openfga:
  api-url: YOUR_FGA_API_URL
  store-id: YOUR_FGA_STORE_ID
  authorization-model-id: YOUR_FGA_AUTHORIZATION_MODEL_ID
  credentials:
    method: API_TOKEN # constant
    config:
      api-token: YOUR_API_TOKEN

Client Credentials

# src/main/resources/application.yaml

openfga:
  api-url: YOUR_FGA_API_URL
  store-id: YOUR_FGA_STORE_ID
  authorization-model-id: YOUR_FGA_AUTHORIZATION_MODEL_ID
  credentials:
    method: CLIENT_CONFIGURATION # constant
    config:
        client-id: YOUR_CLIENT_ID
        client-secret: YOUR_CLIENT_SECRET
        api-token-issuer: YOUR_API_TOKEN_ISSUER
        api-audience: YOUR_API_AUDIENCE
        scopes: YOUR_SPACE_SEPERATED_SCOPES

Using the fgaClient bean

Once configured, an fgaClient bean is available to be injected into your Spring components:

@Service
public class MyService {
    
    @Autowired
    private OpenFgaClient fgaClient;
}

This can be used to interact with the FGA API, for example to write authorization data:

public Document createDoc(String id) {
    // ...
    ClientWriteRequest writeRequest =  new ClientWriteRequest()
            .writes(List.of(new ClientTupleKey()
                    .user(String.format("user:%s", SecurityContextHolder.getContext().getAuthentication()))
                    .relation("owner")
                    ._object(String.format("document:%s", id))));

    try {
        fgaClient.write(writeRequest).get();
    } catch (InterruptedException | ExecutionException | FgaInvalidParameterException e) {
        throw new RuntimeException("Error writing to FGA", e);
    }
    // ...
}

Using the fga bean

The starter also creates an fga bean, which can be used in conjunction with Spring Security's method security to protect access to resources using FGA:

// Method body will only execute if the FGA check returns true. 403 otherwise.
@PreAuthorize("@fga.check('document', #docId, 'reader', 'user', authentication?.name)")
public Document getDocument(@PathVariable String docId) {
    return repository.findById(id);
}

You may also omit the user ID, in which case the name of the currently authenticated principal will be used as the user ID:

// Method body will only execute if the FGA check returns true. 403 otherwise.
@PreAuthorize("@fga.check('document', #docId, 'reader', 'user')")
public Document getDocument(@PathVariable String docId) {
    return repository.findById(id);
}

Contributing

Issues

If you have found a bug or if you have a feature request, please create an issue. Please do not report security vulnerabilities on the public GitHub issue tracker.

Pull Requests

Pull requests are welcome, however we do kindly ask that for non-trivial changes or feature additions, that you create an issue first.

Author

OpenFGA

License

This project is licensed under the Apache-2.0 license. See the LICENSE file for more info.

spring-boot-starter's People

Contributors

jimmyjames avatar dependabot[bot] avatar evansims avatar rhamzeh avatar ewanharris avatar indiepopart avatar

Stargazers

Martin Besozzi avatar Jared Bates avatar Thomas Darimont avatar 윤성복 avatar Nathanael COURET avatar Robert Buruleanu avatar Aldric avatar Joseph Gan avatar Eddú Meléndez Gonzales avatar  avatar Perry Arellano-Jones avatar Maria Ines Parnisari avatar  avatar Andrés Aguiar avatar

Watchers

 avatar Chris Aniszczyk avatar  avatar  avatar Patrick Dillon avatar  avatar Talent Zeng avatar  avatar Adrian Tam avatar Poovamraj T T avatar  avatar  avatar

spring-boot-starter's Issues

feature: support contextual tuples and context params

When making an FGA check, contextual tuples and/or a context parameter can be passed for more advanced authorization scenarios.

Contextual tuples

Contextual tuples can be sent in a check request and will be part of the authorization evaluation as if they exist they in the store.

For example, user:123 is a member of the marketing group, and the marketing group has been granted the viewer relationship for document:roadmap.

We can send conditional tuples on the request to inform the groups to which user:123 belongs (e.g., from a groups claim):

var body = new ClientCheckRequest()
      .user("user:123")
      .relation("viewer")
      ._object("document:1")
      .contextualTuples(
          List.of(
              new ClientTupleKey()
                  .user("user:123")
                  .relation("member")
                  ._object("group:marketing"),
              new ClientTupleKey()
                  .user("user:123")
                  .relation("member")
                  ._object("group:everyone")
          ));

var allowed = fga.check(body).get().getAllowed();

Conext with conditions

An authorization model may define a condition, and a context parameter can be supplied to the check request as part of the authorization criteria. For example, a condition could exist that specifies that user:anne has viewer relationship to document:roadmap only if the current time is within 10 minutes of the time access was granted.

Example model:

model
  schema 1.1

type user

type document
  relations
    define viewer: [user with non_expired_grant]

condition non_expired_grant(current_time: timestamp, grant_time: timestamp, grant_duration: duration) {
  current_time < grant_time + grant_duration
}

Write a tuple with a condition:

var body = new ClientWriteRequest()
        .writes(List.of(
                new ClientTupleKey()
                        .user("user:123")
                        .relation("viewer")
                        ._object("document:roadmap")
                        .condition(new ClientRelationshipCondition()
                                .name("non_expired_grant")
                                .context(Map.of("grant_time", "2023-01-01T00:00:00Z","grant_duration", "10m"))
                        )
                        
        ));

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

Send a check request including the context parameter:

var body = new ClientCheckRequest()
      .user("user:123")
      .relation("viewer")
      ._object("document:1")
      .context(Map.of("current_time", "2023-01-01T00:10:01Z"));

var response = fga.check(body).get();

References

Create WebFlux example

Create a simple WebFlux example that demonstrates:

  • Configuring an FGA client
  • Writing FGA data
  • Protecting a method with an FGA check

Consider additional FGA client configuration

The OpenFgaClient offers additional configurations than those surfaced in #12 (timeouts, maxRetries, etc). We should catalog these and consider if we should expose them for configuration of the openFgaClient bean.

Provide pre-method simple FGA check support

Enable an FGA check to be run pre-method invocation. If the check fails, the method body should not be executed and the result should not be returned to the client.

For initial offering, checks with contextual tuples or context are not to be included.

Create Servlet example

Create a simple Servlet example that demonstrates:

  • Configuring an FGA client
  • Writing FGA data
  • Protecting a method with an FGA check

README

Create/update README:

  • Consistent with FGA repositories
  • Documents install/usage

Initial Spring Boot Support

Epic to contain v0 support for FGA with Spring Security.

This work broadly entails:

  • Enabling the configuration of an OpenFgaClient bean
  • A simple FGA check to be used at least for pre-method invocation security (no contextual tuples or context, or list API support; those will come later)

Tasks:

Provide OpenFgaClient auto configuration

Provide a configured OpenFgaClient bean.

The client should be configured via application properties or yaml, or environment variables, per the normal Spring convention, and should have a specific prefix (e.g., openfga.*)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.