Skip to main content
Version: 2.0.0

Java 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 Java code

Initialise the Javs SDK and check for permissions.

  1. Install the Permit.io SDK with:

For Maven projects, use:

<dependency>
<groupId>io.permit</groupId>
<artifactId>permit-sdk-java</artifactId>
<version>2.0.0</version>
</dependency>
  1. Create a new instance of the SDK.
    You can find instructions on getting a secret API key in the previous section.
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()
);
  1. Sync the user to the permissions system

    When the user first logins, and after you check if he authenticated successfully (i.e: by checking the JWT access token) - you need to declare the user in the permission system so you can run permit.check() on that user.

import io.permit.sdk.api.models.CreateOrUpdateResult;
import io.permit.sdk.openapi.models.UserRead;
import io.permit.sdk.enforcement.User;

// 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()
);

// assign the `admin` role to the user in the `default` tenant
permit.api.users.assignRole(user.key, "admin", "default");

// the response object contains the user, and whether or not the user was create or updated
UserRead user = response.getResult();
boolean wasCreated = response.wasCreated();

Check for permissions using the SDK

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");
}
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.

// 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
Resource resourceWithAttributes = new Resource.Builder("resource").withTenant(tenant.key).withAttributes(resourceAttributes).build()

// Checking the permissions
permit.check(userWithAttributes, "action", resourceWithAttributes);
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 Spring Boot app made up of a single file, with the SDK installed.

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")
.withApiUrl("https://api.stg.permit.io")
.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);
}
}

Full app example

Example application using Spring framework and the Permit.io SDK. https://github.com/permitio/permit-java-example

Features

  • RBAC policy
  • ABAC policy
  • ReBAC policy
  • Terraform setup