Skip to main content
Version: 2.0.0

Dot Net Quickstart

Prerequisites:

This tutorial is intended for users who have completed the basic setup of at least one policy in Permit. If you haven’t done that yet, check out this guide first.

1. Get your Permit Environment API Key

  • In the Permit Dashboard, navigate to the Projects screen.
  • Find the Project and Environment you wish to connect to.
  • Click the Dots icon on the top right of the environment card.
  • Click Copy API Key.
Copy secret key from user menu
note

You can also copy the Environment API Key of the active environment by clicking on the User Menu > Copy Environment Key

Copy secret key from Projects management
Remember

The API Key that you will copy from the user menu is linked to the active environment on the sidebar. Switching to another active environment and then clicking on the Copy Environment Key option will copy a different API Key - the API key of the newly activated environment.

2. Setup your PDP (Policy Decision Point) Container

Permit provides you with a Policy Decision Point, which functions as your microservice for authorization. The PDP is provided as a docker container ready for you to use, or as a cloud version for quick experimentation.

It is extremely simple to utilize the cloud PDP. As part of the initialization of the Permit instance, you need to pass the cloud PDP URL.

note

The cloud PDP is great for quick experimentation with Permit, to learn how the service works, and to quickly integrate the SDK.

In production deployments, it is best to deploy the Docker Container PDP for better latency and availability.

For time being, the cloud PDP is not compatible with Attribute-based Access Control policies (ABAC) and also Relationship-based Access Control policies (ReBAC).

// This line initializes the SDK and connects your app
// to the Permit.io Cloud PDP.

const permit = new Permit({
pdp: "https://cloudpdp.api.permit.io",
// your API Key
token: "[YOUR_API_KEY]",
});

Add the SDK to your .NET code

We are now ready to init the .NET SDK and check for permissions.

  1. Create a new directory with an empty .NET project inside (we use HttpListener to demonstrate a REST API).
mkdir hello-permissions-dotnet && cd hello-permissions-dotnet && dotnet new console
  1. Install the Permit.io SDK

    dotnet add package Permit
  2. Import the SDK into your code

    using PermitSDK;
    using PermitSDK.Models;
  3. Create a new instance of the SDK.
    You can find instructions on getting a secret API key in the previous section.

    // This line initializes the SDK and connects your .NET app
    // to the Permit.io PDP container you've set up in the previous step.
    Permit permit = new Permit(
    "[YOUR_API_KEY]",
    "http://localhost:7766"
    );
    1. You can also set more config options when initializing the SDK.

      // you can also set more config options
      Permit permitClient = new Permit(
      // the API key to use
      token: "[YOUR_API_KEY]",
      // the URL of the Permit.io PDP container
      pdp: "http://localhost:7766",
      // the tenant to use if the tenant is not provided
      defaultTenant: "default",
      // whether to use the default tenant if the tenant is not provided
      useDefaultTenantIfEmpty: true,
      // should run in debug mode
      debugMode: true,
      // set the log level
      level: "info",
      // set the log label
      label: "Permitio-sdk",
      // should log as JSON
      logAsJson: false,
      // the URL of the API (relevant for EU customers)
      apiURL: "https://api.eu-central-1.permit.io",
      // should raise errors (instead of the default behavior of returning false for network errors in permit checks)
      raiseErrors: false,
      // Optional: manual set the environment_id and project_id for the SDK client (to avoid `scope` api call)
      envId: "[YOUR_ENVIRONMENT_ID]",
      projectId: "[YOUR_PROJECT_ID]"
      );

Check for permissions using the SDK

bool permitted = await permit.Check(user.key, "create", "document");
if (permitted)
{
Console.Write("User is PERMITTED to create a document");
}
else
{
Console.Write("User is NOT PERMITTED to create a document");
}
info

Usually for the user ID you'd use the unique identifier provided by your chosen authentication solution. You can also pass the entire decoded JWT, to include attributes about the user.

REMEMBER

In cases where you are dealing with more than one tenant in your application, permit.check() can pass the tenant as part of the resource.

The tenant passed in needs to be either the tenant id or the tenant key.

You can use the list_tenants API to get the ids and keys set for your tenants.

tenant: a unique tenant id or tenant key that you have defined within Permit.

Check permissions against ABAC policies

Above we have checked for permissions against an RBAC policy - but what if we have an ABAC policy we want to run a permission check for? An ABAC policy is made up of User Sets and Resource Sets, which you can read more about here.

With ABAC we define conditions based on pre-configured attributes.

If we are running a permit.check() for an ABAC policy, we replace the userId and the resource with objects, containing attributes.

UserKey user = new UserKey("userId", "John", "Smith", "john@smith.com");

var resourceInput = new ResourceInput(
"resource",
tenant: "tenant",
attributes: new Dictionary<string, string>
{
{"hasApproval", "True"}
}
);

bool permitted = await permit.Check(user, "action", resourceInput);
REMEMBER

Permission checks are being run against the PDP container that's running locally on your machine - offering minimal latency and without leaving your network.

This means that your user data never goes outside your system, keeping security high.

Full app example

Assuming a .NET app made up of a single file, with the Permit modules installed.

using System;
using System.Text;
using System.Net;
using System.Threading.Tasks;
using PermitSDK;
using PermitSDK.Models;

namespace PermitOnboardingApp
{
class HttpServer
{
public static HttpListener listener;
public static string url = "http://localhost:4000/";
public static string pageData ="<p>User {0} is {1} to {2} {3}</p>";
public static async Task HandleIncomingConnections()
{
bool runServer = true;
while (runServer)
{
HttpListenerContext ctx = await listener.GetContextAsync();
HttpListenerResponse resp = ctx.Response;

// in a real app, you would typically decode the user id from a JWT token
UserKey user = new UserKey("userId", "John", "Smith", "john@permit.io");
// init Permit SDK
string clientToken = "[YOUR_API_KEY]";
Permit permit = new Permit(
clientToken,
"http://localhost:7766",
"default",
true
);
// After we created this user in the previous step, we also synced the user's identifier
// to permit.io servers with permit.write(permit.api.syncUser(user)). The user identifier
// can be anything (email, db id, etc) but must be unique for each user. Now that the
// user is synced, we can use its identifier to check permissions with `permit.check()`.
bool permitted = await permit.Check(user.key, "create", "task");
if (permitted)
{
await SendResponseAsync(resp, 200, String.Format(pageData, user.firstName + user.lastName, "Permitted", "create", "task"));
}
else
{
await SendResponseAsync(resp, 403, String.Format(pageData, user.firstName + user.lastName, "NOT Permitted", "create", "task"));
}

}
}
public static async Task SendResponseAsync(HttpListenerResponse resp, int returnCode, string responseContent)
{
byte[] data = Encoding.UTF8.GetBytes(responseContent);
resp.StatusCode = returnCode;
await resp.OutputStream.WriteAsync(data, 0, data.Length);
resp.Close();
}

public static void Main(string[] args)
{
// Create a Http server and start listening for incoming connections
listener = new HttpListener();
listener.Prefixes.Add(url);
listener.Start();
Console.WriteLine("Listening for connections on {0}", url);
Task listenTask = HandleIncomingConnections();
listenTask.GetAwaiter().GetResult();
listener.Close();
}
}
}

Now that your application is ready, let's run it:

dotnet run

Finally, go to http://localhost:4000 to see the outcome of the permission check.