Code Examples
Integration examples for calling the AuthzX evaluate endpoint from your application.
cURL
curl -X POST https://api.authzx.com/policy-srv/v1/evaluate \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"subject": { "id": "user-123", "type": "user" },
"resource": { "type": "document", "id": "doc-456" },
"action": "read"
}'
Go
package authzx
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
const baseURL = "https://api.authzx.com"
type Client struct {
apiKey string
httpClient *http.Client
}
func NewClient(apiKey string) *Client {
return &Client{
apiKey: apiKey,
httpClient: &http.Client{},
}
}
type Subject struct {
ID string `json:"id"`
Type string `json:"type"`
Attributes map[string]interface{} `json:"attributes,omitempty"`
Roles []string `json:"roles,omitempty"`
}
type Resource struct {
Type string `json:"type"`
ID string `json:"id"`
Attributes map[string]interface{} `json:"attributes,omitempty"`
}
type EvaluateRequest struct {
Subject Subject `json:"subject"`
Resource Resource `json:"resource"`
Action string `json:"action"`
Context map[string]interface{} `json:"context,omitempty"`
}
type EvaluateResponse struct {
Allowed bool `json:"allowed"`
Reason string `json:"reason"`
PolicyID string `json:"policy_id,omitempty"`
AccessPath string `json:"access_path,omitempty"`
}
func (c *Client) Evaluate(req *EvaluateRequest) (*EvaluateResponse, error) {
body, err := json.Marshal(req)
if err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
httpReq, err := http.NewRequest("POST", baseURL+"/policy-srv/v1/evaluate", bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("create request: %w", err)
}
httpReq.Header.Set("Authorization", "Bearer "+c.apiKey)
httpReq.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("send request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status: %d", resp.StatusCode)
}
var result EvaluateResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, fmt.Errorf("decode response: %w", err)
}
return &result, nil
}
// Usage:
//
// client := authzx.NewClient("your-api-key")
// result, err := client.Evaluate(&authzx.EvaluateRequest{
// Subject: authzx.Subject{ID: "user-123", Type: "user"},
// Resource: authzx.Resource{Type: "document", ID: "doc-456"},
// Action: "read",
// })
// if result.Allowed {
// // proceed
// }
Python
import requests
class AuthzXClient:
def __init__(self, api_key: str, base_url: str = "https://api.authzx.com"):
self.api_key = api_key
self.base_url = base_url
def evaluate(
self,
subject_id: str,
subject_type: str,
resource_type: str,
resource_id: str,
action: str,
subject_attributes: dict = None,
subject_roles: list = None,
resource_attributes: dict = None,
context: dict = None,
) -> dict:
payload = {
"subject": {
"id": subject_id,
"type": subject_type,
},
"resource": {
"type": resource_type,
"id": resource_id,
},
"action": action,
}
if subject_attributes:
payload["subject"]["attributes"] = subject_attributes
if subject_roles:
payload["subject"]["roles"] = subject_roles
if resource_attributes:
payload["resource"]["attributes"] = resource_attributes
if context:
payload["context"] = context
response = requests.post(
f"{self.base_url}/policy-srv/v1/evaluate",
json=payload,
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
},
)
response.raise_for_status()
return response.json()
# Usage:
client = AuthzXClient("your-api-key")
result = client.evaluate(
subject_id="user-123",
subject_type="user",
resource_type="document",
resource_id="doc-456",
action="read",
)
if result["allowed"]:
print(f"Access granted via {result['access_path']}")
else:
print(f"Access denied: {result['reason']}")
Node.js / TypeScript
interface EvaluateRequest {
subject: {
id: string;
type: string;
attributes?: Record<string, any>;
roles?: string[];
};
resource: {
type: string;
id: string;
attributes?: Record<string, any>;
};
action: string;
context?: Record<string, any>;
}
interface EvaluateResponse {
allowed: boolean;
reason: string;
policy_id?: string;
access_path?: string;
}
class AuthzXClient {
private apiKey: string;
private baseUrl: string;
constructor(apiKey: string, baseUrl = "https://api.authzx.com") {
this.apiKey = apiKey;
this.baseUrl = baseUrl;
}
async evaluate(req: EvaluateRequest): Promise<EvaluateResponse> {
const response = await fetch(
`${this.baseUrl}/policy-srv/v1/evaluate`,
{
method: "POST",
headers: {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify(req),
}
);
if (!response.ok) {
throw new Error(`AuthzX error: ${response.status}`);
}
return response.json();
}
}
// Usage:
const client = new AuthzXClient("your-api-key");
const result = await client.evaluate({
subject: { id: "user-123", type: "user" },
resource: { type: "document", id: "doc-456" },
action: "read",
});
if (result.allowed) {
console.log(`Access granted via ${result.access_path}`);
} else {
console.log(`Access denied: ${result.reason}`);
}
Java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class AuthzXClient {
private final String apiKey;
private final String baseUrl;
private final HttpClient httpClient;
public AuthzXClient(String apiKey) {
this(apiKey, "https://api.authzx.com");
}
public AuthzXClient(String apiKey, String baseUrl) {
this.apiKey = apiKey;
this.baseUrl = baseUrl;
this.httpClient = HttpClient.newHttpClient();
}
public String evaluate(String subjectId, String subjectType,
String resourceType, String resourceId,
String action) throws Exception {
String json = String.format("""
{
"subject": { "id": "%s", "type": "%s" },
"resource": { "type": "%s", "id": "%s" },
"action": "%s"
}
""", subjectId, subjectType, resourceType, resourceId, action);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/policy-srv/v1/evaluate"))
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> response = httpClient.send(
request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new RuntimeException("AuthzX error: " + response.statusCode());
}
return response.body();
}
}
// Usage:
//
// AuthzXClient client = new AuthzXClient("your-api-key");
// String result = client.evaluate(
// "user-123", "user", "document", "doc-456", "read");
Express.js Middleware
A common pattern is to use AuthzX as middleware in your Express.js API:
import { AuthzXClient } from "./authzx"; // from the Node.js example above
const authzx = new AuthzXClient(process.env.AUTHZX_API_KEY!);
function authorize(resourceType: string, action: string) {
return async (req, res, next) => {
const result = await authzx.evaluate({
subject: { id: req.user.id, type: "user" },
resource: { type: resourceType, id: req.params.id },
action,
});
if (!result.allowed) {
return res.status(403).json({ error: "Forbidden", reason: result.reason });
}
next();
};
}
// Usage in routes:
app.get("/documents/:id", authorize("document", "read"), (req, res) => {
// User is authorized — serve the document
});
app.put("/documents/:id", authorize("document", "write"), (req, res) => {
// User is authorized — update the document
});
app.delete("/documents/:id", authorize("document", "delete"), (req, res) => {
// User is authorized — delete the document
});
Go Middleware (Gin)
func Authorize(client *authzx.Client, resourceType, action string) gin.HandlerFunc {
return func(c *gin.Context) {
userID := c.GetString("user_id") // from your auth middleware
result, err := client.Evaluate(&authzx.EvaluateRequest{
Subject: authzx.Subject{ID: userID, Type: "user"},
Resource: authzx.Resource{Type: resourceType, ID: c.Param("id")},
Action: action,
})
if err != nil {
c.AbortWithStatusJSON(500, gin.H{"error": "Authorization check failed"})
return
}
if !result.Allowed {
c.AbortWithStatusJSON(403, gin.H{"error": "Forbidden", "reason": result.Reason})
return
}
c.Next()
}
}
// Usage:
// r.GET("/documents/:id", Authorize(client, "document", "read"), getDocument)
// r.PUT("/documents/:id", Authorize(client, "document", "write"), updateDocument)