### REST API Testing Examples (Bash) Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt These bash commands demonstrate how to test REST API endpoints protected by authorization. They cover starting OPA with Docker, running the Spring Boot application, and making various curl requests to test access for different users and actions, including reading documents, creating, updating, deleting, sharing, and listing. ```bash # Start OPA with Docker cd authz-sample-app/docker docker-compose up -d # Run the sample application cd .. mvn spring-boot:run -Dspring.profiles.active=opa # Test as alice (admin) - should succeed curl -u alice:password \ http://localhost:8080/api/documents/doc-001 # Expected response: # {"id":"doc-001","title":"Public Document","content":"This is a public document.","ownerId":"alice","department":"Engineering","confidential":false} # Test reading confidential document as alice (owner) - should succeed curl -u alice:password \ http://localhost:8080/api/documents/doc-002 # Test reading confidential document as bob (not owner) - should be denied curl -u bob:password \ http://localhost:8080/api/documents/doc-002 # Expected: 403 Forbidden - Access denied # Create a new document as authenticated user curl -u alice:password \ -X POST \ -H "Content-Type: application/json" \ -d '{"title":"New Document","content":"Document content","department":"Engineering","confidential":false}' \ http://localhost:8080/api/documents # Update a document (requires write permission) curl -u alice:password \ -X PUT \ -H "Content-Type: application/json" \ -d '{"title":"Updated Title","content":"Updated content","department":"Engineering","confidential":false}' \ http://localhost:8080/api/documents/doc-001 # Delete a document (requires delete permission) curl -u alice:password \ -X DELETE \ http://localhost:8080/api/documents/doc-001 # Share a document (requires share permission) curl -u alice:password \ -X POST \ "http://localhost:8080/api/documents/doc-001/share?userId=bob" # List all documents curl -u alice:password \ http://localhost:8080/api/documents ``` -------------------------------- ### Build and Test with Maven (Bash) Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/CONTRIBUTING.md Provides commands for cleaning, installing, and verifying the project using Maven. It includes running unit tests and integration tests which require Docker. ```bash # Clone your fork git clone https://github.com/YOUR_USERNAME/authz-spring-boot-starter.git cd authz-spring-boot-starter # Build mvn clean install # Run tests mvn test # Run with integration tests (requires Docker) docker run -d -p 8181:8181 openpolicyagent/opa:latest run --server mvn verify -Pintegration-tests ``` -------------------------------- ### Commit Message Examples (Bash) Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/CONTRIBUTING.md Illustrates good practices for writing commit messages in Git, emphasizing the use of present tense and imperative mood, and limiting the subject line length. ```bash # Good examples: # Add support for custom timeout configuration # Fix cache invalidation for batch requests # Update documentation for AVP connector ``` -------------------------------- ### Building the Project from Source Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Details the steps required to build the authz-spring-boot-starter project from its source code. This includes cloning the repository, navigating to the project directory, and executing Maven commands for cleaning, installing, and running tests. ```bash # Clone the repository git clone https://github.com/big-acl/authz-spring-boot-starter.git cd authz-spring-boot-starter # Build mvn clean install # Run tests mvn test ``` -------------------------------- ### Running Sample Application with OPA using Docker Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Provides instructions to run the sample application integrated with Open Policy Agent (OPA) using Docker. This involves starting OPA via Docker Compose and then running the Spring Boot application with the 'opa' profile. ```bash # Start OPA with Docker cd authz-sample-app/docker docker-compose up -d # Run the application cd .. mvn spring-boot:run -Dspring.profiles.active=opa ``` -------------------------------- ### Add Dependencies for AuthZ Spring Boot Starter Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Includes the main starter dependency and an example PDP connector for Open Policy Agent (OPA). You need to choose a PDP connector based on your chosen authorization backend. ```xml com.bigacl authz-spring-boot-starter 0.1.0 com.bigacl authz-pdp-opa 0.1.0 ``` -------------------------------- ### Testing Sample Application API Endpoints Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Illustrates how to test the sample application's API endpoints using `curl`. Examples include accessing documents as different users (admin and regular user) and creating a new document, demonstrating authorization checks. ```bash # As alice (admin) - should succeed curl -u alice:password http://localhost:8080/api/documents/doc-001 # As bob (user) - may be denied for confidential documents curl -u bob:password http://localhost:8080/api/documents/doc-002 # Create a document curl -u alice:password -X POST \ -H "Content-Type: application/json" \ -d '{"title":"New Doc","content":"Content"}' \ http://localhost:8080/api/documents ``` -------------------------------- ### Custom Context Provider Implementation (Java) Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md An example implementation of `AuthzContextProvider` to dynamically add contextual information to authorization requests, such as client IP and user agent from the `HttpServletRequest`. ```java @Component public class CustomContextProvider implements AuthzContextProvider { @Override public AuthzContext provide() { HttpServletRequest request = getCurrentRequest(); return AuthzContext.builder() .value("client_ip", request.getRemoteAddr()) .value("user_agent", request.getHeader("User-Agent")) .value("tenant_id", request.getHeader("X-Tenant-ID")) .value("timestamp", Instant.now().toString()) .build(); } } ``` -------------------------------- ### Sample OPA Policy in Rego Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md An example policy written in Rego for Open Policy Agent (OPA). It defines rules for granting or denying access based on the input, including roles, resource ownership, and resource attributes. ```rego package authz default allow := false # Allow admins everything allow { "ROLE_ADMIN" in input.subject.roles } # Allow users to read their own documents allow { input.action.name == "read" input.resource.type == "Document" input.resource.owner_id == input.subject.id } # Allow users to read non-confidential documents allow { input.action.name == "read" input.resource.type == "Document" not input.resource.confidential } ``` -------------------------------- ### Define OPA Policies in Rego Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt Provides example Rego policies for Open Policy Agent (OPA) to define authorization rules. These policies cover scenarios like admin access, read/write permissions for documents based on ownership and confidentiality, and role-based access control. ```rego package authz import future.keywords.if import future.keywords.in default allow := false # Allow admins everything allow if { "ROLE_ADMIN" in input.subject.roles } # Allow read access to non-confidential documents allow if { input.action.name == "read" input.resource.type == "Document" not input.resource.confidential } # Allow read access to own documents allow if { input.action.name == "read" input.resource.type == "Document" input.resource.owner_id == input.subject.id } # Allow write access to own documents allow if { input.action.name == "write" input.resource.type == "Document" input.resource.owner_id == input.subject.id } # Allow delete access to own documents allow if { input.action.name == "delete" input.resource.type == "Document" input.resource.owner_id == input.subject.id } # Allow create access to authenticated users with USER role allow if { input.action.name == "create" input.resource.type == "Document" "ROLE_USER" in input.subject.roles } # Allow share access to document owners allow if { input.action.name == "share" input.resource.type == "Document" input.resource.owner_id == input.subject.id } # Users in the same department can read non-confidential documents allow if { input.action.name == "read" input.resource.type == "Document" not input.resource.confidential input.subject.department == input.resource.department } ``` -------------------------------- ### Custom Resource Converter Implementation (Java) Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md An example implementation of `ResourceConverter` to convert domain objects (e.g., `Document`) into AuthZEN `Resource` objects. It supports specific domain classes and defines a priority for conversion. ```java @Component public class DocumentResourceConverter implements ResourceConverter { @Override public Resource convert(Object domainObject) { Document doc = (Document) domainObject; return Resource.builder() .type("Document") .id(doc.getId()) .property("owner_id", doc.getOwnerId()) .property("department", doc.getDepartment()) .property("confidential", doc.isConfidential()) .build(); } @Override public boolean supports(Class clazz) { return Document.class.isAssignableFrom(clazz); } @Override public int getPriority() { return 100; // Higher priority = used first } } ``` -------------------------------- ### Custom Subject Resolver Implementation (Java) Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md An example implementation of `SubjectResolver` to extract Subject information from Spring Security's `Authentication` object. This allows custom mapping of user details to the AuthZEN Subject model. ```java @Component public class CustomSubjectResolver implements SubjectResolver { @Override public Subject resolve(Authentication authentication) { MyUserDetails user = (MyUserDetails) authentication.getPrincipal(); return Subject.builder() .type("user") .id(user.getId()) .property("email", user.getEmail()) .property("roles", user.getRoles()) .property("tenant_id", user.getTenantId()) .build(); } } ``` -------------------------------- ### Use hasPermission in Service Methods Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Demonstrates how to use Spring Security's hasPermission expression within @PreAuthorize and @PostAuthorize annotations to enforce access control on service methods. It shows examples of checking permissions based on method arguments and return values. ```java @Service public class DocumentService { @PreAuthorize("hasPermission(#id, 'Document', 'read')") public Document getDocument(String id) { return documentRepository.findById(id); } @PreAuthorize("hasPermission(#document, 'write')") public Document updateDocument(Document document) { return documentRepository.save(document); } @PostAuthorize("hasPermission(returnObject, 'read')") public Document findDocument(String query) { return documentRepository.search(query); } } ``` -------------------------------- ### Build and Use Action Objects in Java Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt Illustrates the creation and usage of Action objects, representing the operation being performed. Actions can include metadata and properties relevant to the operation. ```java import com.bigacl.authz.core.model.Action; import java.util.List; // Build an action with properties Action action = Action.builder() .name("read") .property("fields", List.of("title", "content", "author")) .property("include_metadata", true) .build(); // Simple action with just the name Action simpleAction = new Action("write"); // Create from permission object (used internally by hasPermission) Action fromPermission = Action.fromPermission("delete"); // Add properties to existing action Action updatedAction = action.withProperty("reason", "audit"); // Access action properties String name = action.name(); // "read" Map props = action.properties(); ``` -------------------------------- ### Build and Use Resource Objects in Java Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt Demonstrates how to construct and manipulate Resource objects, which represent the target of an access request. Resources can be built with various attributes and properties. ```java import com.bigacl.authz.core.model.Resource; // Build a resource with attributes Resource resource = Resource.builder() .type("Document") .id("doc-123") .property("owner_id", "alice") .property("department", "Engineering") .property("confidential", true) .property("classification", "internal") .build(); // Simple resource with type and id Resource simpleResource = new Resource("Document", "doc-456"); // Resource with type only (for create operations) Resource typeOnly = Resource.ofType("Document"); // Add properties to existing resource Resource updatedResource = resource.withProperty("version", 2); // Access resource properties String type = resource.type(); // "Document" String id = resource.id(); // "doc-123" Map props = resource.properties(); ``` -------------------------------- ### Run OPA for Integration Tests (Docker) Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/CONTRIBUTING.md Command to run the Open Policy Agent (OPA) in Docker, exposing its port. This is a prerequisite for running integration tests that rely on OPA. ```bash docker run -d -p 8181:8181 openpolicyagent/opa:latest run --server ``` -------------------------------- ### Build and Use AuthzContext Objects in Java Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt Shows how to create and manage AuthzContext objects, which encapsulate environmental information for policy evaluation, such as IP addresses and timestamps. Supports various creation methods and merging. ```java import com.bigacl.authz.core.model.AuthzContext; import java.time.Instant; // Build context with multiple values AuthzContext context = AuthzContext.builder() .value("client_ip", "192.168.1.100") .value("user_agent", "Mozilla/5.0") .value("timestamp", Instant.now().toString()) .value("request_uri", "/api/documents/123") .value("http_method", "GET") .value("tenant_id", "tenant-001") .build(); // Create empty context AuthzContext emptyContext = AuthzContext.empty(); // Create with single value AuthzContext singleValue = AuthzContext.of("request_id", "req-12345"); // Create from map AuthzContext fromMap = AuthzContext.of(Map.of( "client_ip", "10.0.0.1", "session_id", "sess-abc" )); // Add values to existing context AuthzContext updated = context.with("correlation_id", "corr-xyz"); // Merge two contexts AuthzContext merged = context.merge(AuthzContext.of("extra", "value")); // Access context values String ip = context.get("client_ip"); // "192.168.1.100" String defaultVal = context.getOrDefault("missing", "default"); boolean hasKey = context.containsKey("timestamp"); // true boolean empty = context.isEmpty(); // false ``` -------------------------------- ### Configuration for Open Policy Agent (OPA) PDP Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt This YAML configuration snippet demonstrates how to set up the AuthZ Spring Boot Starter to use Open Policy Agent (OPA) as the Policy Decision Point (PDP). It includes settings for enabling the feature, fail-closed behavior, subject defaults, caching, and OPA-specific connection details like URL, policy path, and authentication token. ```yaml authz: enabled: true fail-closed: true # Deny access when PDP is unavailable subject: default-type: user cache: enabled: true ttl: 5m max-size: 10000 pdp: type: opa opa: url: http://localhost:8181 policy-path: /v1/data/authz/allow auth-token: ${OPA_TOKEN:} timeout: 5s ``` -------------------------------- ### Contributing to the Project Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Outlines the standard workflow for contributing to the project, following common Git and GitHub practices. It covers forking the repository, creating feature branches, committing changes, and submitting a pull request. ```bash 1. Fork the repository 2. Create a feature branch (`git checkout -b feature/amazing-feature`) 3. Commit your changes (`git commit -m 'Add amazing feature'`) 4. Push to the branch (`git push origin feature/amazing-feature`) 5. Open a Pull Request ``` -------------------------------- ### Configuration for OpenID AuthZEN PDP Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt This YAML configuration illustrates how to configure the AuthZ Spring Boot Starter to connect with any OpenID AuthZEN-compliant authorization server. It covers enabling the feature, fail-closed behavior, and AuthZEN-specific endpoint details like base URL, evaluation paths, authentication token, and timeout. ```yaml authz: enabled: true fail-closed: true pdp: type: authzen authzen: base-url: https://your-pdp.example.com access-evaluation-path: /access/v1/evaluation access-evaluations-path: /access/v1/evaluations auth-token: ${AUTHZEN_TOKEN:} timeout: 5s ``` -------------------------------- ### Building and Using the Subject Model (Java) Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt Demonstrates how to construct and utilize the Subject model, which represents the principal making an access request. Subjects can include various properties like roles, email, and tenant ID, which are used in authorization policies. The model is immutable, with methods returning new instances upon modification. ```java import com.bigacl.authz.core.model.Subject; import java.util.List; import java.util.Map; // Build a subject with user attributes Subject subject = Subject.builder() .type("user") .id("alice") .property("email", "alice@example.com") .property("roles", List.of("ROLE_USER", "ROLE_ADMIN")) .property("department", "Engineering") .property("tenant_id", "tenant-001") .build(); // Simple subject with just type and id Subject simpleSubject = new Subject("user", "bob"); // Add properties to existing subject (immutable, returns new instance) Subject updatedSubject = subject.withProperty("last_login", "2024-01-15"); // Access subject properties String type = subject.type(); // "user" String id = subject.id(); // "alice" Map props = subject.properties(); ``` -------------------------------- ### Maven Dependencies for AuthZ Spring Boot Starter Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt This section lists the necessary Maven dependencies for integrating the AuthZ Spring Boot Starter into a Spring Boot project. It includes the core starter dependency and optional connector dependencies for different Policy Decision Points (PDPs) like OPA, AVP, and AuthZEN. ```xml com.bigacl authz-spring-boot-starter 0.1.0 com.bigacl authz-pdp-opa 0.1.0 com.bigacl authz-pdp-avp 0.1.0 com.bigacl authz-pdp-authzen 0.1.0 ``` -------------------------------- ### Create Feature Branch (Git) Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/CONTRIBUTING.md Demonstrates how to create a new feature branch from the main branch using Git. This is a standard practice for isolating development work. ```bash git checkout -b feature/amazing-feature ``` -------------------------------- ### Build and Use AuthzRequest Objects in Java Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt Demonstrates how to construct an AuthzRequest, which combines Subject, Resource, Action, and AuthzContext for a complete authorization check. Includes methods for adding context and accessing components. ```java import com.bigacl.authz.core.model.*; // Build a complete authorization request AuthzRequest request = AuthzRequest.builder() .subject(Subject.builder() .type("user") .id("alice") .property("roles", List.of("ROLE_USER")) .build()) .resource(Resource.builder() .type("Document") .id("doc-123") .property("owner_id", "bob") .build()) .action("read") .context(AuthzContext.builder() .value("client_ip", "192.168.1.100") .build()) .build(); // Simple request without context AuthzRequest simpleRequest = new AuthzRequest( new Subject("user", "alice"), new Resource("Document", "doc-123"), new Action("read") ); // Add context to existing request AuthzRequest withContext = request.withContext( AuthzContext.of("timestamp", Instant.now().toString()) ); // Add single context value AuthzRequest withValue = request.withContextValue("trace_id", "trace-123"); // Access request components Subject subject = request.subject(); Resource resource = request.resource(); Action action = request.action(); AuthzContext context = request.context(); ``` -------------------------------- ### Configuration for Amazon Verified Permissions (AVP) PDP Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt This YAML configuration shows how to configure the AuthZ Spring Boot Starter to utilize AWS Verified Permissions (AVP) as the Policy Decision Point (PDP). Key settings include enabling the feature, fail-closed behavior, and AVP-specific parameters such as the policy store ID and AWS region. ```yaml authz: enabled: true fail-closed: true pdp: type: avp avp: policy-store-id: ${AVP_POLICY_STORE_ID} region: ${AWS_REGION:us-east-1} ``` -------------------------------- ### AuthzResponse: Create and Inspect Authorization Decisions (Java) Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt Demonstrates how to create AuthzResponse objects for permit and deny decisions, including adding contextual information like reasons and policy IDs. It also shows how to inspect the decision and retrieve context values. ```java import com.bigacl.authz.core.model.AuthzResponse; import java.util.Map; // Create permit response AuthzResponse permit = AuthzResponse.permit(); // Create permit with context AuthzResponse permitWithContext = AuthzResponse.permit(Map.of( "decision_id", "dec-12345", "policy_id", "policy-admin-access" )); // Create deny response AuthzResponse deny = AuthzResponse.deny(); // Create deny with reason AuthzResponse denyWithReason = AuthzResponse.denyWithReason( "User does not have read permission on confidential documents" ); // Create deny with full context AuthzResponse denyWithContext = AuthzResponse.deny(Map.of( "reason", "Insufficient permissions", "required_role", "ROLE_ADMIN", "policy_id", "policy-confidential-docs" )); // Check decision boolean decision = permit.decision(); // true boolean isPermit = permit.isPermit(); // true boolean isDeny = deny.isDeny(); // true // Access response context String reason = denyWithReason.getReason(); // "User does not have..." String policyId = permitWithContext.getContextValue("policy_id"); Map ctx = permit.context(); ``` -------------------------------- ### Implement Custom PolicyDecisionPoint in Java Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt Demonstrates how to implement the PolicyDecisionPoint interface to create a custom PDP. This involves defining authorization logic within the `evaluate` and `evaluateBatch` methods and implementing health checks and type support. ```java import com.bigacl.authz.core.model.AuthzRequest; import com.bigacl.authz.core.model.AuthzResponse; import com.bigacl.authz.core.pdp.PolicyDecisionPoint; import com.bigacl.authz.core.pdp.PolicyEvaluationException; import java.util.List; // Custom PDP implementation public class CustomPolicyDecisionPoint implements PolicyDecisionPoint { @Override public AuthzResponse evaluate(AuthzRequest request) { // Implement your authorization logic boolean allowed = checkPermission(request); if (allowed) { return AuthzResponse.permit(); } return AuthzResponse.denyWithReason("Access denied by custom policy"); } @Override public List evaluateBatch(List requests) { // Batch evaluation for better performance return requests.stream() .map(this::evaluate) .toList(); } @Override public String getType() { return "custom"; } @Override public boolean supports(String pdpType) { return "custom".equalsIgnoreCase(pdpType); } @Override public boolean isHealthy() { // Check if PDP is reachable return pingPdpEndpoint(); } private boolean checkPermission(AuthzRequest request) { // Your custom authorization logic here return true; } private boolean pingPdpEndpoint() { return true; } } ``` -------------------------------- ### Object-Based Permission Check with @PreAuthorize Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt This Java service demonstrates how to use the `hasPermission()` method within the `@PreAuthorize` annotation to perform object-based permission checks. It shows how to secure methods based on the properties of domain objects passed as parameters, leveraging the starter's resource conversion capabilities. ```java import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; @Service public class DocumentService { // Permission check on method parameter // Evaluates: hasPermission(document, 'write') // The document object is converted to a Resource using ResourceConverter @PreAuthorize("hasPermission(#document, 'write')") public Document updateDocument(Document document) { // Update logic here document.setUpdatedAt(Instant.now()); return documentRepository.save(document); } // Permission check on method parameter with different action @PreAuthorize("hasPermission(#document, 'delete')") public void deleteDocument(Document document) { documentRepository.delete(document); } } ``` -------------------------------- ### Core AuthZ Configuration Options Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Provides a reference for core configuration properties of the AuthZ Spring Boot Starter. This includes enabling/disabling the feature, fail-safe behavior, subject defaults, cache settings, and general PDP configuration. ```yaml authz: # Enable/disable AuthZ (default: true) enabled: true # Behavior when PDP is unavailable (default: true = deny) fail-closed: true # Subject configuration subject: default-type: user # Cache configuration cache: enabled: true ttl: 5m max-size: 10000 # PDP configuration pdp: type: opa # opa, avp, or authzen ``` -------------------------------- ### Implement AuthzContextProvider for Request Context (Java) Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt This Java snippet shows how to implement AuthzContextProvider to enrich authorization requests with contextual information from the HTTP request. It extracts details like client IP, user agent, request URI, tenant ID, and timestamps. Dependencies include Jakarta Servlet API, Spring Web, and core BigACL authorization models. ```java import com.bigacl.authz.core.model.AuthzContext; import com.bigacl.authz.core.resolver.AuthzContextProvider; import jakarta.servlet.http.HttpServletRequest; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import java.time.Instant; @Component public class CustomContextProvider implements AuthzContextProvider { @Override public AuthzContext provide() { HttpServletRequest request = getCurrentRequest(); if (request == null) { return AuthzContext.empty(); } return provide(request); } @Override public AuthzContext provide(HttpServletRequest request) { if (request == null) { return AuthzContext.empty(); } return AuthzContext.builder() // Request information .value("client_ip", getClientIp(request)) .value("user_agent", request.getHeader("User-Agent")) .value("request_uri", request.getRequestURI()) .value("http_method", request.getMethod()) .value("request_id", request.getHeader("X-Request-ID")) // Tenant context .value("tenant_id", request.getHeader("X-Tenant-ID")) // Time context .value("timestamp", Instant.now().toString()) .value("timezone", request.getHeader("X-Timezone")) // Security context .value("session_id", request.getSession(false) != null ? request.getSession().getId() : null) .value("origin", request.getHeader("Origin")) .build(); } private HttpServletRequest getCurrentRequest() { ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); return attrs != null ? attrs.getRequest() : null; } private String getClientIp(HttpServletRequest request) { String xff = request.getHeader("X-Forwarded-For"); if (xff != null && !xff.isEmpty()) { return xff.split(",")[0].trim(); } return request.getRemoteAddr(); } } ``` -------------------------------- ### Implement ResourceConverter for Domain Object Conversion (Java) Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt This snippet demonstrates how to implement the ResourceConverter interface to convert domain objects like 'Document' and 'Project' into a 'Resource' object for authorization evaluation. It handles specific domain types and provides a priority for conversion order. Dependencies include core BigACL authorization models and Spring's stereotype annotations. ```java import com.bigacl.authz.core.model.Resource; import com.bigacl.authz.core.resolver.ResourceConverter; import org.springframework.stereotype.Component; @Component public class DocumentResourceConverter implements ResourceConverter { @Override public Resource convert(Object domainObject) { if (domainObject instanceof Document doc) { return Resource.builder() .type("Document") .id(doc.getId()) .property("owner_id", doc.getOwnerId()) .property("department", doc.getDepartment()) .property("confidential", doc.isConfidential()) .property("classification", doc.getClassification()) .property("created_by", doc.getCreatedBy()) .build(); } if (domainObject instanceof Optional opt && opt.isPresent()) { return convert(opt.get()); } throw new IllegalArgumentException( "Cannot convert " + domainObject.getClass() + " to Resource" ); } @Override public boolean supports(Class clazz) { return Document.class.isAssignableFrom(clazz) || (Optional.class.isAssignableFrom(clazz)); } @Override public int getPriority() { return 100; // Higher priority = checked first } } // Additional converter for another domain type @Component public class ProjectResourceConverter implements ResourceConverter { @Override public Resource convert(Object domainObject) { Project project = (Project) domainObject; return Resource.builder() .type("Project") .id(project.getId()) .property("owner_id", project.getOwnerId()) .property("team_members", project.getTeamMemberIds()) .property("status", project.getStatus().name()) .property("budget_level", project.getBudgetLevel()) .build(); } @Override public boolean supports(Class clazz) { return Project.class.isAssignableFrom(clazz); } @Override public int getPriority() { return 100; } } ``` -------------------------------- ### Open Policy Agent (OPA) Specific Configuration Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Details the configuration options specific to using Open Policy Agent (OPA) as the PDP. This includes the OPA server URL, policy path, optional authentication token, and request timeout. ```yaml authz: pdp: type: opa opa: url: http://localhost:8181 policy-path: /v1/data/authz/allow auth-token: ${OPA_TOKEN:} # Optional Bearer token timeout: 5s ``` -------------------------------- ### Configure PDP Type and OPA Endpoint Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Configures the AuthZ starter to use Open Policy Agent (OPA) as the Policy Decision Point (PDP). This involves specifying the PDP type and the OPA endpoint URL, along with the policy path. ```yaml # application.yml authz: enabled: true pdp: type: opa opa: url: http://localhost:8181 policy-path: /v1/data/authz/allow ``` -------------------------------- ### AuthZEN PDP Configuration (YAML) Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Configures the Policy Decision Point (PDP) for AuthZEN, specifying the base URL, API paths, authentication token, and timeout for communication with the AuthZEN service. ```yaml authz: pdp: type: authzen authzen: base-url: https://your-pdp.example.com access-evaluation-path: /access/v1/evaluation access-evaluations-path: /access/v1/evaluations auth-token: "${AUTHZEN_TOKEN:}" timeout: 5s ``` -------------------------------- ### Manage Authorization Cache in Java Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt Shows how to use the AuthzCacheProvider interface to manage authorization decision caching within a Spring Boot application. This includes invalidating cache entries based on subjects, resources, or all entries, and logging cache statistics. ```java import com.bigacl.authz.core.cache.AuthzCacheProvider; import com.bigacl.authz.core.cache.AuthzCacheProvider.CacheStatistics; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class AuthorizationService { @Autowired private AuthzCacheProvider cacheProvider; // Invalidate cache when user permissions change public void onUserRolesChanged(String userId) { cacheProvider.invalidateBySubject("user", userId); } // Invalidate cache when resource is modified public void onDocumentUpdated(String documentId) { cacheProvider.invalidateByResource("Document", documentId); } // Invalidate all cache entries (e.g., after policy update) public void onPolicyUpdated() { cacheProvider.invalidateAll(); } // Monitor cache performance public void logCacheStatistics() { CacheStatistics stats = cacheProvider.getStatistics(); System.out.println("Cache Statistics:"); System.out.println(" Hit rate: " + String.format("%.2f%%", stats.hitRate() * 100)); System.out.println(" Hit count: " + stats.hitCount()); System.out.println(" Miss count: " + stats.missCount()); System.out.println(" Eviction count: " + stats.evictionCount()); System.out.println(" Current size: " + stats.size()); } } ``` -------------------------------- ### AuthZEN Cache Statistics Retrieval (Java) Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Retrieves and prints statistics from the AuthZEN cache provider, including hit rate, hit count, miss count, and current cache size. ```java AuthzCacheProvider.CacheStatistics stats = cacheProvider.getStatistics(); System.out.println("Hit rate: " + stats.hitRate()); System.out.println("Hit count: " + stats.hitCount()); System.out.println("Miss count: " + stats.missCount()); System.out.println("Size: " + stats.size()); ``` -------------------------------- ### Amazon Verified Permissions (AVP) Configuration Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Configuration settings for using Amazon Verified Permissions (AVP) as the Policy Decision Point (PDP). Requires the policy store ID and optionally the AWS region. ```yaml authz: pdp: type: avp avp: policy-store-id: ${AVP_POLICY_STORE_ID} region: ${AWS_REGION:us-east-1} ``` -------------------------------- ### AuthZEN Data Model: Context (Java) Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Provides additional environmental information for the authorization decision, such as client IP, timestamp, and request URI. ```java AuthzContext context = AuthzContext.builder() .value("client_ip", "192.168.1.100") .value("timestamp", Instant.now().toString()) .value("request_uri", "/api/documents/123") .build(); ``` -------------------------------- ### Enable Spring Security Method Security Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt This Java configuration class enables Spring Security's method security features, which are required for the AuthZ Spring Boot Starter to intercept and evaluate authorization policies on method calls. The `@EnableMethodSecurity` annotation activates this functionality. ```java import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; @Configuration @EnableMethodSecurity public class SecurityConfig { // The AuthzPermissionEvaluator is auto-configured // No additional beans required for basic usage } ``` -------------------------------- ### ID-based Authorization with Spring Security Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Demonstrates how to use the `hasPermission` method from Spring Security's `@PreAuthorize` annotation for ID-based authorization. This allows fine-grained control over resource access based on the target ID, target type, and required permission. ```java // hasPermission(targetId, targetType, permission) @PreAuthorize("hasPermission(#id, 'Document', 'read')") public Document getDocument(String id) { } @PreAuthorize("hasPermission(#id, 'Document', 'delete')") public void deleteDocument(String id) { } ``` -------------------------------- ### AuthZEN Data Model: Action (Java) Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Represents the operation being performed on a resource. It has a name and can include properties like the fields being accessed. ```java Action action = Action.builder() .name("read") .property("fields", List.of("title", "content")) .build(); ``` -------------------------------- ### AuthZEN Caching Configuration (YAML) Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Enables and configures the built-in caching mechanism using Caffeine. Settings include enabling/disabling the cache, time-to-live (TTL), and maximum cache size. ```yaml authz: cache: enabled: true ttl: 5m # Time-to-live for cache entries max-size: 10000 # Maximum number of cached decisions ``` -------------------------------- ### AuthZEN Cache Invalidation (Java) Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Demonstrates programmatic cache invalidation using the `AuthzCacheProvider`. It shows how to invalidate specific entries by subject or resource, or clear the entire cache. ```java @Autowired private AuthzCacheProvider cacheProvider; // Invalidate all decisions for a user cacheProvider.invalidateBySubject("user", "alice"); // Invalidate all decisions for a resource cacheProvider.invalidateByResource("Document", "doc-123"); // Invalidate all cache entries cacheProvider.invalidateAll(); ``` -------------------------------- ### AuthZEN Data Model: Resource (Java) Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Represents the target of the access request. It includes a type, unique ID, and properties such as owner and confidentiality. ```java Resource resource = Resource.builder() .type("Document") .id("doc-123") .property("owner_id", "alice") .property("confidential", true) .build(); ``` -------------------------------- ### Enable Spring Method Security Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Enables Spring Security's method security features, which are required for using annotations like @PreAuthorize and @PostAuthorize. The PermissionEvaluator is automatically configured by the starter. ```java @Configuration @EnableMethodSecurity public class SecurityConfig { // The PermissionEvaluator is auto-configured } ``` -------------------------------- ### Object-Based Permission Check with @PostAuthorize (Java) Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt Uses @PostAuthorize to perform permission checks on the return value of a method after it has executed. This is useful for verifying access to the retrieved resource. It requires the Spring Security dependency. ```java import org.springframework.security.access.prepost.PostAuthorize; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class DocumentService { // Permission check on return value // Evaluates: hasPermission(returnObject, 'read') // Access is denied if user cannot read the returned document @PostAuthorize("hasPermission(returnObject, 'read')") public Optional findById(String id) { return Optional.ofNullable(documentRepository.findById(id)); } // For non-Optional returns, check the object directly @PostAuthorize("hasPermission(returnObject, 'read')") public Document getDocument(String id) { Document doc = documentRepository.findById(id); if (doc == null) { throw new DocumentNotFoundException("Document not found: " + id); } return doc; } } ``` -------------------------------- ### ID-Based Permission Check with @PreAuthorize (Java) Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt Utilizes @PreAuthorize to check permissions based on resource type and ID before a method executes. This is suitable for operations where the full object is not immediately available or needed for the check. It requires the Spring Security dependency. ```java import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; @Service public class DocumentService { // Permission check by ID and type // Evaluates: hasPermission(#id, 'Document', 'read') // Creates Resource with type="Document" and id=parameter value @PreAuthorize("hasPermission(#id, 'Document', 'read')") public Document getById(String id) { Document doc = documentRepository.findById(id); if (doc == null) { throw new DocumentNotFoundException("Document not found: " + id); } return doc; } // Create permission with null ID (for new resources) @PreAuthorize("hasPermission(null, 'Document', 'create')") public Document create(Document document, String ownerId) { document.setId(UUID.randomUUID().toString()); document.setOwnerId(ownerId); document.setCreatedAt(Instant.now()); return documentRepository.save(document); } // Update permission by resource ID @PreAuthorize("hasPermission(#id, 'Document', 'write')") public Document update(String id, Document updates) { Document existing = documentRepository.findById(id); existing.setTitle(updates.getTitle()); existing.setContent(updates.getContent()); existing.setUpdatedAt(Instant.now()); return documentRepository.save(existing); } // Delete permission by resource ID @PreAuthorize("hasPermission(#id, 'Document', 'delete')") public void delete(String id) { documentRepository.deleteById(id); } // Share permission by resource ID @PreAuthorize("hasPermission(#id, 'Document', 'share')") public void share(String id, String userId) { Document doc = documentRepository.findById(id); doc.getSharedWith().add(userId); documentRepository.save(doc); } } ``` -------------------------------- ### Spring Security hasPermission() with Object (Java) Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Illustrates using Spring Security's `hasPermission()` method with a target domain object in `@PreAuthorize` and `@PostAuthorize` annotations. The domain object is automatically converted to an AuthZEN `Resource`. ```java // hasPermission(targetDomainObject, permission) @PreAuthorize("hasPermission(#document, 'write')") public void updateDocument(Document document) { } @PostAuthorize("hasPermission(returnObject, 'read')") public Document getDocument(String id) { } ``` -------------------------------- ### AuthZEN Data Model: Subject (Java) Source: https://github.com/big-acl/authz-spring-boot-starter/blob/main/README.md Represents the entity requesting access. It includes a type, unique ID, and custom properties like roles and department. ```java Subject subject = Subject.builder() .type("user") .id("alice") .property("email", "alice@example.com") .property("roles", List.of("ROLE_USER", "ROLE_ADMIN")) .property("department", "Engineering") .build(); ``` -------------------------------- ### Time-based Access Control Policy (Rego) Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt This Rego policy defines rules for time-based access control. It checks if the action is 'read' on a 'Report' resource and if the request occurs during business hours (9 AM to 6 PM UTC). The `is_business_hours` function parses the timestamp and compares the hour. ```rego allow if { input.action.name == "read" input.resource.type == "Report" is_business_hours(input.context.timestamp) } is_business_hours(timestamp) if { # Parse and check business hours (9 AM - 6 PM) hour := time.clock([time.parse_rfc3339_ns(timestamp), "UTC"])[0] hour >= 9 hour < 18 } ``` -------------------------------- ### CustomSubjectResolver: Extract User Details from Spring Security (Java) Source: https://context7.com/big-acl/authz-spring-boot-starter/llms.txt Provides an implementation of the SubjectResolver interface to extract custom subject information from Spring Security's Authentication object. This includes handling custom user details classes and JWTs for building a Subject object. ```java import com.bigacl.authz.core.model.Subject; import com.bigacl.authz.core.resolver.SubjectResolver; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.stereotype.Component; import java.util.List; @Component public class CustomSubjectResolver implements SubjectResolver { @Override public Subject resolve(Authentication authentication) { // Handle your custom user details class if (authentication.getPrincipal() instanceof MyUserDetails) { MyUserDetails user = (MyUserDetails) authentication.getPrincipal(); List roles = authentication.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .toList(); return Subject.builder() .type("user") .id(user.getId()) .property("email", user.getEmail()) .property("roles", roles) .property("tenant_id", user.getTenantId()) .property("department", user.getDepartment()) .property("manager_id", user.getManagerId()) .property("clearance_level", user.getClearanceLevel()) .build(); } // Handle OAuth2 tokens if (authentication.getPrincipal() instanceof Jwt) { Jwt jwt = (Jwt) authentication.getPrincipal(); return Subject.builder() .type("user") .id(jwt.getSubject()) .property("email", jwt.getClaim("email")) .property("roles", jwt.getClaimAsStringList("roles")) .property("tenant_id", jwt.getClaim("tenant_id")), .build(); } // Default fallback return Subject.builder() .type("user") .id(authentication.getName()) .property("roles", authentication.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .toList()) .build(); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.