Fga.Net 0.3.0-alpha

.NET 6.0
This is a prerelease version of Fga.Net.
NuGet\Install-Package Fga.Net -Version 0.3.0-alpha
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.
dotnet add package Fga.Net --version 0.3.0-alpha
<PackageReference Include="Fga.Net" Version="0.3.0-alpha" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Fga.Net --version 0.3.0-alpha
#r "nuget: Fga.Net, 0.3.0-alpha"
#r directive can be used in F# Interactive, C# scripting and .NET Interactive. Copy this into the interactive tool or source code of the script to reference the package.
// Install Fga.Net as a Cake Addin
#addin nuget:?package=Fga.Net&version=0.3.0-alpha&prerelease

// Install Fga.Net as a Cake Tool
#tool nuget:?package=Fga.Net&version=0.3.0-alpha&prerelease

Auth0 FGA for .NET & ASP.NET Core

Nuget (with prereleases) Nuget (with prereleases)

Packages

  • Fga.Net: Provides an auto-generated NSwag client for accessing the FGA API, alongside an authentication client, token caching middleware, and dependency injection extensions.

  • Fga.Net.AspNetCore: Additionally includes Authorization middleware to support FGA checks as part of a request's lifecycle.

Getting Started

Note: This project is in its early stages and will have breaking changes as FGA matures.

Please ensure you have a basic understanding of how FGA works before continuing: https://docs.fga.dev/

ASP.NET Core Setup

Before getting started, ensure you have a Store ID, Client ID, and Client Secret ready from How to get your API keys.

I'm also assuming you have authentication setup within your project, such as JWT bearer authentication via Auth0.

  1. Install Fga.Net.AspNetCore from Nuget.
  2. Add your StoreId, ClientId and ClientSecret to your application configuration, ideally via the dotnet secrets manager.
  3. Add the following code to your ASP.NET Core configuration:
// Registers FgaAuthenticationClient, FgaAuthorizationClient, and the authorization handler
builder.Services.AddAuth0Fga(x =>
{
    x.ClientId = builder.Configuration["Auth0Fga:ClientId"];
    x.ClientSecret = builder.Configuration["Auth0Fga:ClientSecret"];
});

// Register the authorization policy
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy(FgaAuthorizationDefaults.PolicyKey, 
        p => p
            .RequireAuthenticatedUser()
            .AddFgaRequirement(builder.Configuration["Auth0Fga:StoreId"]));
});
  1. Create an attribute that inherits from TupleCheckAttribute. From here, you can pull the metadata you require to perform your tuple checks out of the HTTP request. For example, an equivalent to the How To Integrate Within A Framework example would be:
public class EntityAuthorizationAttribute : TupleCheckAttribute
{
    private readonly string _prefix;
    private readonly string _routeValue;
    public EntityAuthorizationAttribute(string prefix, string routeValue)
    {
        _prefix = prefix;
        _routeValue = routeValue;
    }

    public override ValueTask<string> GetUser(HttpContext context) 
        => ValueTask.FromResult(context.User.Identity!.Name!);

    public override ValueTask<string> GetRelation(HttpContext context) 
        => ValueTask.FromResult(context.Request.Method switch 
        {
            "GET" => "viewer",
            "POST" => "writer",
            _ => "owner"
        });

    public override ValueTask<string> GetObject(HttpContext context) 
        => ValueTask.FromResult($"{_prefix}:{context.GetRouteValue(_routeValue)}");
}
  1. Apply the Authorize and EntityAuthorization attributes to your controller(s):
    [ApiController]
    [Route("[controller]")]
    [Authorize(FgaAuthorizationDefaults.PolicyKey)]
    public class DocumentController : ControllerBase
    {  
        [HttpGet("view/{documentId}")]
        [EntityAuthorization("doc", "documentId")]
        public string GetByConvention(string documentId)
        {
            return documentId;
        }
    }

If you need to manually perform checks, inject the IFgaAuthorizationClient as required.

An additional pre-made attribute that allows all tuple values to be hardcoded strings ships with the package (StringTupleCheckAttribute). This attrbute is useful for testing and debug purposes, but should not be used in a real application.

Worker Service / Generic Host Setup

Fga.Net ships with the AddAuth0FgaAuthenticationClient and AddAuth0FgaAuthorizationClient service collection extensions that handle all required wire-up.

To get started:

  1. Install Fga.Net
  2. Add your StoreId, ClientId and ClientSecret to your application configuration, ideally via the dotnet secrets manager.
  3. Register the authentication & authorization clients:
var host = Host.CreateDefaultBuilder(args)
    .ConfigureServices((context, services) =>
    {
        services.AddAuth0FgaAuthenticationClient();
        services.AddAuth0FgaAuthorizationClient(config =>
        {
            config.ClientId = context.Configuration["Auth0Fga:ClientId"];
            config.ClientSecret = context.Configuration["Auth0Fga:ClientSecret"];
        });

        services.AddHostedService<MyBackgroundWorker>();
    })
    .Build();

await host.RunAsync();
  1. Request the client in your services:
public class MyBackgroundWorker : BackgroundService
{
    private readonly IFgaAuthorizationClient _authorizationClient;

    public MyBackgroundWorker(IFgaAuthorizationClient authorizationClient)
    {
        _authorizationClient = authorizationClient;
    }

    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        // Do work with the client
    }
}

Standalone client setup

Useful for testing.

I would not recommend a standalone client setup outside of transient lambda scenarios as the HttpClient lifetime is not automatically maintained.

  1. Install Fga.Net
  2. Create the authorization client as below:
var clientId = args[0];
var clientSecret = args[1];
var storeId = args[2];

var client = FgaAuthorizationClient.Create(FgaAuthenticationClient.Create(), new FgaClientConfiguration
{
    ClientId = clientId,
    ClientSecret = clientSecret
});

var response = await client.CheckAsync(storeId, new CheckRequestParams
{
    Tuple_key = new TupleKey()
    {
        User = "",
        Relation = "",
        Object = ""
    }
});

Internal Cache

The FgaTokenCache will cache the FGA authorization token until 15 minutes before expiry. This is not currently customizable.

This cache is automatically enabled if you use any of the DI extensions, as well as FgaAuthorizationClient.Create.

Disclaimer

I am not affiliated with nor represent Auth0. All support queries regarding the underlying service should go to the Auth0 Labs Discord.

Product Versions
.NET net6.0 net6.0-android net6.0-ios net6.0-maccatalyst net6.0-macos net6.0-tvos net6.0-windows
Compatible target framework(s)
Additional computed target framework(s)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
0.3.0-alpha 72 2/13/2022
0.2.0-alpha 77 12/20/2021
0.1.1-alpha 76 12/20/2021
0.1.0-alpha 82 12/20/2021