### Configure OPA Properties via YAML Source: https://github.com/styrainc/opa-springboot/blob/main/README.md Example configuration for OPA Spring Boot settings, including server URL, policy paths, resource types, and event publishing preferences. ```yaml opa: url: http://localhost:8182 path: foo/bar request: resource: type: stomp_endpoint context: type: websocket subject: type: oauth2_resource_owner response: context: reason-key: de authorization-event: denied: enabled: false granted: enabled: true ``` -------------------------------- ### AuthZEN Input and Output Schema Source: https://context7.com/styrainc/opa-springboot/llms.txt Example JSON structures for the AuthZEN-compliant input sent to OPA and the expected decision output returned by the policy engine. ```json // Input { "subject": { "id": "user@example.com", "authorities": [{"authority": "ROLE_USER"}] }, "resource": { "id": "/api/documents/123" }, "action": { "name": "GET" } } // Output { "decision": true, "context": { "id": "policy-rule-123", "reason_user": { "en": "User has read access" } } } ``` -------------------------------- ### OPA Properties Configuration Example Source: https://context7.com/styrainc/opa-springboot/llms.txt This YAML snippet shows how to configure OPA authorization settings in an `application.yaml` file. It covers essential properties such as the OPA server URL, policy path, and customization for request input, response context, and authorization event publishing. ```yaml # application.yaml opa: url: http://localhost:8181 # OPA server URL (default: http://localhost:8181) path: authz/main # Policy path in OPA (default: null, uses OPA default) request: resource: type: endpoint # Resource type in input (default: "endpoint") context: type: http # Context type in input (default: "http") subject: type: java_authentication # Subject type in input (default: "java_authentication") response: context: reason-key: en # Key for decision reasons (default: "en") authorization-event: denied: enabled: true # Publish events on denied requests (default: true) granted: enabled: false # Publish events on granted requests (default: false) ``` -------------------------------- ### Define OPA Authorization Policy in Rego Source: https://context7.com/styrainc/opa-springboot/llms.txt An example Rego policy that defines authorization logic. It consumes AuthZEN-compliant input and returns a decision object containing the authorization result, context ID, and localized reason messages. ```rego # authz/main.rego package authz import rego.v1 default main := { "decision": false, "context": { "id": "default-deny", "reason_user": { "en": "Access denied by default policy" } } } main := result if { input.subject.id != null input.action.name == "GET" result := { "decision": true, "context": { "id": "authenticated-read", "reason_user": { "en": "Authenticated users can read resources" } } } } ``` -------------------------------- ### Customize OPA Input Context with OPAInputContextCustomizer (Java) Source: https://github.com/styrainc/opa-springboot/blob/main/README.md Defines an OPAInputContextCustomizer bean to modify the 'context' part of the OPA input. The context can be set to null or modified, ensuring it contains a 'type' key if not null. This example demonstrates how to remove the context entirely. ```java import static io.github.open_policy_agent.opa.springboot.input.InputConstants.CONTEXT; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.CONTEXT_TYPE; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import io.github.open_policy_agent.opa.springboot.input.OPAInputContextCustomizer; @Configuration public class OPAConfig { @Bean public OPAInputContextCustomizer opaInputContextCustomizer() { return (authentication, requestAuthorizationContext, context) -> null; } } ``` -------------------------------- ### Customize OPA Input Resource with Java Source: https://github.com/styrainc/opa-springboot/blob/main/docs/how-to/add-sdk.md Defines an OPAInputResourceCustomizer bean to modify the 'resource' part of the OPA input. The resource must contain 'type' and 'id'. This example changes the resource type and adds a new key-value pair. ```java import static io.github.open_policy_agent.opa.springboot.input.InputConstants.RESOURCE; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.RESOURCE_TYPE; import java.util.HashMap; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import io.github.open_policy_agent.opa.springboot.input.OPAInputResourceCustomizer; @Configuration public class OPAConfig { @Bean public OPAInputResourceCustomizer opaInputResourceCustomizer() { return (authentication, requestAuthorizationContext, resource) -> { var customResource = new HashMap<>(resource); customResource.put(RESOURCE_TYPE, "stomp_endpoint"); // Change an existing attribute. customResource.put("resource_key", "resource_value"); // Add a new attribute. return customResource; }; } } ``` -------------------------------- ### Listen to OPA Authorization Events (Java) Source: https://github.com/styrainc/opa-springboot/blob/main/README.md Provides an example of an event listener that reacts to Spring Security's Authorization Events, specifically AuthorizationDeniedEvent and AuthorizationGrantedEvent. These events contain OPAAuthorizationDecision, allowing access to the OPA server's response. Clients can enable or disable these events via properties. ```java import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; import io.github.open_policy_agent.opa.springboot.authorization.event.AuthorizationDeniedEvent; import io.github.open_policy_agent.opa.springboot.authorization.event.AuthorizationGrantedEvent; @Component public class OPAAuthorizationEventListener { @EventListener public void onDeny(AuthorizationDeniedEvent denied) { // Handle denied event } @EventListener public void onGrant(AuthorizationGrantedEvent granted) { // Handle granted event } } ``` -------------------------------- ### Configure OPAAuthorizationManager in Spring Security Source: https://github.com/styrainc/opa-springboot/blob/main/docs/how-to/add-sdk.md Demonstrates how to register the OPAAuthorizationManager within a Spring Security configuration class. This setup ensures that all incoming HTTP requests are intercepted and authorized using OPA policies. ```java package com.example; import io.github.open_policy_agent.opa.springboot.OPAAuthorizationManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authorization.AuthorizationManager; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.access.intercept.RequestAuthorizationContext; @Configuration @EnableWebSecurity public class SecurityConfig { @Autowired OPAAuthorizationManager opaAuthorizationManager; @Bean SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(authorize -> authorize.anyRequest().access(opaAuthorizationManager)); // Other security configs return http.build(); } } ``` -------------------------------- ### Customize OPA Input Action with Java Source: https://github.com/styrainc/opa-springboot/blob/main/docs/how-to/add-sdk.md Defines an OPAInputActionCustomizer bean to modify the 'action' part of the OPA input. The action must contain a 'name'. This example removes headers, changes the action name, and adds a new key-value pair. ```java import static io.github.open_policy_agent.opa.springboot.input.InputConstants.ACTION; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.ACTION_HEADERS; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.ACTION_NAME; import java.util.HashMap; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import io.github.open_policy_agent.opa.springboot.input.OPAInputActionCustomizer; @Configuration public class OPAConfig { @Bean public OPAInputActionCustomizer opaInputActionCustomizer() { return (authentication, requestAuthorizationContext, action) -> { var customAction = new HashMap<>(action); customAction.remove(ACTION_HEADERS); // Remove an existing attribute. customAction.put(ACTION_NAME, "read"); // Change an existing attribute. customAction.put("action_key", "action_value"); // Add a new attribute. return customAction; }; } } ``` -------------------------------- ### Remove OPA Input Context with Java Source: https://github.com/styrainc/opa-springboot/blob/main/docs/how-to/add-sdk.md Defines an OPAInputContextCustomizer bean to customize the 'context' part of the OPA input. If not null, context must contain a 'type'. This example demonstrates how to remove the context entirely by returning null. ```java import static io.github.open_policy_agent.opa.springboot.input.InputConstants.CONTEXT; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.CONTEXT_TYPE; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import io.github.open_policy_agent.opa.springboot.input.OPAInputContextCustomizer; @Configuration public class OPAConfig { @Bean public OPAInputContextCustomizer opaInputContextCustomizer() { return (authentication, requestAuthorizationContext, context) -> null; } } ``` -------------------------------- ### Customize OPA Input Subject with Java Source: https://github.com/styrainc/opa-springboot/blob/main/docs/how-to/add-sdk.md Defines an OPAInputSubjectCustomizer bean to modify the 'subject' part of the OPA input. The subject must contain 'type' and 'id'. This example removes authorities, changes the type, and adds a new key-value pair. ```java import static io.github.open_policy_agent.opa.springboot.input.InputConstants.SUBJECT; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.SUBJECT_AUTHORITIES; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.SUBJECT_TYPE; import java.util.HashMap; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import io.github.open_policy_agent.opa.springboot.input.OPAInputSubjectCustomizer; @Configuration public class OPAConfig { @Bean public OPAInputSubjectCustomizer opaInputSubjectCustomizer() { return (authentication, requestAuthorizationContext, subject) -> { var customSubject = new HashMap<>(subject); customSubject.remove(SUBJECT_AUTHORITIES); // Remove an existing attribute. customSubject.put(SUBJECT_TYPE, "oauth2_resource_owner"); // Change an existing attribute. customSubject.put("subject_key", "subject_value"); // Add a new attribute. return customSubject; }; } } ``` -------------------------------- ### Build and Publish SDK Locally Source: https://github.com/styrainc/opa-springboot/blob/main/README.md Commands to build the SDK from source and publish the artifact to the local Maven repository for testing or local development. ```bash ./gradlew publishToMavenLocal -Pskip.signing ``` ```batch gradlew.bat publishToMavenLocal -"Pskip.signing" ``` -------------------------------- ### Configure Project Dependencies Source: https://context7.com/styrainc/opa-springboot/llms.txt Configuration snippets for adding the OPA Spring Boot SDK to Gradle and Maven build files. ```gradle dependencies { implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'io.github.open-policy-agent.opa:springboot:1.0.5' } ``` ```xml io.github.open-policy-agent.opa springboot 1.0.5 ``` -------------------------------- ### Define Custom OPAClient Bean Source: https://github.com/styrainc/opa-springboot/blob/main/README.md Shows how to instantiate a custom OPAClient bean to provide specific headers or custom HTTP clients for communication with the OPA server. ```java import io.github.open_policy_agent.opa.OPAClient; @Configuration public class OPAConfig { @Bean public OPAClient opaClient(OPAProperties opaProperties) { var headers = Map.ofEntries(entry("Authorization", "Bearer secret")); return new OPAClient(opaProperties.getUrl(), headers); } } ``` -------------------------------- ### Enable SDK Logging Source: https://context7.com/styrainc/opa-springboot/llms.txt Properties to enable TRACE and DEBUG level logging for the OPA Spring Boot SDK to assist in troubleshooting connectivity and policy evaluation. ```properties logging.level.io.github.open_policy_agent.opa.springboot=TRACE logging.level.io.github.open_policy_agent.opa=DEBUG ``` -------------------------------- ### Customize OPA Input Action in Java Source: https://github.com/styrainc/opa-springboot/blob/main/README.md Defines an OPAInputActionCustomizer to tailor the 'action' component of the OPA input map. This is useful for specifying the intended action (e.g., 'read', 'write') or adding contextual details about the operation. ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import io.github.open_policy_agent.opa.springboot.input.OPAInputActionCustomizer; import java.util.HashMap; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.ACTION; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.ACTION_HEADERS; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.ACTION_NAME; @Configuration public class OPAConfig { @Bean public OPAInputActionCustomizer opaInputActionCustomizer() { return (authentication, requestAuthorizationContext, action) -> { var customAction = new HashMap<>(action); customAction.remove(ACTION_HEADERS); // Remove an existing attribute. customAction.put(ACTION_NAME, "read"); // Change an existing attribute. customAction.put("action_key", "action_value"); // Add a new attribute. return customAction; }; } } ``` -------------------------------- ### Customize OPA Resource Input with OPAInputResourceCustomizer Source: https://context7.com/styrainc/opa-springboot/llms.txt Enables customization of the 'resource' section of the OPA input document. This is used to inject path variables, query parameters, or specific resource types into the policy engine for fine-grained access control. ```java import io.github.open_policy_agent.opa.springboot.input.OPAInputResourceCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.HashMap; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.*; @Configuration public class OPAConfig { @Bean public OPAInputResourceCustomizer opaInputResourceCustomizer() { return (authentication, requestAuthorizationContext, resource) -> { var customResource = new HashMap<>(resource); var request = requestAuthorizationContext.getRequest(); // Change resource type for WebSocket endpoints if (request.getServletPath().startsWith("/ws")) { customResource.put(RESOURCE_TYPE, "websocket_endpoint"); } // Add path variables as resource attributes String path = request.getServletPath(); if (path.matches("/api/documents/\\d+")) { String documentId = path.substring(path.lastIndexOf('/') + 1); customResource.put("document_id", documentId); } // Add query parameters customResource.put("query_params", request.getParameterMap()); return customResource; }; } } ``` -------------------------------- ### Configure OPA Spring Boot SDK Properties (YAML) Source: https://github.com/styrainc/opa-springboot/blob/main/docs/how-to/add-sdk.md Shows how to configure the OPA Spring Boot SDK using external configuration properties, specifically in a `application.yaml` file. These properties control the OPA server URL, policy path, and context types for requests and responses. ```yaml opa: url: http://localhost:8182 # OPA server URL. Default is "http://localhost:8181". path: foo/bar # Policy path in OPA. Default is null. request: resource: type: stomp_endpoint # Type of the request's resource. Default is "endpoint". context: type: websocket # Type of the request's context. Default is "http". subject: type: oauth2_resource_owner # Type of the request's subject. Default is "java_authentication". response: context: reason-key: de # Key to search for decision reasons in the response. Default is "en". ``` -------------------------------- ### Add OPA Spring Boot SDK Dependency (Gradle) Source: https://github.com/styrainc/opa-springboot/blob/main/docs/how-to/add-sdk.md Demonstrates how to add the OPA Spring Boot SDK as a dependency in a Gradle-based project. This is typically done in the `build.gradle` file to include the necessary libraries for OPA integration. ```gradle implementation 'io.github.open-policy-agent.opa:springboot:+' ``` -------------------------------- ### Configure OPAAuthorizationManager in Spring Security Source: https://github.com/styrainc/opa-springboot/blob/main/README.md Demonstrates how to integrate the OPAAuthorizationManager into a Spring Security configuration to enforce authorization on HTTP requests. ```java import io.github.open_policy_agent.opa.springboot.OPAAuthorizationManager; @Configuration @EnableWebSecurity public class SecurityConfig { @Autowired OPAAuthorizationManager opaAuthorizationManager; @Bean SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(authorize -> authorize.anyRequest().access(opaAuthorizationManager)); // Other security configs return http.build(); } } ``` -------------------------------- ### Customize OPA Input Resource in Java Source: https://github.com/styrainc/opa-springboot/blob/main/README.md Provides an OPAInputResourceCustomizer to alter the 'resource' field within the OPA input map. This enables modification of resource attributes, such as its type or adding specific identifiers, for policy decisions. ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import io.github.open_policy_agent.opa.springboot.input.OPAInputResourceCustomizer; import java.util.HashMap; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.RESOURCE; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.RESOURCE_TYPE; @Configuration public class OPAConfig { @Bean public OPAInputResourceCustomizer opaInputResourceCustomizer() { return (authentication, requestAuthorizationContext, resource) -> { var customResource = new HashMap<>(resource); customResource.put(RESOURCE_TYPE, "stomp_endpoint"); // Change an existing attribute. customResource.put("resource_key", "resource_value"); // Add a new attribute. return customResource; }; } } ``` -------------------------------- ### Configure OPA Path Selection with OPAPathSelector Source: https://context7.com/styrainc/opa-springboot/llms.txt Implements a functional interface to dynamically select OPA policy paths based on the request context. This is essential for multi-tenant architectures or routing requests to specific policies based on URL patterns. ```java import io.github.open_policy_agent.opa.springboot.OPAPathSelector; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class OPAConfig { @Bean public OPAPathSelector opaPathSelector() { return (authentication, requestAuthorizationContext, opaInput) -> { String httpPath = requestAuthorizationContext.getRequest().getServletPath(); // Route to different policies based on URL path if (httpPath.startsWith("/api/admin")) { return "authz/admin/main"; } else if (httpPath.startsWith("/api/users")) { return "authz/users/main"; } else if (httpPath.startsWith("/api/public")) { return "authz/public/main"; } return "authz/default/main"; }; } } ``` -------------------------------- ### Customize OPA Context with Java Source: https://context7.com/styrainc/opa-springboot/llms.txt Customizes the 'context' portion of the OPA input document. This can involve adding timestamps, day of the week, or request metadata like User-Agent and Origin. It uses the OPAInputContextCustomizer interface. An alternative bean demonstrates how to completely remove the context. ```java import io.github.open_policy_agent.opa.springboot.input.OPAInputContextCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.time.Instant; import java.util.HashMap; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.*; @Configuration public class OPAConfig { @Bean public OPAInputContextCustomizer opaInputContextCustomizer() { return (authentication, requestAuthorizationContext, context) -> { var customContext = new HashMap<>(context); // Add timestamp for time-based policies customContext.put("timestamp", Instant.now().toString()); customContext.put("day_of_week", java.time.LocalDate.now().getDayOfWeek().name()); // Add request metadata var request = requestAuthorizationContext.getRequest(); customContext.put("user_agent", request.getHeader("User-Agent")); customContext.put("origin", request.getHeader("Origin")); return customContext; }; } // Alternative: Remove context entirely from input @Bean public OPAInputContextCustomizer removeContextCustomizer() { return (authentication, requestAuthorizationContext, context) -> null; } } ``` -------------------------------- ### Configure OPAPathSelector Bean in Java Source: https://github.com/styrainc/opa-springboot/blob/main/README.md Defines an OPAPathSelector bean to dynamically select OPA policy paths based on the HTTP request path. This allows for different policy evaluations depending on the request's context. ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import io.github.open_policy_agent.opa.springboot.auth.OPAAuthorizationManager; import io.github.open_policy_agent.opa.springboot.auth.OPAPathSelector; import org.springframework.security.core.Authentication; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; import org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource; import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import javax.servlet.http.HttpServletRequest; @Configuration public class OPAConfig { @Bean public OPAPathSelector opaPathSelector() { return (authentication, requestAuthorizationContext, opaInput) -> { String httpRequestPath = requestAuthorizationContext.getRequest().getServletPath(); if (httpRequestPath.startsWith("/foo")) { return "foo/main"; } else if (httpRequestPath.startsWith("/bar")) { return "bar/main"; } else { return "default/main"; } }; } } ``` -------------------------------- ### Custom OPAClient Bean Configuration Source: https://context7.com/styrainc/opa-springboot/llms.txt This Java configuration defines a custom `OPAClient` bean, allowing for advanced settings like custom authentication headers and HTTP client configurations. This is useful for connecting to OPA servers that require specific authentication tokens or custom network settings. ```java import io.github.open_policy_agent.opa.OPAClient; import io.github.open_policy_agent.opa.springboot.autoconfigure.OPAProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Map; import static java.util.Map.entry; @Configuration public class OPAConfig { @Bean public OPAClient opaClient(OPAProperties opaProperties) { // Configure custom headers for OPA authentication var headers = Map.ofEntries( entry("Authorization", "Bearer my-opa-token"), entry("X-Custom-Header", "custom-value") ); return new OPAClient(opaProperties.getUrl(), headers); } } ``` -------------------------------- ### Implement Authorization Event Listener in Spring Boot Source: https://context7.com/styrainc/opa-springboot/llms.txt This component listens for authorization events published by the OPA SDK. It allows developers to perform audit logging, metrics collection, or trigger alerts when access is granted or denied. ```java import io.github.open_policy_agent.opa.springboot.authorization.OPAAuthorizationDecision; import org.springframework.context.event.EventListener; import org.springframework.security.authorization.event.AuthorizationDeniedEvent; import org.springframework.security.authorization.event.AuthorizationGrantedEvent; import org.springframework.stereotype.Component; @Component public class OPAAuthorizationEventListener { @EventListener public void onDeny(AuthorizationDeniedEvent denied) { var decision = (OPAAuthorizationDecision) denied.getAuthorizationDecision(); var opaResponse = decision.getOpaResponse(); String reason = opaResponse != null ? opaResponse.getReasonForDecision("en") : "unknown"; System.out.println("Access DENIED - Reason: " + reason); System.out.println("Subject: " + denied.getAuthentication().get().getName()); } @EventListener public void onGrant(AuthorizationGrantedEvent granted) { var decision = (OPAAuthorizationDecision) granted.getAuthorizationDecision(); System.out.println("Access GRANTED for: " + granted.getAuthentication().get().getName()); } } ``` -------------------------------- ### Inject Application Data into OPA Context with Java Source: https://context7.com/styrainc/opa-springboot/llms.txt Injects application-specific data into the `input.context.data` field for OPA policies. This is useful for providing business context not directly available from the request or authentication. It uses the ContextDataProvider interface and requires services like UserService and TenantService. ```java import io.github.open_policy_agent.opa.springboot.ContextDataProvider; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Map; @Configuration public class OPAConfig { @Bean public ContextDataProvider contextDataProvider(UserService userService, TenantService tenantService) { return (authenticationSupplier, requestContext) -> { var auth = authenticationSupplier.get(); if (auth == null || !auth.isAuthenticated()) { return Map.of("authenticated", false); } String userId = auth.getName(); // Fetch additional user and tenant data return Map.of( "authenticated", true, "user_profile", userService.getUserProfile(userId), "tenant_config", tenantService.getTenantConfig(userId), "feature_flags", Map.of( "new_dashboard", true, "beta_features", false ) ); }; } } ``` -------------------------------- ### Customize OPA Subject Input with OPAInputSubjectCustomizer Source: https://context7.com/styrainc/opa-springboot/llms.txt Allows modification of the 'subject' section of the OPA input document. Useful for mapping OAuth2 claims, removing sensitive authorities, or injecting custom user attributes into the policy evaluation. ```java import io.github.open_policy_agent.opa.springboot.input.OPAInputSubjectCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import java.util.HashMap; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.*; @Configuration public class OPAConfig { @Bean public OPAInputSubjectCustomizer opaInputSubjectCustomizer() { return (authentication, requestAuthorizationContext, subject) -> { var customSubject = new HashMap<>(subject); // Change subject type for OAuth2 customSubject.put(SUBJECT_TYPE, "oauth2_resource_owner"); // Remove verbose authorities from input customSubject.remove(SUBJECT_AUTHORITIES); // Add custom claims from JWT token if (authentication instanceof JwtAuthenticationToken jwtAuth) { customSubject.put("tenant_id", jwtAuth.getToken().getClaim("tenant_id")); customSubject.put("roles", jwtAuth.getToken().getClaim("roles")); customSubject.put("email", jwtAuth.getToken().getClaim("email")); } return customSubject; }; } } ``` -------------------------------- ### Customize OPA Action with Java Source: https://context7.com/styrainc/opa-springboot/llms.txt Customizes the 'action' portion of the OPA input document. It can modify the action name (e.g., mapping HTTP methods to semantic actions), remove sensitive headers, and add custom attributes like content type. This uses the OPAInputActionCustomizer interface. ```java import io.github.open_policy_agent.opa.springboot.input.OPAInputActionCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.HashMap; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.*; @Configuration public class OPAConfig { @Bean public OPAInputActionCustomizer opaInputActionCustomizer() { return (authentication, requestAuthorizationContext, action) -> { var customAction = new HashMap<>(action); // Remove sensitive headers from OPA input customAction.remove(ACTION_HEADERS); // Map HTTP methods to semantic action names String method = (String) action.get(ACTION_NAME); String semanticAction = switch (method) { case "GET" -> "read"; case "POST" -> "create"; case "PUT", "PATCH" -> "update"; case "DELETE" -> "delete"; default -> method.toLowerCase(); }; customAction.put(ACTION_NAME, semanticAction); // Add content type for write operations var request = requestAuthorizationContext.getRequest(); if (request.getContentType() != null) { customAction.put("content_type", request.getContentType()); } return customAction; }; } } ``` -------------------------------- ### Endpoint Authorization Source: https://github.com/styrainc/opa-springboot/blob/main/docs/reference/input-output-schema.md Defines the structure of the input sent to OPA by the OPA Spring Boot SDK for endpoint authorization requests and the expected output format. ```APIDOC ## Endpoint Authorization ### Description This section details the schema for authorization requests made by the OPA Spring Boot SDK for API endpoints. It covers the structure of the input payload sent to OPA and the expected output format for authorization decisions. ### Method POST ### Endpoint `/v1/data/endpoint/authz` (Example endpoint, actual may vary) ### Parameters #### Query Parameters None #### Request Body ##### Input Schema - **input.resource.type** (String) - Required - A constant describing the type of resource being accessed (`endpoint`). - **input.resource.id** (String) - Required - Endpoint servlet path. - **input.action.name** (String) - Required - HTTP request method (`GET`, `POST`, `PUT`, `PATCH`, `HEAD`, `OPTIONS`, `TRACE`, or `DELETE`). - **input.action.protocol** (String) - Required - HTTP protocol for request (e.g., `HTTP 1.1`). - **input.action.headers** (Map[String, Any]) - Optional - HTTP headers of the request. - **input.context.type** (String) - Required - A constant describing the type of contextual information provided (`http`). - **input.context.host** (String) - Required - HTTP remote host of the request. - **input.context.ip** (String) - Required - HTTP remote IP of the request. - **input.context.port** (String) - Required - HTTP remote port for the request. - **input.context.data** (Map[String, Any]) - Optional - Supplemental data injected via a `ContextDataProvider`. - **input.subject.type** (String) - Required - A constant describing the kind of subject being provided (`java_authentication`). - **input.subject.id** (String) - Required - Spring authentication principal. - **input.subject.details** (String) - Optional - Spring authentication details. - **input.subject.authorities** (String) - Optional - Spring authentication authorities. ### Request Example ```json { "input": { "resource": { "type": "endpoint", "id": "/api/users" }, "action": { "name": "GET", "protocol": "HTTP/1.1" }, "context": { "type": "http", "host": "example.com", "ip": "192.168.1.100", "port": "8080" }, "subject": { "type": "java_authentication", "id": "user123", "details": "some_details", "authorities": "ROLE_USER" } } } ``` ### Response #### Success Response (200) - **output.decision** (Boolean) - Required - `true` if the request should be allowed, `false` otherwise. - **output.context.id** (String) - Required - AuthZEN Reason Object ID. - **output.context.reason_admin** (Map[String, String]) - Optional - AuthZEN Reason Field Object for administrative use. - **output.context.reason_user** (Map[String, String]) - Optional - AuthZEN Reason Field Object for user-facing error messages. - **output.context.data** (Map[String, Any]) - Optional - Supplemental data provided by the OPA policy. #### Response Example ```json { "output": { "decision": true, "context": { "id": "authz-reason-123", "reason_admin": { "code": "ADMIN_CODE", "message": "Admin readable message" }, "reason_user": { "code": "USER_CODE", "message": "User friendly message" }, "data": { "key": "value" } } } } ``` ``` -------------------------------- ### Handle OPAAccessDeniedException with RFC 9457 Response (Java) Source: https://github.com/styrainc/opa-springboot/blob/main/README.md Demonstrates how to implement an AccessDeniedHandler to catch OPAAccessDeniedException and generate an HTTP response compliant with RFC 9457. This handler extracts relevant information from the OPA response to include in the problem details. ```java import com.fasterxml.jackson.databind.ObjectMapper; import io.github.open_policy_agent.opa.springboot.authorization.OPAAccessDeniedException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandlerImpl; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.SUBJECT; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.SUBJECT_ID; @Component public class OPAAccessDeniedHandler extends AccessDeniedHandlerImpl { @Autowired private ObjectMapper objectMapper; @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { if (!(accessDeniedException instanceof OPAAccessDeniedException opaAccessDeniedException)) { super.handle(request, response, accessDeniedException); return; } Map body = new HashMap<>(); body.put("status", HttpStatus.FORBIDDEN.value()); body.put("title", opaAccessDeniedException.getMessage()); var subject = (Map) opaAccessDeniedException.getOpaResponse().getContext().getData().get(SUBJECT); var subjectId = subject.get(SUBJECT_ID); body.put("detail", "Access denied for subject: " + subjectId); body.put("subject", subject); response.setStatus(HttpStatus.FORBIDDEN.value()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.setCharacterEncoding(StandardCharsets.UTF_8.toString()); response.getWriter().write(objectMapper.writeValueAsString(body)); response.getWriter().flush(); } } ``` -------------------------------- ### Customize OPA Input Subject in Java Source: https://github.com/styrainc/opa-springboot/blob/main/README.md Implements OPAInputSubjectCustomizer to modify the 'subject' part of the OPA input map. This allows for dynamic adjustment of subject attributes like type or adding custom keys before policy evaluation. ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import io.github.open_policy_agent.opa.springboot.input.OPAInputSubjectCustomizer; import java.util.HashMap; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.SUBJECT; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.SUBJECT_AUTHORITIES; import static io.github.open_policy_agent.opa.springboot.input.InputConstants.SUBJECT_TYPE; @Configuration public class OPAConfig { @Bean public OPAInputSubjectCustomizer opaInputSubjectCustomizer() { return (authentication, requestAuthorizationContext, subject) -> { var customSubject = new HashMap<>(subject); customSubject.remove(SUBJECT_AUTHORITIES); // Remove an existing attribute. customSubject.put(SUBJECT_TYPE, "oauth2_resource_owner"); // Change an existing attribute. customSubject.put("subject_key", "subject_value"); // Add a new attribute. return customSubject; }; } } ``` -------------------------------- ### Configure OPAAuthorizationManager in Spring Security Source: https://context7.com/styrainc/opa-springboot/llms.txt This Java snippet demonstrates how to configure the OPAAuthorizationManager within a Spring Security configuration class. It integrates OPA's authorization decisions into the HTTP request authorization flow, allowing specific paths to be publicly accessible while others are protected by OPA policies. ```java import io.github.open_policy_agent.opa.springboot.OPAAuthorizationManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { @Autowired OPAAuthorizationManager opaAuthorizationManager; @Bean SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(authorize -> authorize .requestMatchers("/public/**").permitAll() .anyRequest().access(opaAuthorizationManager)); return http.build(); } } ``` -------------------------------- ### Define Authorization Policies in Rego Source: https://context7.com/styrainc/opa-springboot/llms.txt Rego policies for OPA that handle admin access and business hour restrictions. These policies evaluate user authorities and system time to return authorization decisions. ```rego main := result if { is_admin result := { "decision": true, "context": { "id": "admin-access", "reason_user": { "en": "Admin users have full access" }, "data": { "granted_by": "admin_role" } } } } main := result if { not is_business_hours result := { "decision": false, "context": { "id": "outside-hours", "reason_user": { "en": "Access is only permitted during business hours (9 AM - 6 PM)" } } } } is_admin if { "ROLE_ADMIN" in input.subject.authorities[_].authority } is_business_hours if { hour := time.clock(time.now_ns())[0] hour >= 9 hour < 18 } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.