Integrate
Enforce

Enforce Authorization in your Application

Install the client SDK

Follow the installation instruction (opens in a new tab) to install the Oso Cloud client SDK for your language.

Add enforcement

Most authorization comes down to "can this user perform this action on this resource?" We call authorization checks like these enforcement.

The Oso API for enforcement is authorize(user, action, resource) -- authorize whether this user can perform this action on this resource, and return true/false. This is what you call in your application to do enforcement.

The user and resource arguments are represented using a generic object with a type and an ID. This way, Oso can reference these objects against the data that you've stored.

For example, suppose we have a controller method to read a repository. We'll typically build the user object from authentication information, and extract the repository ID from the request path parameters.

And finally, we can check the user is authorized to perform the read action on the repository.


// get global oso instance
import { oso } from "../app";
router.get("/repos/:repoId", async (req, res) => {
const user = { type: "User", id: req.user.id };
const repo = { type: "Repository", id: req.params.repoId };
if (!(await oso.authorize(user, "read", repo))) {
return res.status(403).send("Unauthorized");
}
// fetch repository from database, etc.
});

Policy Tests & Enforcement

The authorize API is intentionally designed to mirror the allow API for policy tests.

When writing a policy test, the test assertions are exactly what you would be passing in via the authorize API.


test "repo members can read their repositories" {
setup {
has_role(User{"alice"}, "member", Repository{"repo-1"});
}
assert allow(User{"alice"}, "read", Repository{"repo-1"});
}


@app.route("/repos/<str:repoId>")
def get_repo(repoId):
user = { "type": "User", "id": "alice"}
repo = { "type": "Repository", "id": "repo-1" }
if not oso.authorize(user, "read", repo):
raise PermissionDenied