Connect your app and run your first permission check
Connect an application to Permit.io and call permit.check() to allow or deny a request based on the user's role. This tutorial is for backend developers who have a Permit.io policy and want to enforce the policy from code. At the end, you have a running demo application that returns an allow or deny result for each request, and the check appears in the Permit audit log.
Prerequisites
- A Permit.io account with at least one policy. If you don't have a policy yet, complete the Quickstart.
- Docker, if you run the policy decision point (PDP) as a container. See Install Docker.
1. Get your environment API key
The SDK and the PDP authenticate with Permit using an environment API key. Each API key belongs to one environment.
- In the Permit dashboard, open the Projects screen.
- Find the project and the environment you want to connect to.
- On the environment card, click the
icon in the top-right corner.
- Click Copy API Key.
You can also copy the API key of the active environment from User Menu > Copy Environment Key.

The API key you copy from the user menu belongs to the active environment in the sidebar. If you switch the active environment and click Copy Environment Key again, you copy a different API key: the key of the newly active environment.
Anyone with your environment API key can change that environment's policy and data through the Permit API. Load the API key from an environment variable or a secret store, and don't commit the API key to your repository.
2. Set up your policy decision point (PDP)
Your application sends each permission check to a policy decision point (PDP), the service that evaluates the check against your policy. Use the managed Cloud PDP that Permit.io runs, or run the PDP as a Docker container on your machine.
The SDK examples on this page connect to a container PDP at http://localhost:7766. To use the Cloud PDP, set the SDK's PDP URL to https://cloudpdp.api.permit.io instead.
- Cloud PDP
- Container PDP
The Cloud PDP needs no installation. Pass the Cloud PDP URL when you initialize the Permit SDK. The following Node.js example shows the shape. The SDK install step further down shows the same setting in this page's language. Replace [YOUR_API_KEY] with your environment API key:
// 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]",
});
The Cloud PDP is a managed service that Permit.io runs. The Cloud PDP supports RBAC (role-based access control) and ReBAC (relationship-based access control) policies. The Cloud PDP does not support ABAC (attribute-based access control) policies, so the ABAC examples on this page need a container PDP.
For capabilities, limits, and when to choose each PDP type, see Cloud PDP capabilities.
Pull and run the permitio/pdp-v2 container image. Docker must be installed and running.
1. Pull the PDP container from Docker Hub
docker pull permitio/pdp-v2:latest
2. Run the PDP container
Replace <YOUR_API_KEY> with the environment API key you copied in 1. Get your environment API key, then run:
docker run -it -p 7766:7000 --env PDP_DEBUG=True --env PDP_API_KEY=<YOUR_API_KEY> permitio/pdp-v2:latest
| Option | Meaning |
|---|---|
-p 7766:7000 | Maps port 7766 on your machine to port 7000 inside the container. The SDK sends checks to http://localhost:7766. |
PDP_API_KEY | The environment API key. The PDP uses the API key to load that environment's policy and data from Permit. |
PDP_DEBUG=True | Turns on debug logging in the container output. |
To confirm the PDP container is running, run docker ps in a second terminal. The output lists a container from the permitio/pdp-v2:latest image with 0.0.0.0:7766->7000/tcp in the PORTS column.
For more PDP options, see Run the PDP.
3. Install the SDK and check permissions
Select your language. Each tab installs the Permit.io SDK, creates a client that connects to your PDP, runs permit.check(), and runs a full demo application.
NodeJS
Python (sync)
Python (asyncio)
Java
Golang
Ruby
.Net
Install and initialize the Node.js SDK
Install the permitio package, import the Permit class, and create a Permit client that connects to your PDP.
- Install the Permit.io Node.js SDK:
npm install permitio
- Import the
Permitclass with an ES moduleimportor a CommonJSrequire:
- Import
- Require
import { Permit } from "permitio";
const { Permit } = require("permitio");
- Create a
Permitclient. Replace[YOUR_API_KEY]with your environment API key, and setpdpto the URL of your PDP:
// This line initializes the SDK and connects your Node.js app
// to the Permit.io PDP container you've set up in the previous step.
const permit = new Permit({
// your API Key
token: "[YOUR_API_KEY]",
// in production, you might need to change this url to fit your deployment
pdp: "http://localhost:7766",
// if you want the SDK to emit logs, uncomment this:
// log: {
// level: "debug",
// },
// By default, permit.check() throws on a timeout / network error.
// To make permit.check() return false instead, uncomment this:
// throwOnError: false,
});
| Option | Description |
|---|---|
token | Your environment API key. |
pdp | The URL of the PDP that evaluates checks: http://localhost:7766 for the container PDP, or https://cloudpdp.api.permit.io for the Cloud PDP. |
log.level | The SDK log level, for example "debug". |
throwOnError | Set to true to make permit.check() throw when the PDP request fails, or false to make permit.check() return false instead. |
Check permissions with the Node.js SDK
Call permit.check() with three arguments. permit.check() returns a promise that resolves to true when the policy allows the action, and false otherwise.
| Argument | Description |
|---|---|
user | The key that identifies the user in Permit, typically the user ID from your authentication provider. To pass attributes, use an object with key and attributes. |
action | The action key, for example create. |
resource | The resource type key, for example document, or an object with type, tenant, and attributes. |
This example checks whether the user john@permit.io can create a document:
const permitted = await permit.check("john@permit.io", "create", "document");
if (permitted) {
console.log("John is PERMITTED to create a document");
} else {
console.log("John is NOT PERMITTED to create a document");
}
If john@permit.io exists in your environment and has a role that grants create on document, the example prints John is PERMITTED to create a document. Otherwise, the example prints John is NOT PERMITTED to create a document. To add users and assign roles, see Sync users.
Check a permission in a specific tenant
In a multi-tenant application, pass the tenant key in the tenant field of the resource object. To look up the keys of your tenants, call the list tenants API.
This example checks whether john@permit.io can read documents in the awesome_inc tenant:
const permitted = await permit.check(
// the key of the user
"john@permit.io",
// the action
"read",
{
type: "document",
tenant: "awesome_inc",
}
);
permit.check() sends each check to the PDP URL you configure. A container PDP evaluates checks on your machine, using policy and data that the PDP loads from Permit. Users, roles, and attributes that you create in the dashboard or sync through the Permit API are stored in the Permit control plane.
Check ABAC permissions with the Node.js SDK
An attribute-based access control (ABAC) policy grants permissions based on user and resource attributes, grouped into user sets and resource sets. See ABAC policy components. ABAC checks need a container PDP.
To check an ABAC policy, pass the user and the resource as objects with just-in-time attributes, which you pass in the check call. In this example, replace check@permit.io, action, resource, and tenant with a user key, action key, resource key, and tenant key from your environment:
const permitted = await permit.check(
// the user object
{
// the user key
key: "check@permit.io",
// just-in-time attributes on the user
attributes: {
location: "England",
department: "Engineering",
},
},
// the action the user is trying to do
"action",
// Resource
{
// the type of the resource (the resource key)
type: "resource",
// just-in-time attributes on the resource
attributes: {
hasApproval: "true",
},
// the tenant the resource belong to
tenant: "tenant",
}
);
For more check options, see Check permissions with permit.check().
Run a full Node.js example app
This single-file Express app runs a permission check on each request to http://localhost:4000.
- In a new project directory, install the
permitioandexpresspackages withnpm install permitio express. - Save the following code as
app.js. - Replace
[YOUR_API_KEY]with your environment API key, and[A_USER_ID]with the key of a user in your environment.
const { Permit } = require("permitio");
const express = require("express");
const app = express();
const port = 4000;
// This line initializes the SDK and connects your Node.js app
// to the Permit.io PDP container you've set up in the previous step.
const permit = new Permit({
// in production, you might need to change this url to fit your deployment
pdp: "http://localhost:7766",
// your secret API Key
token: "[YOUR_API_KEY]",
});
// You can open http://localhost:4000 to invoke this http
// endpoint, and see the outcome of the permission check.
app.get("/", async (req, res) => {
// Example user object
// You would usually get the user from your authentication layer (e.g. Auth0, Cognito, etc) via a JWT token or a database.
const user = {
key: "[A_USER_ID]",
firstName: "John",
lastName: "Smith",
email: "john@permit.io",
};
// check for permissions to a resource and action (in this example, create a document)
const permitted = await permit.check(user.key, "create", "document");
if (permitted) {
res.status(200).send(`${user.firstName} ${user.lastName} is PERMITTED to create document!`);
} else {
res.status(403).send(`${user.firstName} ${user.lastName} is NOT PERMITTED to create document!`);
}
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
- Run
node app.js. The terminal printsExample app listening at http://localhost:4000. - Open
http://localhost:4000in a browser.
If the user's role grants create on document, the page returns HTTP 200 with John Smith is PERMITTED to create document!. Otherwise, the page returns HTTP 403 with John Smith is NOT PERMITTED to create document!.
Install and initialize the Python SDK (sync)
Install the permit package, import the sync Permit class, and create a Permit client that connects to your PDP. Use the sync SDK when your code doesn't use asyncio. The sync SDK and the asyncio SDK ship in the same permit package.
- Install the Permit.io Python SDK:
pip install permit
- Import the
Permitclass frompermit.sync. ThePermitclass in the top-levelpermitmodule is the asyncio version.
from permit.sync import Permit
- Create a
Permitclient. Replace<YOUR_API_KEY>with your environment API key, and setpdpto the URL of your PDP:
# Connect the SDK to the PDP that evaluates permission checks.
permit = Permit(
# in production, change this URL to the address of your PDP
pdp="http://localhost:7766",
# your environment API key
token="<YOUR_API_KEY>",
)
| Option | Description |
|---|---|
token | Your environment API key. |
pdp | The URL of the PDP that evaluates checks: http://localhost:7766 for the container PDP, or https://cloudpdp.api.permit.io for the Cloud PDP. |
To send checks to the managed Cloud PDP instead of a container PDP, set pdp to the Cloud PDP URL:
permit = Permit(
pdp="https://cloudpdp.api.permit.io",
token="<YOUR_API_KEY>",
)
The Cloud PDP supports RBAC (role-based access control) and ReBAC (relationship-based access control) policies. ABAC (attribute-based access control) checks need a container PDP. See Cloud PDP capabilities.
Check permissions with the Python SDK (sync)
Call permit.check() with three arguments. With the sync SDK, permit.check() returns True or False directly, so you call permit.check() without await. permit.check() returns True when the policy allows the action, and False otherwise.
| Argument | Description |
|---|---|
user | The key that identifies the user in Permit, typically the user ID from your authentication provider. To pass attributes, use a dictionary with key and attributes. |
action | The action key, for example create. |
resource | The resource type key, for example document, or a dictionary with type, tenant, and attributes. |
This example checks whether the user john@smith.com can create a document:
permitted = permit.check("john@smith.com", "create", "document")
if permitted:
print("John is permitted to create a document")
else:
print("John is NOT PERMITTED to create document!")
If john@smith.com exists in your environment and has a role that grants create on document, the example prints John is permitted to create a document. Otherwise, the example prints John is NOT PERMITTED to create document!. To add users and assign roles, see Sync users.
Check a permission in a specific tenant
In a multi-tenant application, pass the tenant key in the tenant field of the resource dictionary. To look up the keys of your tenants, call the list tenants API. In this example, replace userId, action, resource, and tenant with a user key, action key, resource key, and tenant key from your environment:
permitted = permit.check("userId", "action", {"type": "resource", "tenant": "tenant"})
permit.check() sends each check to the PDP URL you configure. A container PDP evaluates checks on your machine, using policy and data that the PDP loads from Permit. Users, roles, and attributes that you create in the dashboard or sync through the Permit API are stored in the Permit control plane.
Run a full Python example app (Flask)
This single-file Flask app syncs a user and a tenant to Permit when the app starts, then runs a permission check on each request. The app is safe to restart: permit.api.users.sync() updates a user that already exists, and the app catches PermitAlreadyExistsError when the tenant2 tenant already exists.
- Create a directory for the project:
mkdir hello-permissions && cd hello-permissions
- Optional: create a virtual environment for the project. The following command needs
pyenvandpyenv-virtualenv.
pyenv virtualenv permissions && pyenv activate permissions
- Install the Permit.io SDK and Flask:
pip install permit flask
- Create a file called
test.py:
touch test.py
-
Copy the following code into
test.py. Replace<YOUR_API_KEY>with your environment API key.The first part of
test.pycreates the Flask app and the Permit client:
import json
from permit.sync import Permit
from permit.exceptions import PermitAlreadyExistsError
from flask import Flask, Response
app = Flask(__name__)
# Connect the SDK to the PDP that evaluates permission checks.
permit = Permit(
# in production, change this URL to the address of your PDP
pdp="http://localhost:7766",
# your environment API key
token="<YOUR_API_KEY>",
)
Append sync_objects(), which creates the user, the tenant2 tenant, and the two role assignments when the app starts:
def sync_objects():
# create the user, or update the user when the key already exists
permit.api.users.sync({
"key": "john@smith.com",
"first_name": "John",
"last_name": "Smith",
"email": "john@smith.com",
})
permit.api.users.assign_role({"user": "john@smith.com", "role": "admin", "tenant": "default"})
# create the tenant2 tenant. Creating a tenant that already exists raises
# PermitAlreadyExistsError, so this app keeps the existing tenant and continues.
try:
permit.api.tenants.create({"key": "tenant2", "name": "Second Tenant"})
except PermitAlreadyExistsError:
pass
permit.api.users.assign_role({"user": "john@smith.com", "role": "viewer", "tenant": "tenant2"})
sync_objects()
Append the / route handler, which checks the default tenant and answers 403 when the policy denies the action:
@app.route("/")
def check_permissions():
# permit.check() identifies the user by the key that sync_objects() synced to Permit.
# A user key can be any string (an email, a database id) that is unique for each user.
permitted = permit.check("john@smith.com", "retrieve", "task") # default tenant is used
if not permitted:
return Response(json.dumps({
"result": "John Smith is NOT PERMITTED to retrieve task!"
}), status=403, mimetype='application/json')
return Response(json.dumps({
"result": "John Smith is PERMITTED to retrieve task!"
}), status=200, mimetype='application/json')
Append the /tenant2 route handler, which sends the same kind of check to the tenant2 tenant:
@app.route("/tenant2")
def check_permissions_tenant2():
# the resource dictionary sends the check to the tenant2 tenant instead of the default tenant
permitted = permit.check("john@smith.com", "create", {"type": "task", "tenant": "tenant2"}) # tenant2 is used
if not permitted:
return Response(json.dumps({
"result": "John Smith is NOT PERMITTED to create task (tenant 2)!"
}), status=403, mimetype='application/json')
return Response(json.dumps({
"result": "John Smith is PERMITTED to create task (tenant 2)!"
}), status=200, mimetype='application/json')
The example needs a task resource with retrieve and create actions, and admin and viewer roles, in your environment. If those objects don't exist, the role assignments in sync_objects() fail with PermitApiError when the app starts. To create them, see Build an RBAC policy.
- Start the app:
FLASK_APP=test flask run --host=0.0.0.0
- Open the app URL that Flask prints (
http://127.0.0.1:5000by default) in a browser, then open the/tenant2path.
The / route checks whether john@smith.com can retrieve a task in the default tenant. The /tenant2 route checks whether john@smith.com can create a task in the tenant2 tenant. Each route returns HTTP 200 with a JSON result message that contains is PERMITTED, or HTTP 403 with a message that contains is NOT PERMITTED. With the admin role assigned in the default tenant, / returns:
{"result": "John Smith is PERMITTED to retrieve task!"}
If a route returns is NOT PERMITTED and you expect an allow, check that the role you assigned in the Permit dashboard grants the action on the task resource, and that the container PDP is running with an API key from the same environment.
Check ABAC permissions with the Python SDK (sync)
An attribute-based access control (ABAC) policy grants permissions based on user and resource attributes, grouped into user sets and resource sets. See ABAC policy components. ABAC checks need a container PDP.
To check an ABAC policy, pass the user and the resource as dictionaries that carry the attributes the policy compares. In this example, replace check@permit.io, action, resource, and tenant with a user key, action key, resource key, and tenant key from your environment:
permitted = permit.check(
# the user, with just-in-time attributes that user set conditions evaluate
{
"key": "check@permit.io",
"attributes": {
"location": "England",
"department": "Engineering",
},
},
# the action
"action",
# the resource, with just-in-time attributes that resource set conditions evaluate
{
"type": "resource",
"attributes": {
"hasApproval": "true",
},
"tenant": "tenant",
}
)
For more check options, see Check permissions with permit.check().
Install and initialize the Python SDK (asyncio)
Install the permit package, import the Permit class, and create a Permit client that connects to your PDP. The Permit class in the permit module uses asyncio. If your code doesn't use asyncio, use the sync Python SDK instead.
- Install the Permit.io Python SDK:
pip install permit
- Import the
Permitclass:
from permit import Permit
- Create a
Permitclient. Replace<YOUR_API_KEY>with your environment API key, and setpdpto the URL of your PDP:
# Connect the SDK to the PDP that evaluates permission checks.
permit = Permit(
# your environment API key
token="<YOUR_API_KEY>",
# in production, change this URL to the address of your PDP
pdp="http://localhost:7766",
# optional, the timeout in seconds for requests to the PDP (supported from version 2.5.0)
pdp_timeout=5,
# optional, the timeout in seconds for requests to the Permit API (supported from version 2.5.0)
api_timeout=5,
)
| Option | Description |
|---|---|
token | Your environment API key. |
pdp | The URL of the PDP that evaluates checks: http://localhost:7766 for the container PDP, or https://cloudpdp.api.permit.io for the Cloud PDP. |
pdp_timeout | Optional. Timeout in seconds for requests to the PDP. Available since SDK version 2.5.0. |
api_timeout | Optional. Timeout in seconds for requests to the Permit API. Available since SDK version 2.5.0. |
To send checks to the managed Cloud PDP instead of a container PDP, set pdp to the Cloud PDP URL:
permit = Permit(
token="<YOUR_API_KEY>",
pdp="https://cloudpdp.api.permit.io",
)
The Cloud PDP supports RBAC (role-based access control) and ReBAC (relationship-based access control) policies. ABAC (attribute-based access control) checks need a container PDP. See Cloud PDP capabilities.
Check permissions with the Python SDK (asyncio)
Call await permit.check() inside an async function, with three arguments. permit.check() returns True when the policy allows the action, and False otherwise.
| Argument | Description |
|---|---|
user | The key that identifies the user in Permit, typically the user ID from your authentication provider. To pass attributes, use a dictionary with key and attributes. |
action | The action key, for example create. |
resource | The resource type key, for example document, or a dictionary with type, tenant, and attributes. |
This example checks whether the user john@smith.com can create a document:
import asyncio
from permit import Permit
permit = Permit(token="<YOUR_API_KEY>", pdp="http://localhost:7766")
async def main():
permitted = await permit.check("john@smith.com", "create", "document")
if permitted:
print("John is permitted to create a document")
else:
print("John is NOT PERMITTED to create document!")
asyncio.run(main())
If john@smith.com exists in your environment and has a role that grants create on document, the example prints John is permitted to create a document. Otherwise, the example prints John is NOT PERMITTED to create document!. To add users and assign roles, see Sync users.
Check a permission in a specific tenant
In a multi-tenant application, pass the tenant key in the tenant field of the resource dictionary. To look up the keys of your tenants, call the list tenants API.
This example checks whether john@permit.io can read documents in the awesome_inc tenant. Like every await permit.check() call, it runs inside an async function:
permitted = await permit.check(
# the key of the user
"john@permit.io",
# the action
"read",
# the resource (all resources of type document under the awesome_inc tenant)
{ "type": "document", "tenant": "awesome_inc" }
)
permit.check() sends each check to the PDP URL you configure. A container PDP evaluates checks on your machine, using policy and data that the PDP loads from Permit. Users, roles, and attributes that you create in the dashboard or sync through the Permit API are stored in the Permit control plane.
Run a full Python example app (FastAPI)
This single-file FastAPI app runs a permission check on each request to its root URL.
- Create a directory for the project:
mkdir hello-permissions && cd hello-permissions
- Optional: create a virtual environment for the project. The following command needs
pyenvandpyenv-virtualenv.
pyenv virtualenv permissions && pyenv activate permissions
- Install the Permit.io SDK, FastAPI, and Uvicorn, the server that runs the app:
pip install permit fastapi "uvicorn[standard]"
- Create a file called
test.py:
touch test.py
-
Copy the following code into
test.py. Replace<YOUR_API_KEY>with your environment API key, andjohn@smith.comwith the key of a user in your environment.The first part of
test.pycreates the FastAPI app, the Permit client, and the user the app checks:
from permit import Permit
from fastapi import FastAPI, status, HTTPException
from fastapi.responses import JSONResponse
app = FastAPI()
# Connect the SDK to the PDP that evaluates permission checks.
permit = Permit(
# in production, change this URL to the address of your PDP
pdp="http://localhost:7766",
# your environment API key
token="<YOUR_API_KEY>",
)
# The user must exist in your environment and have a role that grants the action.
# To create users and assign roles, see the Sync users guide.
user = {
"key": "john@smith.com",
"first_name": "John",
"last_name": "Smith",
"email": "john@smith.com",
} # in a real app, you would typically decode the user id from a JWT token
Append the route handler, which runs one check per request to / and answers 403 when the policy denies the action:
@app.get("/")
async def check_permissions():
permitted = await permit.check(user["key"], "read", "document")
if not permitted:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail={
"result": f"{user.get('first_name')} {user.get('last_name')} is NOT PERMITTED to read document!"
})
return JSONResponse(status_code=status.HTTP_200_OK, content={
"result": f"{user.get('first_name')} {user.get('last_name')} is PERMITTED to read document!"
})
- Start the app. Replace
<YOUR_LOCALHOST_PORT_NUMBER>with a free port, for example8000:
uvicorn test:app --reload --port=<YOUR_LOCALHOST_PORT_NUMBER>
- Open
http://localhost:<YOUR_LOCALHOST_PORT_NUMBER>in a browser.
The app checks whether john@smith.com can read a document. If the policy allows the action, the app returns HTTP 200 with this body:
{"result": "John Smith is PERMITTED to read document!"}
Otherwise, the app returns HTTP 403 with the message John Smith is NOT PERMITTED to read document!. If the app returns is NOT PERMITTED and you expect an allow, check that john@smith.com has a role that grants read on document, and that the container PDP is running with an API key from the same environment.
Explore the Python example repository
The permit-python-example repository contains a FastAPI app that uses SQLAlchemy, PostgreSQL, and the Permit.io Python SDK. The example covers:
- RBAC (role-based access control) policy
- ABAC policy
- ReBAC (relationship-based access control) policy
- Terraform setup
Check ABAC permissions with the Python SDK (asyncio)
An attribute-based access control (ABAC) policy grants permissions based on user and resource attributes, grouped into user sets and resource sets. See ABAC policy components. ABAC checks need a container PDP.
To check an ABAC policy, pass the user and the resource as dictionaries that carry the attributes the policy compares. In this example, replace check@permit.io, action, resource, and tenant with a user key, action key, resource key, and tenant key from your environment:
permitted = await permit.check(
# the user object
{
# the user key
"key": "check@permit.io",
# just-in-time attributes on the user
"attributes": {
"location": "England",
"department": "Engineering",
},
},
# the action the user is trying to do
"action",
# the resource the user is trying to act on
{
# the type of the resource (the resource key)
"type": "resource",
# just-in-time attributes on the resource
"attributes": {
"hasApproval": "true",
},
# the tenant the resource belong to
"tenant": "tenant",
}
)
For more check options, see Check permissions with permit.check().
Install and initialize the Java SDK
Add the io.permit:permit-sdk-java dependency, create a Permit client that connects to your PDP, and sync a user.
- Add the Permit.io Java SDK to your project. The examples pin version
2.0.0. To use a later version, check the permit-java releases.
- Maven
- Gradle
For Maven projects, add the dependency to your pom.xml:
<dependency>
<groupId>io.permit</groupId>
<artifactId>permit-sdk-java</artifactId>
<version>2.0.0</version>
</dependency>
For Gradle projects, add permit-sdk-java as a dependency in your build.gradle:
dependencies {
// ...
implementation 'io.permit:permit-sdk-java:2.0.0'
}
- Create a
Permitclient. Replace[YOUR_API_KEY]with your environment API key, and pass the URL of your PDP towithPdpAddress():
import io.permit.sdk.Permit;
import io.permit.sdk.PermitConfig;
// This line initializes the SDK and connects your Java app
// to the Permit.io PDP container you've set up in the previous step.
Permit permit = new Permit(
new PermitConfig.Builder("[YOUR_API_KEY]")
// in production, you might need to change this url to fit your deployment
.withPdpAddress("http://localhost:7766")
// optionally, if you wish to get more debug messages to your log, set this to true
.withDebugMode(false)
.build()
);
| Builder method | Description |
|---|---|
PermitConfig.Builder("[YOUR_API_KEY]") | Your environment API key. |
withPdpAddress() | The URL of the PDP that evaluates checks: http://localhost:7766 for the container PDP, or https://cloudpdp.api.permit.io for the Cloud PDP. |
withDebugMode() | Set to true to log more debug messages. |
- Sync the user to Permit. After your application authenticates a user, for example by validating the user's JWT access token, create or update the user in Permit with
permit.api.users.sync(). For role-based checks, the user must exist in Permit and have a role. Replace[A_UNIQUE_USER_ID]with the user's key.
import io.permit.sdk.api.models.CreateOrUpdateResult;
import io.permit.sdk.openapi.models.UserRead;
import io.permit.sdk.enforcement.User;
import java.util.HashMap;
// optional - save the user attributes in permit so that they are
// automatically available as ABAC attributes in permit.check()
HashMap<String, Object> userAttributes = new HashMap<>();
userAttributes.put("age", Integer.valueOf(20));
userAttributes.put("subscription", "pro");
// Syncing the user to the permission system
CreateOrUpdateResult<UserRead> response = permit.api.users.sync(
(new User.Builder("[A_UNIQUE_USER_ID]"))
.withEmail("john@smith.com") // optional
.withFirstName("John") // optional
.withLastName("Smith") // optional
.withAttributes(userAttributes) // optional, used for ABAC permission checks
.build()
);
// the response object contains the user, and whether or not the user was created or updated
UserRead user = response.getResult();
boolean wasCreated = response.wasCreated();
// assign the `admin` role to the user in the `default` tenant
permit.api.users.assignRole(user.key, "admin", "default");
permit.api.users.sync() returns a CreateOrUpdateResult<UserRead>. getResult() returns the user, and wasCreated() returns true if Permit created the user. permit.api.users.assignRole() takes the user key, the role key, and the tenant key.
Check permissions with the Java SDK
Call permit.check() with three arguments. permit.check() returns true when the policy allows the action, and false otherwise.
| Argument | Description |
|---|---|
user | A User. Create one from the user key with User.fromString("<user key>"). The user key is typically the user ID from your authentication provider. |
action | The action key, for example "create". |
resource | A Resource. Build one with new Resource.Builder("<resource key>"), and set the tenant key with withTenant(). |
This example checks whether a user can create a document in the default tenant. Replace [A_USER_ID] with the key of the user you synced:
import io.permit.sdk.enforcement.Resource;
import io.permit.sdk.enforcement.User;
// to run a permission check, use permit.check()
boolean permitted = permit.check(
// the user you check permission on
User.fromString("[A_USER_ID]"),
// the action (key) the user want to perform
"create",
// the resource the user is trying to access
new Resource.Builder("document").withTenant("default").build()
);
if (permitted) {
System.out.println("User is PERMITTED to create a document");
} else {
System.out.println("User is NOT PERMITTED to create a document");
}
If the user has a role in the default tenant that grants create on document, the example prints User is PERMITTED to create a document. Otherwise, the example prints User is NOT PERMITTED to create a document.
In a multi-tenant application, pass the tenant key to withTenant() on the resource. To look up the keys of your tenants, call the list tenants API.
permit.check() sends each check to the PDP URL you configure. A container PDP evaluates checks on your machine, using policy and data that the PDP loads from Permit. Users, roles, and attributes that you sync with permit.api.users.sync() are stored in the Permit control plane.
Check ABAC permissions with the Java SDK
An attribute-based access control (ABAC) policy grants permissions based on user and resource attributes, grouped into user sets and resource sets. See ABAC policy components. ABAC checks need a container PDP.
To check an ABAC policy, pass a User and a Resource that carry attributes, set with withAttributes(). Replace action and resource with an action key and a resource key from your environment:
// Creating a UserSet
HashMap<String, Object> userAttributes = new HashMap<>();
userAttributes.put("isAllowed", "True");
User userWithAttributes = (new User.Builder("John"))
.withEmail("John@smith.com")
.withFirstName("John")
.withLastName("Smith")
.withAttributes(userAttributes)
.build();
// Creating a ResourceSet
HashMap<String, Object> resourceAttributes = new HashMap<>();
resourceAttributes.put("hasApproval", "true");
Resource resourceWithAttributes = new Resource.Builder("resource").withTenant("default").withAttributes(resourceAttributes).build();
// Checking the permissions
permit.check(userWithAttributes, "action", resourceWithAttributes);
For more check options, see Check permissions with permit.check().
Run a full Java example app (Spring Boot)
This single-file Spring Boot app syncs a user, assigns the user the admin role in the default tenant, and runs a permission check on each request to its root URL.
- Create a Spring Boot web project that includes the Permit.io Java SDK dependency.
- Save the following code as
DemoApplication.javain thecom.example.myprojectpackage. - Replace
[YOUR_API_KEY]with your environment API key, and both[A_USER_ID]placeholders with the same user key.
package com.example.myproject;
import io.permit.sdk.Permit;
import io.permit.sdk.PermitConfig;
import io.permit.sdk.api.PermitApiError;
import io.permit.sdk.api.PermitContextError;
import io.permit.sdk.enforcement.Resource;
import io.permit.sdk.enforcement.User;
import io.permit.sdk.openapi.models.UserCreate;
import io.permit.sdk.openapi.models.UserRead;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
@RestController
@SpringBootApplication
public class DemoApplication {
final Permit permit;
final UserRead user;
public DemoApplication() {
// init the permit SDK
this.permit = new Permit(
new PermitConfig.Builder("[YOUR_API_KEY]")
.withPdpAddress("http://localhost:7766")
.withDebugMode(true)
.build()
);
try {
// typically you would sync a user to the permission system
// and assign an initial role when the user signs up to the system
this.user = permit.api.users.sync(
// the user "key" is any id that identifies the user uniquely
// but is typically taken straight from the user JWT `sub` claim
new UserCreate("[A_USER_ID]")
.withEmail("user@example.com")
.withFirstName("Joe")
.withLastName("Doe")
).getResult();
// assign the `admin` role to the user in the `default` tenant
permit.api.users.assignRole(user.key, "admin", "default");
} catch (IOException | PermitApiError | PermitContextError e) {
throw new RuntimeException(e);
}
}
@GetMapping("/")
ResponseEntity<String> home() throws IOException, PermitApiError, PermitContextError {
// is `user` allowed to do `action` on `resource`?
User user = User.fromString("[A_USER_ID]"); // pass the user key to init a user from string
String action = "create";
Resource resource = new Resource.Builder("document")
.withTenant("default")
.build();
// to run a permission check, use permit.check()
boolean permitted = permit.check(user, action, resource);
if (permitted) {
return ResponseEntity.status(HttpStatus.OK).body(
"Joe Doe is PERMITTED to create document!"
);
} else {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(
"Joe Doe is NOT PERMITTED to create document!"
);
}
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
- Start the app, for example with
./mvnw spring-boot:runor./gradlew bootRun. - Open the app's root URL (
http://localhost:8080by default in Spring Boot) in a browser.
If the admin role grants create on document, the page returns HTTP 200 with Joe Doe is PERMITTED to create document!. Otherwise, the page returns HTTP 403 with Joe Doe is NOT PERMITTED to create document!.
Explore the Java example repository
The permit-java-example repository contains a blog application that uses the Permit.io Java SDK. The example covers:
- RBAC (role-based access control) policy
- ABAC policy
- ReBAC (relationship-based access control) policy
- Terraform setup
Install and initialize the Go SDK
Install the permit-golang module, import the permit and config packages, and create a Permit client that connects to your PDP.
- Install the Permit.io Go SDK:
go get github.com/permitio/permit-golang
- Import the
permitpackage:
import "github.com/permitio/permit-golang/pkg/permit"
- Create a Permit client from a config that
config.NewConfigBuilder()builds. Replace<YOUR_API_TOKEN>with your environment API key, and set the PDP URL withWithPdpUrl().
package main
import "github.com/permitio/permit-golang/pkg/permit"
import "github.com/permitio/permit-golang/pkg/config"
func main() {
permitConfig := config.NewConfigBuilder("<YOUR_API_TOKEN>").
WithPdpUrl("http://localhost:7766").
Build()
permitClient := permit.NewPermit(permitConfig)
_ = permitClient
}
Check permissions with the Go SDK
Call Check() on the Permit client with three arguments. Check() returns true when the policy allows the action, false otherwise, and an error if the check fails.
| Argument | Description |
|---|---|
user | An enforcement.User. Build one with enforcement.UserBuilder("<user key>").Build(). The user key is typically the user ID from your authentication provider. |
action | The action key, for example "create". |
resource | An enforcement.Resource. Build one with enforcement.ResourceBuilder("<resource key>").Build(). |
This example checks whether a user can create a document:
package main
import "github.com/permitio/permit-golang/pkg/permit"
import "github.com/permitio/permit-golang/pkg/config"
import "github.com/permitio/permit-golang/pkg/enforcement"
func main() {
PermitConfig := config.NewConfigBuilder("<YOUR_API_TOKEN>").Build()
Permit := permit.NewPermit(PermitConfig)
user := enforcement.UserBuilder("john@doe.com").Build()
resource := enforcement.ResourceBuilder("document").Build()
permitted, err := Permit.Check(user, "create", resource)
if err != nil {
return
}
if permitted {
// Let the user read the resource
} else {
// Deny access
}
}
permitted is true if john@doe.com exists in your environment and has a role that grants create on document. To add users and assign roles, see Sync users.
Check a permission in a specific tenant
In a multi-tenant application, set the tenant key on the resource with WithTenant(). To look up the keys of your tenants, call the list tenants API.
resource := enforcement.ResourceBuilder("document").WithTenant("tenant").Build()
permitted, err := permitClient.Check(user, "create", resource)
Check() sends each check to the PDP URL you configure. A container PDP evaluates checks on your machine, using policy and data that the PDP loads from Permit. Users, roles, and attributes that you create in the dashboard or sync through the Permit API are stored in the Permit control plane.
Check ABAC permissions with the Go SDK
An attribute-based access control (ABAC) policy grants permissions based on user and resource attributes, grouped into user sets and resource sets. See ABAC policy components. ABAC checks need a container PDP.
To check an ABAC policy, set just-in-time attributes on the user or the resource with WithAttributes(). In this example, replace userKey and resourceKey with a user key and a resource key from your environment:
userCheck := enforcement.UserBuilder("userKey").Build()
attributes := map[string]interface{}{
"hasApproval": "true",
}
resourceCheck := enforcement.ResourceBuilder("resourceKey").WithTenant("default").WithAttributes(attributes).Build()
allowed, _ := permitClient.Check(userCheck, "create", resourceCheck)
For more check options, see Check permissions with permit.check().
Run a full Go example app
This single-file Go app runs a permission check on each request to http://localhost:4000. The app logs with go.uber.org/zap.
- In a Go module, add the dependencies with
go get github.com/permitio/permit-golang go.uber.org/zap. - Save the following code as
main.go. - Replace
<YOUR_API_KEY>with your environment API key, anduser_idwith the key of a user in your environment.
package main
import (
"fmt"
"go.uber.org/zap"
"net/http"
"github.com/permitio/permit-golang/pkg/config"
"github.com/permitio/permit-golang/pkg/enforcement"
"github.com/permitio/permit-golang/pkg/permit"
)
const (
port = 4000
)
func main() {
// Connect the SDK to the PDP that evaluates permission checks.
permitClient := permit.NewPermit(
// Building new config for Permit client
config.NewConfigBuilder(
// your api key
"<YOUR_API_KEY>").
// Set the PDP URL
WithLogger(zap.NewExample()).
WithPdpUrl("http://localhost:7766").
Build(),
)
// You can open http://localhost:4000 to invoke this http
// endpoint, and see the outcome of the permission check.
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// The user must exist in your environment and have a role that grants the action.
// Create users with permitClient.SyncUser(ctx, models.UserCreate{Key: "user_id"}).
// A user key can be any string (an email, a database id) that is unique for each user.
user := enforcement.UserBuilder("user_id").
WithFirstName("john").
WithLastName("doe").
WithEmail("john@doe.com").
Build()
// The document resource and its read action must exist in your policy.
resource := enforcement.ResourceBuilder("document").Build()
permitted, err := permitClient.Check(user, "read", resource)
if err != nil {
fmt.Println(err)
return
}
if permitted {
w.WriteHeader(http.StatusOK)
_, err = w.Write([]byte(user.FirstName + " " + user.LastName + " is PERMITTED to read document!"))
} else {
w.WriteHeader(http.StatusForbidden)
_, err = w.Write([]byte(fmt.Sprintf(user.FirstName + " " + user.LastName + " is NOT PERMITTED to read document!")))
}
})
fmt.Printf("Listening on http://localhost:%d", port)
http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}
- Run
go run main.go. The terminal printsListening on http://localhost:4000. - Open
http://localhost:4000in a browser.
If the user's role grants read on document, the page returns HTTP 200 with john doe is PERMITTED to read document!. Otherwise, the page returns HTTP 403 with john doe is NOT PERMITTED to read document!.
Explore the Go example repository
The permit-go-example repository contains a Go app and a Terraform configuration that creates the app's policy in Permit.
Install and initialize the Ruby SDK
Install the permit-sdk gem, load the SDK, and create a Permit client that connects to your PDP.
-
Install the Permit.io Ruby SDK:
gem install permit-sdk -
Load the SDK in your code:
require 'permit' -
Create a
Permitclient withPermit.new(token, pdp_url). Replace<YOUR_API_KEY>with your environment API key. The second argument is the PDP URL, and defaults tohttp://localhost:7766, the address of a container PDP on your machine:require 'permit'permit = Permit.new("<YOUR_API_KEY>", "http://localhost:7766") # the PDP url is optional
To send checks to the managed Cloud PDP instead of a container PDP, pass the Cloud PDP URL:
require 'permit'
permit = Permit.new("<YOUR_API_KEY>", "https://cloudpdp.api.permit.io")
The Cloud PDP supports RBAC (role-based access control) and ReBAC (relationship-based access control) policies. ABAC (attribute-based access control) checks need a container PDP. See Cloud PDP capabilities.
Check permissions with the Ruby SDK
Call permit.check() with three arguments. permit.check() returns true when the policy allows the action, and false otherwise.
| Argument | Description |
|---|---|
user | The user key as a string, or a hash with key and optional first_name, last_name, email, and attributes. The user key is typically the user ID from your authentication provider. |
action | The action key as a string, for example "create". |
resource | The resource type key as a string, for example "document", or a hash with type, tenant, and attributes. A string resource uses the default tenant. |
The following examples check whether the user john@permit.io can create a document. This example passes the user and the resource as strings:
require 'permit'
permit = Permit.new("<YOUR_API_KEY>", "http://localhost:7766") # the PDP url is optional
permitted = permit.check("john@permit.io", "create" , "document")
if permitted
puts "john@permit.io is permitted to create a document"
else
puts "john@permit.io is not permitted to create a document"
end
This example passes the user and the resource as hashes:
require 'permit'
permit = Permit.new("<YOUR_API_KEY>", "http://localhost:7766") # the PDP url is optional
user_hash = {"key": "john@permit.io", "first_name": "john", "last_name": "doe", "email": "john@permit.io"}
resource_hash = {"type": "document", "tenant": "default"}
permitted = permit.check(user_hash, "create" , resource_hash)
if permitted
puts "john@permit.io is permitted to create a document"
else
puts "john@permit.io is not permitted to create a document"
end
If john@permit.io exists in your environment and has a role that grants create on document, both examples print john@permit.io is permitted to create a document. Otherwise, the examples print john@permit.io is not permitted to create a document. To add users and assign roles, see Sync users.
When the PDP answers with a status code other than 200, for example because the PDP URL is wrong or the API key belongs to another environment, permit.check() raises a RuntimeError that names the status code. Handle the exception in request code, or the request fails with a server error instead of a deny.
Check a permission in a specific tenant
In a multi-tenant application, pass the tenant key in the tenant field of the resource hash, as resource_hash does in the hash example. To look up the keys of your tenants, call the list tenants API. In this example, replace user, action, resource, and tenant with a user key, action key, resource key, and tenant key from your environment:
if permit.check("user", "action", { "type": "resource", "tenant": "tenant" })
# the policy allows the action in that tenant
end
permit.check() sends each check to the PDP URL you configure. A container PDP evaluates checks on your machine, using policy and data that the PDP loads from Permit. Users, roles, and attributes that you create in the dashboard or sync through the Permit API are stored in the Permit control plane.
Run a full Ruby example app
This single-file WEBrick app listens on port 4000 and runs a permission check on each request. The app uses the default PDP URL, http://localhost:7766. The app loads the json library, because the response bodies call to_json on a hash.
-
Install the
permit-sdkandwebrickgems:gem install permit-sdk webrick -
Save the following code as
app.rb. Replace<YOUR_API_KEY>with your environment API key, andjohn@permit.iowith the key of a user in your environment:require 'json'require 'webrick'require 'permit'permit = Permit.new("<YOUR_API_KEY>")server = WEBrick::HTTPServer.new(Port: 4000)server.mount_proc '/' do |_, res|res['Content-Type'] = 'application/json'permitted = permit.check("john@permit.io", "read", "document")if permittedres.status = 200res.body = { result: "john@permit.io is PERMITTED to read document!" }.to_jsonnextendres.status = 403res.body = { result: "john@permit.io is NOT PERMITTED to read document" }.to_jsonendtrap 'INT' do server.shutdown endserver.start -
Run the app:
ruby app.rb -
Open
http://localhost:4000in a browser.
If the user's role grants read on document, the page returns HTTP 200 with this body:
{"result":"john@permit.io is PERMITTED to read document!"}
Otherwise, the page returns HTTP 403 with john@permit.io is NOT PERMITTED to read document. If the page returns is NOT PERMITTED and you expect an allow, check that the user has a role that grants read on document, and that the container PDP runs with an API key from the same environment.
Check ABAC permissions with the Ruby SDK
An attribute-based access control (ABAC) policy grants permissions based on user and resource attributes, grouped into user sets and resource sets. See ABAC policy components. ABAC checks need a container PDP.
To check an ABAC policy, pass a resource hash with an attributes hash. In this example, user is a user key or user hash, and close and resource stand for an action key and a resource key from your environment:
if permit.check(user, 'close', { "type": "resource", "attributes": {"hasApproval": "true"}, "tenant": "default" })
# the policy allows the action on a resource that has the attribute values
end
For more check options, see Check permissions with permit.check().
Install and initialize the .NET SDK
Create a .NET console project, install the Permit NuGet package, and create a Permit client that connects to your PDP. The full example app on this page uses HttpListener to serve HTTP requests.
- Create a directory with an empty .NET console project:
mkdir hello-permissions-dotnet && cd hello-permissions-dotnet && dotnet new console
-
Install the Permit.io .NET SDK:
dotnet add package Permit -
Import the SDK namespaces into your code:
using PermitSDK;using PermitSDK.Models; -
Create a
Permitclient. Replace[YOUR_API_KEY]with your environment API key, and pass the URL of your PDP as the second argument:// Connect the SDK to the PDP that evaluates permission checks.Permit permit = new Permit("[YOUR_API_KEY]","http://localhost:7766");To set more options, pass them as named arguments:
// you can also set more config optionsPermit permitClient = new Permit(// the API key to usetoken: "[YOUR_API_KEY]",// the URL of the Permit.io PDP containerpdp: "http://localhost:7766",// the tenant to use if the tenant is not provideddefaultTenant: "default",// whether to use the default tenant if the tenant is not provideduseDefaultTenantIfEmpty: true,// should run in debug modedebugMode: true,// set the log levellevel: "info",// set the log labellabel: "Permitio-sdk",// should log as JSONlogAsJson: 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]");
The Permit constructor accepts these parameters. Parameter names are case-sensitive.
| Parameter | Default | Description |
|---|---|---|
token | Required | Your environment API key. |
pdp | http://localhost:7766 | The URL of the PDP: http://localhost:7766 for the container PDP, or https://cloudpdp.api.permit.io for the Cloud PDP. |
defaultTenant | default | The tenant key to use when a check doesn't pass a tenant. |
useDefaultTenantIfEmpty | true | Whether to use defaultTenant when a check doesn't pass a tenant. |
debugMode | false | Whether to log debug messages. |
apiUrl | https://api.permit.io | The URL of the Permit API. |
level, label, logAsJson | info, permitio-sdk, false | Log level, log label, and JSON log output. |
projectId, envId | None | The project ID and environment ID. Set both to skip the API call that looks up the scope of the API key. |
raiseErrors | false | Whether a failed check request throws an error instead of returning false. |
Check permissions with the .NET SDK
Call await permit.Check() with three arguments: the user key, the action key, and the resource key. permit.Check() returns true when the policy allows the action, and false otherwise.:
UserKey user = new UserKey("userId", "John", "Smith", "john@permit.io");
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");
}
If the user has a role that grants create on document, the example writes User is PERMITTED to create a document. Otherwise, the example writes User is NOT PERMITTED to create a document. Use the user ID from your authentication provider as the user key. To add users and assign roles, see Sync users.
In a multi-tenant application, pass a ResourceInput with a tenant argument as the resource, as in the ABAC example below. To look up the keys of your tenants, call the list tenants API.
permit.Check() sends each check to the PDP URL you configure. A container PDP evaluates checks on your machine, using policy and data that the PDP loads from Permit. Users, roles, and attributes that you create in the dashboard or sync through the Permit API are stored in the Permit control plane.
Check ABAC permissions with the .NET SDK
An attribute-based access control (ABAC) policy grants permissions based on user and resource attributes, grouped into user sets and resource sets. See ABAC policy components. ABAC checks need a container PDP.
To check an ABAC policy, pass a UserKey and a ResourceInput with attributes. In this example, replace userId, resource, tenant, and action with a user key, resource key, tenant key, and action key from your environment:
UserKey user = new UserKey("userId", "John", "Smith", "john@smith.com");
var resourceInput = new ResourceInput(
"resource",
tenant: "tenant",
attributes: new Dictionary<string, dynamic>
{
{"hasApproval", "True"}
}
);
bool permitted = await permit.Check(user, "action", resourceInput);
For more check options, see Check permissions with permit.check().
Run a full .NET example app
This single-file .NET console app listens on http://localhost:4000/ and runs a permission check on each request.
- Replace the contents of
Program.csin the project you created with the following code. - Replace
[YOUR_API_KEY]with your environment API key, anduserIdwith the key of a user in your environment.
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
);
// permit.Check() identifies the user by the key. The user must exist in your
// environment: create users with permit.Api.SyncUser(new UserCreate { ... }).
// A user key can be any string (an email, a database id) that is unique for each user.
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();
}
}
}
- Run the app:
dotnet run
The terminal prints Listening for connections on http://localhost:4000/.
- Open
http://localhost:4000in a browser.
The app checks whether the user can create a task. If the policy allows the action, the page returns HTTP 200 with User JohnSmith is Permitted to create task. Otherwise, the page returns HTTP 403 with User JohnSmith is NOT Permitted to create task.
4. Confirm the check in the audit log
Open the Audit Log screen in the Permit dashboard. Each permit.check() call from your application appears as an entry with the user, the action, the resource, and the decision.
If the check doesn't appear in the audit log, see Troubleshoot audit logs.
Next steps
- Sync users and assign roles so
permit.check()can evaluate your real users. - Check permissions with permit.check() with tenants, attributes, and relationships.
- Run the PDP and choose between the Cloud PDP and a container PDP.
- Deploy the PDP to production.
- Compare SDK features by language.