Authorize access to web endpoints

To control which callers can access the web endpoints of a Quarkus application, define authorization rules with security annotations or HTTP security policies for request paths. When security is active, Quarkus checks every HTTP request against these rules to determine whether it can proceed.

Most authorization rules check the roles and permissions of the SecurityIdentity that represents the caller. The security identity provider supplies the roles. To customize them, create a SecurityIdentityAugmentor, as described in Security Identity Customization.

Authorize requests in configuration

To protect paths without a change to the code, define HTTP permissions in the application.properties file. Each permission set names paths, optionally HTTP methods, and the policy that decides whether a request to those paths can proceed.

Be careful when you create complex, possibly overlapping HTTP security policy path expressions. Make sure that there are no typos in the configured policy paths. Be aware that the root path is only prepended to the policy paths that do not start with a forward slash, for more information, see the Permission paths and HTTP root path section. Test your HTTP policy configuration thoroughly, verify that the allowed requests succeed and that the requests with invalid credentials or insufficient permissions are rejected. If you work with Jakarta RESTful Web Services (Jakarta REST) endpoints, prefer standard security annotations to the path-based HTTP security policies.

If you work with Jakarta REST endpoints and need to set default security requirements, prefer using standard security annotations and the quarkus.security.jaxrs.deny-unannotated-endpoints or quarkus.security.jaxrs.default-roles-allowed property instead of HTTP security policy path matching, see Set default access rules for endpoints without annotations. Security annotations can override these properties on an individual Jakarta REST resource or method.

A permission set can use a built-in policy:

Table 1. Quarkus built-in policies
Built-in policy 描述

deny

This policy denies all users.

permit

This policy permits all users.

authenticated

This policy permits only authenticated users.

A permission set can also use a role-based policy that you define, which allows users with specific roles to access the resources:

Example of a role-based policy
quarkus.http.auth.policy.role-policy1.roles-allowed=user,admin                  (1)
1 This defines a role-based policy that allows users with the user role or the admin role.

To apply the policies, reference them from permission sets in the application.properties file:

Example of policy configuration
quarkus.http.auth.policy.role-policy1.roles-allowed=user,admin

quarkus.http.auth.permission.permit1.paths=/public/*                            (1)
quarkus.http.auth.permission.permit1.policy=permit
quarkus.http.auth.permission.permit1.methods=GET

quarkus.http.auth.permission.deny1.paths=/forbidden                             (2)
quarkus.http.auth.permission.deny1.policy=deny

quarkus.http.auth.permission.roles1.paths=/roles-secured/*,/other/*,/api/*      (3)
quarkus.http.auth.permission.roles1.policy=role-policy1
1 This permission references the built-in permit policy to allow GET requests to /public and its sub-paths. Because the permission lists only GET, requests with other methods to the same paths are denied.
2 This permission references the built-in deny policy for both /forbidden and /forbidden/ paths. It is an exact path match because it does not end with *.
3 This permission set references the role-policy1 policy. roles1 is an example name; you can call the permission sets whatever you want.

With this configuration, an anonymous request to /api/orders is rejected with the challenge of the configured authentication mechanism, for example, the HTTP 401 status for Basic authentication, and a request from an authenticated caller that has neither the user role nor the admin role gets the HTTP 403 status.

The exact path pattern /forbidden also secures the /forbidden/ path. This matters because a Jakarta REST endpoint answers both paths, so both paths need to be secured to secure the endpoint. For example, the deny1 permission secures the forbidden endpoint of this resource:

package org.acme.crud;

import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;

@Path("/forbidden")
public class ForbiddenResource {
    @GET
    public String forbidden() {
        return "No!";
    }
}

To permit access to the /forbidden/ path only, add a permission with that more specific exact path:

quarkus.http.auth.permission.permit2.paths=/forbidden/ (1)
quarkus.http.auth.permission.permit2.policy=permit
1 The /forbidden/ path is not secured, while the /forbidden path stays denied.

A permission set can list several paths and several methods, separated by commas. When several permission sets match a request, Quarkus chooses between them as described in Path-matching rules.

A configured HTTP security policy must not contain a semicolon ; character in its paths property. Use a custom HTTP security policy when a security policy decision depends on the presence of certain matrix parameters in the request path.

Write a custom HTTP security policy

When an authorization decision depends on the request itself, implement the io.quarkus.vertx.http.runtime.security.HttpSecurityPolicy interface in an application-scoped CDI bean. A named policy applies only where you assign it. A nameless policy is a global policy, as described later in this section.

package org.acme.http.security;

import jakarta.enterprise.context.ApplicationScoped;

import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.vertx.http.runtime.security.HttpSecurityPolicy;
import io.smallrye.mutiny.Uni;
import io.vertx.ext.web.RoutingContext;

@ApplicationScoped
public class CustomNamedHttpSecPolicy implements HttpSecurityPolicy {
    @Override
    public Uni<CheckResult> checkPermission(RoutingContext event, Uni<SecurityIdentity> identity,
            AuthorizationRequestContext requestContext) {
        if (customRequestAuthorization(event)) {
            return CheckResult.permit();
        }
        return CheckResult.deny();
    }

    @Override
    public String name() {
        return "custom"; (1)
    }

    private static boolean customRequestAuthorization(RoutingContext event) {
        // here comes your own security check
        return !event.request().path().endsWith("denied");
    }
}
1 Named HTTP Security policy will only be applied to the requests that you assign it to, for example, with the application.properties path matching rules.

To assign the named policy to paths, reference it from a permission set:

Example of custom named HttpSecurityPolicy referenced from configuration file
quarkus.http.auth.permission.custom1.paths=/custom/*
quarkus.http.auth.permission.custom1.policy=custom                              (1)
1 Custom policy name must match the value returned by the io.quarkus.vertx.http.runtime.security.HttpSecurityPolicy.name method.

Alternatively, bind the named policy to Jakarta REST endpoints with the @AuthorizationPolicy security annotation:

Example of custom named HttpSecurityPolicy bound to a Jakarta REST endpoint
package org.acme.http.security;

import jakarta.annotation.security.DenyAll;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;

import io.quarkus.vertx.http.security.AuthorizationPolicy;

@DenyAll (1)
@Path("hello")
public class HelloResource {

    @AuthorizationPolicy(name = "custom") (2)
    @GET
    public String hello() {
        return "hello";
    }

}
1 The @AuthorizationPolicy annotation can be used together with other standard security annotations. As usual, the method-level annotation has priority over class-level annotation.
2 Apply custom named HttpSecurityPolicy to the Jakarta REST hello endpoint.

The @AuthorizationPolicy annotation binds only policies that are CDI beans, such as CustomNamedHttpSecPolicy. It cannot bind a role-based policy that you define with quarkus.http.auth.policy. properties.

To create a global HttpSecurityPolicy, do not implement the io.quarkus.vertx.http.runtime.security.HttpSecurityPolicy.name method and leave the policy nameless. When Quarkus authorizes a request to the main HTTP server, it runs every global policy in addition to the permission sets that match the request. The management interface authorizes its requests with the named policies of its own quarkus.management.auth.permission properties, as described in Use HTTP Security Policy to enable path-based authentication.

Inject @RequestScoped beans into HttpSecurityPolicy

A policy can inject @RequestScoped beans only when the CDI request context is active and the beans are prepared. You can activate the context yourself, for example, with the @ActivateRequestContext annotation. However, authorization happens before Quarkus prepares some @RequestScoped beans, such as the Jakarta REST jakarta.ws.rs.core.UriInfo bean.

Instead of activating the context yourself, apply the HttpSecurityPolicy to Jakarta REST endpoints. Quarkus then activates and prepares the CDI request context for you. Use one of the following ways:

  • Use the @AuthorizationPolicy security annotation.

  • Call applyToJaxRs() on the HttpSecurity.HttpPermission when you define the policy programmatically.

  • Set the quarkus.http.auth.permission.custom1.applies-to=jaxrs configuration property. With the jaxrs value, the permission runs after Quarkus matches the request with a Jakarta REST endpoint. The default value is all.

A permission that applies to Jakarta REST endpoints runs after authentication, so it cannot select an authentication mechanism with the auth-mechanism property or the basic() method. To select the authentication mechanism of a Jakarta REST endpoint, annotate the endpoint, for example, with @BasicAuthentication, as described in Use annotations to enable path-based authentication for Jakarta REST endpoints.

Map SecurityIdentity roles

To use deployment-specific role names, map the roles of the SecurityIdentity to other roles. The mapped roles are then applicable for endpoint authorization by using the @RolesAllowed annotation.

The role-based policy that wins the path match for a request can map the roles for that request:

quarkus.http.auth.policy.admin-policy1.roles.admin=Admin1 (1)
quarkus.http.auth.permission.roles1.paths=/* (2)
quarkus.http.auth.permission.roles1.policy=admin-policy1
1 Map the admin role to the Admin1 role. The SecurityIdentity will have both admin and Admin1 roles.
2 The /* path is secured, and only authenticated HTTP requests are granted access, because admin-policy1 does not set the roles-allowed property, and its default value, **, allows any authenticated user.

To map the SecurityIdentity roles to the deployment-specific roles regardless of a path, use the quarkus.http.auth.roles-mapping property:

quarkus.http.auth.roles-mapping.admin=Admin1 (1) (2)
1 Map the admin role to the Admin1 role. The SecurityIdentity will have both admin and Admin1 roles.
2 The /* path is not secured. You must secure your endpoints with standard security annotations or define HTTP permissions in addition to this configuration property.

To add the same mapping programmatically, observe the io.quarkus.vertx.http.security.HttpSecurity CDI event:

package org.acme.http.security;

import jakarta.enterprise.event.Observes;

import io.quarkus.vertx.http.security.HttpSecurity;

public class HttpSecurityConfiguration {

    void configure(@Observes HttpSecurity httpSecurity) {
        httpSecurity.rolesMapping("admin", "Admin1");
    }
}

The quarkus.http.auth.roles-mapping property and the rolesMapping method are mutually exclusive, so use only one of them.

Share permission checks across paths

To apply a permission check to many paths without repeating it in every permission set, mark the permission as shared. Quarkus always applies a shared permission when its path matches, in addition to the most specific unshared permission.

For unshared permission checks, only one path match is applied, the most specific one. When a path matches as the most specific, you can specify multiple permissions for that path and they are all applied.

Example of a custom named HttpSecurityPolicy applied to all paths
quarkus.http.auth.permission.custom1.paths=/*
quarkus.http.auth.permission.custom1.shared=true    (1)
quarkus.http.auth.permission.custom1.policy=custom

quarkus.http.auth.policy.admin-policy1.roles-allowed=admin
quarkus.http.auth.permission.roles1.paths=/admin/*
quarkus.http.auth.permission.roles1.policy=admin-policy1
1 The custom policy named custom is also applied on the /admin/1 path, together with the admin-policy1 policy.
Configuring many shared permission checks is less effective than configuring unshared ones. Use shared permissions to complement unshared permission checks.

For example, use a shared permission to map SecurityIdentity roles for a group of paths:

Map SecurityIdentity roles with shared permission
quarkus.http.auth.policy.role-policy1.roles.root=admin,user (1)
quarkus.http.auth.permission.roles1.paths=/secured/*        (2)
quarkus.http.auth.permission.roles1.policy=role-policy1
quarkus.http.auth.permission.roles1.shared=true

quarkus.http.auth.policy.role-policy2.roles-allowed=user    (3)
quarkus.http.auth.permission.roles2.paths=/secured/user/*
quarkus.http.auth.permission.roles2.policy=role-policy2

quarkus.http.auth.policy.role-policy3.roles-allowed=admin
quarkus.http.auth.permission.roles3.paths=/secured/admin/*
quarkus.http.auth.permission.roles3.policy=role-policy3
1 Role root will be able to access /secured/user/* and /secured/admin/* paths.
2 The /secured/* path can only be accessed by authenticated users. This way, you have secured the /secured/all path and so on.
3 Shared permissions are always applied before unshared ones, therefore a SecurityIdentity with the root role will have the user role as well.

Disable a permission

To turn off a permission without deleting its configuration, set its enabled property to false. The enabled property is runtime configuration, so you can turn the permission set back on without rebuilding the application.

quarkus.http.auth.permission.permit1.enabled=false
quarkus.http.auth.permission.permit1.paths=/public/*,/css/*,/js/*,/robots.txt
quarkus.http.auth.permission.permit1.policy=permit
quarkus.http.auth.permission.permit1.methods=GET,HEAD

To turn the permission set back on at runtime, use a system property or environment variable, such as: -Dquarkus.http.auth.permission.permit1.enabled=true.

Authorize with security annotations

To keep each authorization rule next to the code that it protects, annotate Jakarta REST endpoints and CDI bean methods with security annotations.

Quarkus includes built-in security to allow for Role-Based Access Control (RBAC) based on the common security annotations @RolesAllowed, @DenyAll, and @PermitAll.

Authorization checks for quarkus.http.auth. configurations are performed before security checks for standard security annotations. Therefore, @PermitAll only permits access to paths that are not already restricted by HTTP permissions. @PermitAll cannot override HTTP-level security configurations, only relax restrictions imposed by other standard security annotations such as @RolesAllowed.

Table 2. Quarkus annotation types summary
Annotation type 描述

@DenyAll

Specifies that no security roles are allowed to invoke the specified methods.

@PermitAll

Specifies that all security roles are allowed to invoke the specified methods.

@PermitAll lets everybody in, even without authentication.

@RolesAllowed

Specifies the list of security roles allowed to access methods in an application.

@Authenticated

Quarkus provides the io.quarkus.security.Authenticated annotation that permits any authenticated user to access the resource. It’s equivalent to @RolesAllowed("**").

@PermissionsAllowed

Specifies the list of permissions that are allowed to invoke the specified methods.

@AuthorizationPolicy

Specifies named io.quarkus.vertx.http.runtime.security.HttpSecurityPolicy that should authorize access to the specified Jakarta REST endpoints. Named HttpSecurityPolicy can be used for general authorization checks as demonstrated by Example of custom named HttpSecurityPolicy bound to a Jakarta REST endpoint.

The following SubjectExposingResource example demonstrates an endpoint that uses both Jakarta REST and Common Security annotations to describe and secure its endpoints.

SubjectExposingResource example
package org.acme.security;

import java.security.Principal;

import jakarta.annotation.security.DenyAll;
import jakarta.annotation.security.PermitAll;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.SecurityContext;

import io.quarkus.security.Authenticated;

@Path("subject")
public class SubjectExposingResource {

    @GET
    @Path("secured")
    @RolesAllowed("Tester") (1)
    public String getSubjectSecured(@Context SecurityContext sec) {
        Principal user = sec.getUserPrincipal(); (2)
        String name = user != null ? user.getName() : "anonymous";
        return name;
    }

    @GET
    @Path("authenticated")
    @Authenticated (3)
    public String getSubjectAuthenticated(@Context SecurityContext sec) {
        Principal user = sec.getUserPrincipal();
        String name = user != null ? user.getName() : "anonymous";
        return name;
    }

    @GET
    @Path("unsecured")
    @PermitAll (4)
    public String getSubjectUnsecured(@Context SecurityContext sec) {
        Principal user = sec.getUserPrincipal(); (5)
        String name = user != null ? user.getName() : "anonymous";
        return name;
    }

    @GET
    @Path("denied")
    @DenyAll (6)
    public String getSubjectDenied(@Context SecurityContext sec) {
        Principal user = sec.getUserPrincipal();
        String name = user != null ? user.getName() : "anonymous";
        return name;
    }
}
1 The /subject/secured endpoint requires an authenticated user with the granted "Tester" role through the use of the @RolesAllowed("Tester") annotation.
2 The endpoint obtains the user principal from the Jakarta REST SecurityContext. This returns non-null for a secured endpoint.
3 The /subject/authenticated endpoint allows any authenticated user by specifying the @Authenticated annotation.
4 /subject/unsecured 节点通过使用 @PermitAll 注解来允许未认证的访问。
5 The call to obtain the user principal returns null if the caller is unauthenticated and non-null if the caller is authenticated.
6 The /subject/denied endpoint declares the @DenyAll annotation, disallowing all direct access to it as a REST method, regardless of the user calling it. Calls to the method from other methods in this class are also denied.

If you plan to use standard security annotations on the IO thread, review the information in Proactive Authentication.

The @RolesAllowed annotation value supports property expressions including default values and nested property expressions. Configuration properties used with the annotation are resolved at runtime.

Table 3. Annotation value examples
Annotation Value explanation

@RolesAllowed("${admin-role}")

The endpoint allows users with the role denoted by the value of the admin-role property.

@RolesAllowed("${tester.group}-${tester.role}")

An example showing that the value can contain multiple variables.

@RolesAllowed("${customer:User}")

A default value demonstration. The required role is denoted by the value of the customer property. However, if that property is not specified, a role named User is required as a default.

Example of a property expressions usage in the @RolesAllowed annotation
admin=Administrator
tester.group=Software
tester.role=Tester
%prod.secured=User
%dev.secured=**
all-roles=Administrator,Software,Tester,User
Subject access control example
package org.acme.security;

import java.security.Principal;

import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.SecurityContext;

@Path("subject")
public class SubjectExposingResource {

    @GET
    @Path("admin")
    @RolesAllowed("${admin}") (1)
    public String getSubjectSecuredAdmin(@Context SecurityContext sec) {
        return getUsername(sec);
    }

    @GET
    @Path("software-tester")
    @RolesAllowed("${tester.group}-${tester.role}") (2)
    public String getSubjectSoftwareTester(@Context SecurityContext sec) {
        return getUsername(sec);
    }

    @GET
    @Path("user")
    @RolesAllowed("${customer:User}") (3)
    public String getSubjectUser(@Context SecurityContext sec) {
        return getUsername(sec);
    }

    @GET
    @Path("secured")
    @RolesAllowed("${secured}") (4)
    public String getSubjectSecured(@Context SecurityContext sec) {
        return getUsername(sec);
    }

    @GET
    @Path("list")
    @RolesAllowed("${all-roles}") (5)
    public String getSubjectList(@Context SecurityContext sec) {
        return getUsername(sec);
    }

    private String getUsername(SecurityContext sec) {
        Principal user = sec.getUserPrincipal();
        String name = user != null ? user.getName() : "anonymous";
        return name;
    }
}
1 The @RolesAllowed annotation value is set to the value of Administrator.
2 This /subject/software-tester endpoint requires an authenticated user that has been granted the role of "Software-Tester". It is possible to use multiple expressions in the role definition.
3 This /subject/user endpoint requires an authenticated user that has been granted the role "User" through the use of the @RolesAllowed("${customer:User}") annotation because the configuration property customer is not set.
4 In production, this /subject/secured endpoint requires an authenticated user with the User role. In development mode, it allows any authenticated user.
5 Property expression all-roles will be treated as a collection type List, therefore, the endpoint will be accessible for roles Administrator, Software, Tester and User.

Set default access rules for endpoints without annotations

To avoid accidentally exposing an endpoint that is supposed to be secured, set default requirements for the endpoints and methods that have no security annotations. The following configuration settings alter the role-based access control (RBAC) denying behavior:

quarkus.security.jaxrs.deny-unannotated-endpoints=true|false

If set to true, access is denied for all Jakarta REST endpoints by default. If a Jakarta REST endpoint has no security annotations, it defaults to the @DenyAll behavior. Defaults to false.

quarkus.security.jaxrs.default-roles-allowed=role1,role2

Defines the default role requirements for unannotated endpoints. The ** role is a special role that means any authenticated user. This cannot be combined with deny-unannotated-endpoints because deny takes effect instead.

quarkus.security.deny-unannotated-members=true|false

If set to true, the access is denied to all CDI methods and Jakarta REST endpoints that do not have security annotations but are defined in classes that contain methods with security annotations. Defaults to false.

These are build-time properties.

Secure Jakarta REST endpoints declared in interfaces

When a Jakarta REST endpoint is declared in an interface and implemented in a class, Quarkus supports security annotations placed on the endpoint implementation or its class.

For example, this interface declares the hello endpoint:

package org.acme.security;

import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;

@Path("hello")
public interface HelloInterface {

    @GET
    String hello();

}

This class implements and secures the endpoint:

package org.acme.security;

import jakarta.annotation.security.DenyAll;
import jakarta.annotation.security.RolesAllowed;

@DenyAll (1)
public class HelloInterfaceImpl implements HelloInterface {

    @RolesAllowed("admin") (2)
    @Override
    public String hello() {
        return "Hello";
    }
}
1 Class-level security annotation must be placed on the class where the endpoint implementation is declared.
2 Method-level security annotation must be placed on the endpoint implementation.

The RESTEasy subresource locators declared as default interface methods cannot be secured by standard security annotations. Secured subresource locators must be implemented and secured on the interface implementors like in the example below:

@Path("hello")
public interface HelloInterface {

    @RolesAllowed("admin")
    @Path("sub")
    default HelloSubResource wrongWay() {
        // not supported
    }

    @Path("sub")
    HelloSubResource rightWay();

}

public class HelloInterfaceImpl implements HelloInterface {

    @RolesAllowed("admin")
    @Override
    public HelloSubResource rightWay() {
        return new HelloSubResource();
    }
}

Authorize with permissions

To authorize by what a user is allowed to do rather than by the role of the user, use the io.quarkus.security.PermissionsAllowed annotation. It authorizes any authenticated user with the given permission to access the resource, and checks the permissions granted to a SecurityIdentity instance.

The @PermissionsAllowed annotation is an extension of the common security annotations.

Example of endpoints secured with the @PermissionsAllowed annotation
package org.acme.crud;

import java.security.BasicPermission;
import java.security.Permission;
import java.util.Collection;
import java.util.Collections;

import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.QueryParam;

import io.quarkus.arc.Arc;
import io.quarkus.security.PermissionsAllowed;
import io.vertx.ext.web.RoutingContext;

@Path("/crud")
public class CRUDResource {

    @PermissionsAllowed("create") (1)
    @PermissionsAllowed("update")
    @POST
    @Path("/modify/repeated")
    public String createOrUpdate() {
        return "modified";
    }

    @PermissionsAllowed(value = {"create", "update"}, inclusive=true) (2)
    @POST
    @Path("/modify/inclusive")
    public String createOrUpdate(Long id) {
        return id + " modified";
    }

    @PermissionsAllowed({"see:detail", "see:all", "read"}) (3)
    @GET
    @Path("/id/{id}")
    public String getItem(String id) {
        return "item-detail-" + id;
    }

    @PermissionsAllowed("resource\\:name:action") (4)
    @GET
    @Path("/resource")
    public String getResource() {
        return "resource";
    }

    @PermissionsAllowed(value = "list", permission = CustomPermission.class) (5)
    @Path("/list")
    @GET
    public Collection<String> list(@QueryParam("query-options") String queryOptions) {
        // your business logic comes here
        return Collections.emptySet();
    }

    public static class CustomPermission extends BasicPermission {

        public CustomPermission(String name) {
            super(name);
        }

        @Override
        public boolean implies(Permission permission) {
            var event = Arc.container().instance(RoutingContext.class).get(); (6)
            var publicContent = "public-content".equals(event.request().params().get("query-options"));
            var hasPermission = getName().equals(permission.getName());
            return hasPermission && publicContent;
        }
    }
}
1 The resource method createOrUpdate is only accessible for a user with both create and update permissions.
2 By default, at least one of the permissions specified through one annotation instance is required. You can require all permissions by setting inclusive=true. Both resource methods createOrUpdate have equal authorization requirements.
3 Access is granted to getItem if SecurityIdentity has either read permission or see permission and one of the all or detail actions.
4 The colon separates the permission name from the action. To include a literal colon in the permission name, prefix it with a backslash (\\:). Here, the permission name is resource:name and the action is action. The backslash character is only allowed immediately before a colon. A value with more than one unescaped colon is rejected because there is no way to determine which colon is the separator. A single unescaped colon at the very start or end of the value is treated as part of the name, not as a separator.
5 You can use your preferred java.security.Permission implementation. By default, string-based permission is performed by io.quarkus.security.StringPermission.
6 Permissions are not beans, therefore you obtain bean instances programmatically, for example, by using Arc.container().
If you plan to use the @PermissionsAllowed on the IO thread, review the information in Proactive Authentication.
@PermissionsAllowed is not repeatable on the class level due to a limitation with Quarkus interceptors. For more information, see the Repeatable interceptor bindings section of the Quarkus "CDI reference" guide.

The easiest way to add permissions to a role-enabled SecurityIdentity instance is to map roles to permissions. Use the configuration described in Authorize requests in configuration to grant the required SecurityIdentity permissions for CRUDResource endpoints to authenticated requests, as outlined in the following example:

quarkus.http.auth.policy.role-policy1.permissions.user=see:all                                      (1)
quarkus.http.auth.policy.role-policy1.permissions.admin=create,update,read                          (2)
quarkus.http.auth.permission.roles1.paths=/crud/modify/*,/crud/id/*                                 (3)
quarkus.http.auth.permission.roles1.policy=role-policy1

quarkus.http.auth.policy.role-policy2.permissions.user=list
quarkus.http.auth.policy.role-policy2.permission-class=org.acme.crud.CRUDResource$CustomPermission  (4)
quarkus.http.auth.permission.roles2.paths=/crud/list
quarkus.http.auth.permission.roles2.policy=role-policy2

quarkus.http.auth.policy.role-policy3.permissions.user=resource\\\\:name:action                      (5)
quarkus.http.auth.permission.roles3.paths=/crud/resource
quarkus.http.auth.permission.roles3.policy=role-policy3
1 Add the permission see and the action all to the SecurityIdentity instance of the user role. Similarly, for the @PermissionsAllowed annotation, io.quarkus.security.StringPermission is used by default.
2 Permissions create, update, and read are mapped to the role admin.
3 The role policy role-policy1 allows only authenticated requests to access /crud/modify and /crud/id sub-paths. For more information about the path-matching algorithm, see Longest path wins.
4 You can specify a custom implementation of the java.security.Permission class. Your custom class must define exactly one constructor that accepts the permission name and optionally the actions as a String array. In this scenario, the permission list is added to the SecurityIdentity instance as new CustomPermission("list").
5 To include a literal colon in the permission name, use \\: in the annotation value. In application.properties, use \\\\: because SmallRye Config consumes one level of backslash escaping. Here, the permission name is resource:name and the action is action.
Annotation-based permissions do not work with custom Jakarta REST SecurityContexts because there are no permissions in jakarta.ws.rs.core.SecurityContext.

Pass method arguments to a custom permission

To make the permission decision depend on the arguments of the secured method, create a custom java.security.Permission class with additional constructor parameters. Quarkus matches these parameters by name with the arguments of the method annotated with @PermissionsAllowed.

When the secured method is invoked, Quarkus instantiates your custom permission with the actual arguments.

Example of a custom java.security.Permission class that accepts additional arguments
package org.acme.library;

import java.security.Permission;
import java.util.Arrays;
import java.util.Set;

public class LibraryPermission extends Permission {

    private final Set<String> actions;
    private final Library library;

    public LibraryPermission(String libraryName, String[] actions, Library library) { (1)
        super(libraryName);
        this.actions = Set.copyOf(Arrays.asList(actions));
        this.library = library;
    }

    @Override
    public boolean implies(Permission requiredPermission) {
        if (requiredPermission instanceof LibraryPermission) {
            LibraryPermission that = (LibraryPermission) requiredPermission;
            boolean librariesMatch = getName().equals(that.getName());
            boolean requiredLibraryIsSublibrary = library.isParentLibraryOf(that.library);
            boolean hasOneOfRequiredActions = that.actions.stream().anyMatch(actions::contains);
            return (librariesMatch || requiredLibraryIsSublibrary) && hasOneOfRequiredActions;
        }
        return false;
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof LibraryPermission that && getName().equals(that.getName())
                && actions.equals(that.actions);
    }

    @Override
    public int hashCode() {
        return getName().hashCode();
    }

    @Override
    public String getActions() {
        return String.join(",", actions);
    }

    public static abstract class Library {

        protected String description;

        abstract boolean isParentLibraryOf(Library library);

    }

    public static class MediaLibrary extends Library {

        @Override
        boolean isParentLibraryOf(Library library) {
            return library instanceof MediaLibrary;
        }
    }

    public static class TvLibrary extends MediaLibrary {
        // TvLibrary specific implementation of the 'isParentLibraryOf' method
    }
}
1 There must be exactly one constructor of a custom Permission class. The first parameter is always considered to be a permission name and must be of type String. Quarkus can optionally pass permission actions to the constructor. For this to happen, declare the second parameter as String[].

The LibraryPermission class permits access to the same library or to any of its sublibraries if SecurityIdentity is allowed to perform one of the required actions, for example, read, write, or list.

The following example shows how the LibraryPermission class can be used:

package org.acme.library;

import jakarta.enterprise.context.ApplicationScoped;

import org.acme.library.LibraryPermission.Library;

import io.quarkus.security.PermissionsAllowed;

@ApplicationScoped
public class LibraryService {

    @PermissionsAllowed(value = "tv:write", permission = LibraryPermission.class) (1)
    public Library updateLibrary(String newDesc, Library library) {
        library.description = newDesc;
        return library;
    }

    @PermissionsAllowed(value = "tv:write", permission = LibraryPermission.class) (2)
    @PermissionsAllowed(value = {"tv:read", "tv:list"}, permission = LibraryPermission.class)
    public Library migrateLibrary(Library migrate, Library library) {
        // migrate libraries
        return library;
    }

}
1 The formal parameter library is identified as the parameter matching same-named LibraryPermission constructor parameter. Therefore, Quarkus will pass the library parameter to the LibraryPermission class constructor. However, the LibraryPermission must be instantiated each time the updateLibrary method is invoked.
2 Here, the second Library parameter matches the name library, while the migrate parameter is ignored during the LibraryPermission permission instantiation.
Example of a resource secured with the LibraryPermission
package org.acme.library;

import jakarta.inject.Inject;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;

import org.acme.library.LibraryPermission.Library;

import io.quarkus.security.PermissionsAllowed;

@Path("/library")
public class LibraryResource {

    @Inject
    LibraryService libraryService;

    @PermissionsAllowed(value = "tv:write", permission = LibraryPermission.class)
    @PUT
    @Path("/id/{id}")
    public Library updateLibrary(@PathParam("id") Integer id, Library library) {
        library.description = "updated library " + id;
        return library;
    }

    @PUT
    @Path("/service-way/id/{id}")
    public Library updateLibrarySvc(@PathParam("id") Integer id, Library library) {
        String newDescription = "new description " + id;
        return libraryService.updateLibrary(newDescription, library);
    }

}

Similarly to the CRUDResource example, the following example shows how you can grant a user with the admin role permissions to update MediaLibrary:

package org.acme.library;

import io.quarkus.runtime.annotations.RegisterForReflection;

@RegisterForReflection (1)
public class MediaLibraryPermission extends LibraryPermission {

    public MediaLibraryPermission(String libraryName, String[] actions) {
        super(libraryName, actions, new MediaLibrary());    (2)
    }

}
1 When building a native executable, the permission class must be registered for reflection unless it is also used in at least one io.quarkus.security.PermissionsAllowed#permission attribute. More details about the @RegisterForReflection annotation can be found on the native application tips page.
2 Pass the MediaLibrary instance to the LibraryPermission constructor.
quarkus.http.auth.policy.role-policy3.permissions.admin=media-library:list,media-library:read,media-library:write   (1)
quarkus.http.auth.policy.role-policy3.permission-class=org.acme.library.MediaLibraryPermission
quarkus.http.auth.permission.roles3.paths=/library/*
quarkus.http.auth.permission.roles3.policy=role-policy3
1 Grants the permission media-library, which permits read, write, and list actions. Because MediaLibrary is the TvLibrary class parent, a user with the admin role is also permitted to modify TvLibrary.
The /library/* path can be tested from a Keycloak provider Dev UI page, because the user alice which is created automatically by the Dev Services for Keycloak has an admin role.

Add permissions to a SecurityIdentity programmatically

Besides mapping roles to permissions in configuration, you can add permissions to the SecurityIdentity instance in code. In the following example, SecurityIdentity is customized to add the same permission that the role-based policy grants in Pass method arguments to a custom permission.

Example of adding the LibraryPermission programmatically to SecurityIdentity
package org.acme.library;

import jakarta.enterprise.context.ApplicationScoped;

import io.quarkus.security.identity.AuthenticationRequestContext;
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.security.identity.SecurityIdentityAugmentor;
import io.quarkus.security.runtime.QuarkusSecurityIdentity;
import io.smallrye.mutiny.Uni;

@ApplicationScoped
public class PermissionsIdentityAugmentor implements SecurityIdentityAugmentor {

    @Override
    public Uni<SecurityIdentity> augment(SecurityIdentity identity, AuthenticationRequestContext context) {
        if (isNotAdmin(identity)) {
            return Uni.createFrom().item(identity);
        }
        return Uni.createFrom().item(build(identity));
    }

    private boolean isNotAdmin(SecurityIdentity identity) {
        return identity.isAnonymous() || !"admin".equals(identity.getPrincipal().getName());
    }

    SecurityIdentity build(SecurityIdentity identity) {
        return QuarkusSecurityIdentity.builder(identity)
                .addPermission(new MediaLibraryPermission("media-library", new String[] { "read", "write", "list" })) (1)
                .build();
    }

}
1 Add a media-library permission with read, write, and list actions. Because MediaLibrary is the TvLibrary class parent, the user admin is also permitted to modify TvLibrary.

Create permission checkers

To decide in code whether a caller has a permission, for example, from the arguments of the secured method, mark a CDI bean method with the @PermissionChecker annotation. Then you do not need to grant the permission to the SecurityIdentity in advance. The @PermissionChecker annotation value should match required permission declared by the @PermissionsAllowed annotation value. For example, a permission checker can be created like this:

package org.acme.security.rest.resource;

import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;

import org.jboss.resteasy.reactive.RestForm;
import org.jboss.resteasy.reactive.RestPath;

import io.quarkus.security.PermissionChecker;
import io.quarkus.security.PermissionsAllowed;
import io.quarkus.security.identity.SecurityIdentity;

@Path("/project/{projectName}")
public class ProjectResource {

    @PermissionsAllowed("rename-project") (1)
    @POST
    public String renameProject(@RestPath String projectName, @RestForm String newName) {
        return projectName + " renamed to " + newName;
    }

    @PermissionChecker("rename-project") (2)
    boolean canRenameProject(SecurityIdentity identity, String projectName) { (3) (4)
        var principalName = identity.getPrincipal().getName();
        return projectName.startsWith(principalName + "-"); (5)
    }
}
1 The permission required to access the ProjectResource#renameProject is the rename-project permission.
2 The ProjectResource#canRenameProject method authorizes access to the ProjectResource#renameProject endpoint.
3 The SecurityIdentity instance can be injected into any permission checker method.
4 In this example, the rename-project permission checker is declared on the same resource. However, there is no restriction on where this permission checker can be declared as demonstrated in the next example.
5 In this example, a user owns the projects whose names start with the user name, such as alice-website for the user alice. Replace this check with your own logic.
Permission checker methods can be declared on a normal scoped CDI bean or on a @Singleton bean. The @Dependent CDI bean scope is currently not supported. A Jakarta REST resource class without a scope annotation, such as ProjectResource, is a @Singleton bean.

The permission checker above requires the SecurityIdentity instance to authorize the renameProject endpoint. Instead of declaring the rename-project permission checker directly on the resource, you can declare it on any CDI bean like in this example:

package org.acme.security.rest.resource;

import jakarta.enterprise.context.ApplicationScoped;

import io.quarkus.security.PermissionChecker;
import io.quarkus.security.identity.SecurityIdentity;

@ApplicationScoped (1)
public class ProjectPermissionChecker {

    @PermissionChecker("rename-project")
    boolean canRenameProject(String projectName, SecurityIdentity identity) {   (2)
        var principalName = identity.getPrincipal().getName();
        return projectName.startsWith(principalName + "-");
    }

}
1 A CDI bean with the permission checker must be either a normal scoped bean or a @Singleton bean.
2 The permission checker method must return either boolean or Uni<Boolean>. Private checker methods are not supported.

The build fails when a permission checker method breaks one of these rules, when a @PermissionChecker value matches no @PermissionsAllowed value, or when two permission checkers have the same value.

Permission checks run by default on event loops. Annotate a permission checker method with the io.smallrye.common.annotation.Blocking annotation if you want to run the check on a worker thread.

Matching between the @PermissionsAllowed values and the @PermissionChecker value is based on string equality as shown in the example below:

package org.acme.security;

import java.nio.file.Path;

import jakarta.enterprise.context.ApplicationScoped;

import io.quarkus.security.PermissionChecker;
import io.quarkus.security.PermissionsAllowed;
import io.quarkus.security.identity.SecurityIdentity;

@ApplicationScoped
public class FileService {

    @PermissionsAllowed({ "delete:all", "delete:dir" }) (1)
    void deleteDirectory(Path directoryPath) {
        // delete directory
    }

    @PermissionsAllowed(value = { "delete:service", "delete:file" }, inclusive = true) (2)
    void deleteServiceFile(Path serviceFilePath) {
        // delete service file
    }

    @PermissionChecker("delete:all")
    boolean canDeleteAllDirectories(SecurityIdentity identity) {
        String filePermissions = identity.getAttribute("user-group-file-permissions");
        return filePermissions != null && filePermissions.contains("w");
    }

    @PermissionChecker("delete:service")
    boolean canDeleteService(SecurityIdentity identity) {
        return identity.hasRole("admin");
    }

    @PermissionChecker("delete:file")
    boolean canDeleteFile(Path serviceFilePath) {
        return serviceFilePath != null && !serviceFilePath.endsWith("critical");
    }
}
1 The permission checker method canDeleteAllDirectories grants access to the deleteDirectory because the delete:all values are equal.
2 There must be exactly two permission checker methods, one for the delete:service permission and other for the delete:file permission.

When escaped colons are used, the @PermissionChecker value must be an exact match of the raw @PermissionsAllowed value, including the escape characters:

package org.acme.security;

import jakarta.enterprise.context.ApplicationScoped;

import io.quarkus.security.PermissionChecker;
import io.quarkus.security.PermissionsAllowed;
import io.quarkus.security.identity.SecurityIdentity;

@ApplicationScoped
public class DetailService {

    @PermissionsAllowed("see\\:detail") (1)
    void matched() {
    }

    @PermissionsAllowed("see:detail") (2)
    void notMatched() {
    }

    @PermissionChecker("see\\:detail")
    boolean canAccess(SecurityIdentity identity) {
        return identity.hasRole("admin");
    }
}
1 Matched by the permission checker because both raw annotation values are see\\:detail.
2 Not matched because the raw value see:detail differs from the checker value see\\:detail.

Create permission meta-annotations

To reuse one permission requirement on many methods and classes, put the @PermissionsAllowed annotation on your own annotation. Any method or class that carries your annotation is then secured with that @PermissionsAllowed annotation instance.

For example, a new @CanWrite security annotation can be created like this:

package org.acme.security;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import io.quarkus.security.PermissionsAllowed;

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
@PermissionsAllowed("write") (1)
public @interface CanWrite {

}
1 Any method or class annotated with the @CanWrite annotation is secured with this @PermissionsAllowed annotation instance.

Pass @BeanParam parameters into a permission checker

To use the values of a Jakarta REST jakarta.ws.rs.BeanParam parameter in a permission check, let Quarkus map the fields of the secured method parameters to the parameters of your permission checker or custom permission constructor. For example, consider the following Jakarta REST resource:

package org.acme.security.rest.resource;

import jakarta.ws.rs.BeanParam;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;

import org.acme.security.rest.dto.SimpleBeanParam;

import io.quarkus.security.PermissionsAllowed;

@Path("/hello")
public class HelloResource {

    @PermissionsAllowed(value = "say-hello", params = "beanParam.securityContext.userPrincipal.name") (1)
    @GET
    public String sayHello(@BeanParam SimpleBeanParam beanParam) {
        return "Hello from " + beanParam.uriInfo.getPath();
    }

}
1 The params annotation attribute specifies that user principal name should be passed to the BeanParamPermissionChecker#canSayHello method. Other BeanParamPermissionChecker#canSayHello method parameters like customAuthorizationHeader and query are matched automatically. Quarkus identifies the BeanParamPermissionChecker#canSayHello method parameters among beanParam fields and their public accessors. To avoid ambiguous resolution, automatic detection only looks one level deep, at the beanParam public fields and accessors. For that reason, the path to the user principal name must be specified explicitly.

Where the SimpleBeanParam class is declared like in the example below:

package org.acme.security.rest.dto;

import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.SecurityContext;
import jakarta.ws.rs.core.UriInfo;

public class SimpleBeanParam {

    @HeaderParam("CustomAuthorization")
    private String customAuthorizationHeader;

    @Context
    SecurityContext securityContext;

    @Context
    public UriInfo uriInfo;

    @QueryParam("query")
    public String query;    (1)

    public SecurityContext getSecurityContext() { (2)
        return securityContext;
    }

    public String customAuthorizationHeader() { (3)
        return customAuthorizationHeader;
    }
}
1 Quarkus Security passes public fields directly.
2 Quarkus Security automatically uses public getter methods if they are available.
3 The customAuthorizationHeader field is not public, therefore Quarkus accesses this field with the customAuthorizationHeader accessor. That is particularly useful with Java records, where generated accessors are not prefixed with get.

Here is an example of a @PermissionChecker method that checks the say-hello permission based on a user principal, custom header and query parameter:

package org.acme.security.permission;

import jakarta.enterprise.context.ApplicationScoped;

import io.quarkus.security.PermissionChecker;

@ApplicationScoped
public class BeanParamPermissionChecker {

    @PermissionChecker("say-hello")
    boolean canSayHello(String customAuthorizationHeader, String name, String query) {
        boolean queryParamAllowedForPermissionName = checkQueryParams(query);
        boolean usernameWhitelisted = isUserNameWhitelisted(name);
        boolean customAuthorizationMatches = checkCustomAuthorization(customAuthorizationHeader);
        return queryParamAllowedForPermissionName && usernameWhitelisted && customAuthorizationMatches;
    }

    // here come your own checks
    private static boolean checkQueryParams(String query) {
        return "hi".equals(query);
    }

    private static boolean isUserNameWhitelisted(String name) {
        return "alice".equals(name);
    }

    private static boolean checkCustomAuthorization(String customAuthorizationHeader) {
        return "yes".equals(customAuthorizationHeader);
    }
}
You can pass @BeanParam directly into a @PermissionChecker method and access its fields programmatically. Ability to reference @BeanParam fields with the @PermissionsAllowed#params attribute is useful when you have multiple differently structured @BeanParam classes.

Path-matching rules

Quarkus chooses the permission sets that apply to a request by comparing the request path and method with the paths and methods of each permission set. When several match, the one with the most specific path wins.

The rules in this section decide which path is the most specific.

Paths and methods

If a path ends with the * wildcard, the query it generates matches all sub-paths. Otherwise, it queries for an exact match and only matches that specific path:

quarkus.http.auth.permission.permit1.paths=/public*,/css/*,/js/*,/robots.txt    (1)
quarkus.http.auth.permission.permit1.policy=permit
quarkus.http.auth.permission.permit1.methods=GET,HEAD
1 The * wildcard at the end of the path matches zero or more path segments, but never any word starting from the /public path. For that reason, a path like /public-info is not matched by this pattern. The /public* pattern is the same as the /public/* pattern.

Requests with an unlisted method

The request is rejected if it matches one or more permission sets based on the path but none of the required methods. An anonymous request is rejected with the challenge of the configured authentication mechanism, for example, the HTTP 401 status for Basic authentication, and an authenticated request gets the HTTP 403 status. When no authentication mechanism is active, the anonymous request also gets the HTTP 403 status.

For example, with the permit1 permission set from Paths and methods, GET /public/foo matches both the path and method and is therefore allowed. In contrast, POST /public/foo matches the path but not the method, and is therefore rejected.

Longest path wins

Matching is always done on the "longest path wins" basis. Less specific permission sets are not considered if a more specific one has been matched:

quarkus.http.auth.permission.permit1.paths=/public/*
quarkus.http.auth.permission.permit1.policy=permit
quarkus.http.auth.permission.permit1.methods=GET,HEAD

quarkus.http.auth.permission.deny1.paths=/public/forbidden-folder/*
quarkus.http.auth.permission.deny1.policy=deny

With this configuration, GET /public/forbidden-folder/foo matches the paths of both permission sets. However, because the longer path matches the path of the deny1 permission set, deny1 is chosen, and the request is rejected.

Subpath permissions precede root path permissions, as the deny1 versus permit1 permission example shows. This rule also applies when a subpath permission allows access to a public resource while the root path permission requires authorization:

quarkus.http.auth.policy.user-policy.roles-allowed=user
quarkus.http.auth.permission.roles.paths=/api/*
quarkus.http.auth.permission.roles.policy=user-policy

quarkus.http.auth.permission.public.paths=/api/noauth/*
quarkus.http.auth.permission.public.policy=permit

Wildcards inside a path: longest path to the * wildcard wins

A path that ends with the * wildcard matches all sub-paths. A trailing wildcard can follow other characters, but it still matches only whole path segments. For example, /three/fo* is an alias for /three/fo/*, so it matches /three/fo and /three/fo/bar, but not /three/foo. The wildcard can also be applied in the middle of a path, representing a single path segment. An inner wildcard must occupy a whole segment, so path separators always enclose it, as seen in the /public/*/about-us path. A path such as /api/v*/detail is not allowed.

When several path patterns correspond to the same request path, the system selects the longest sub-path leading to the * wildcard. In this context, every path segment character is more specific than the * wildcard.

Here is a simple example:

quarkus.http.auth.permission.secured.paths=/api/*/detail                    (1)
quarkus.http.auth.permission.secured.policy=authenticated
quarkus.http.auth.permission.public.paths=/api/public-product/detail        (2)
quarkus.http.auth.permission.public.policy=permit
1 Request paths like /api/product/detail can only be accessed by authenticated users.
2 The path /api/public-product/detail is more specific, therefore accessible by anyone.

Test all paths that you secure with HTTP security policies. Writing path patterns with multiple wildcards can be cumbersome, so make sure that each path is authorized as you intend.

In the following example, paths are ordered from the most specific to the least specific one:

Request path /one/two/three/four/five matches ordered from the most specific to the least specific path
/one/two/three/four/five
/one/two/three/four/*
/one/two/three/*/five
/one/two/three/*/*
/one/two/*/four/five
/one/*/three/four/five
/*/two/three/four/five
/*/two/three/*/five
/*

The * wildcard at the end of the path matches zero or more path segments. The * wildcard placed anywhere else matches exactly one path segment.

Most specific method wins

When a path is registered with multiple permission sets, the permission sets explicitly specifying an HTTP method that matches the request take precedence. In this instance, the permission sets without methods only come into effect if the request method does not match permission sets with the method specification.

quarkus.http.auth.permission.permit1.paths=/public/*
quarkus.http.auth.permission.permit1.policy=permit
quarkus.http.auth.permission.permit1.methods=GET,HEAD

quarkus.http.auth.permission.deny1.paths=/public/*
quarkus.http.auth.permission.deny1.policy=deny

With this configuration, GET /public/foo matches the paths of both permission sets. However, it specifically aligns with the explicit method of the permit1 permission set. Therefore, permit1 is selected, and the request is accepted.

In contrast, PUT /public/foo does not match the method permissions of permit1. As a result, deny1 is activated, leading to the rejection of the request.

Several winning permission sets: all must permit

Sometimes, these rules allow multiple permission sets to win simultaneously. In that case, for the request to proceed, all the permissions must allow access. For this to happen, both must either have specified the method or have no method. Method-specific matches take precedence.

quarkus.http.auth.policy.user-policy1.roles-allowed=user
quarkus.http.auth.policy.admin-policy1.roles-allowed=admin

quarkus.http.auth.permission.roles1.paths=/api/*,/restricted/*
quarkus.http.auth.permission.roles1.policy=user-policy1

quarkus.http.auth.permission.roles2.paths=/api/*,/admin/*
quarkus.http.auth.permission.roles2.policy=admin-policy1

With this configuration, GET /api/foo matches the paths of both permission sets, so it requires both the user and admin roles.

Permission paths and HTTP root path

The quarkus.http.root-path configuration property changes the http endpoint context path.

By default, quarkus.http.root-path is prepended automatically to configured permission paths that do not start with a forward slash, for example:

quarkus.http.auth.permission.permit1.paths=public/*,css/*,js/*,robots.txt

该配置相当于以下内容:

quarkus.http.auth.permission.permit1.paths=${quarkus.http.root-path}/public/*,${quarkus.http.root-path}/css/*,${quarkus.http.root-path}/js/*,${quarkus.http.root-path}/robots.txt

A leading slash changes how the configured permission path is interpreted. The configured URL is used as-is, and paths are not adjusted if the value of quarkus.http.root-path changes.

Example:
quarkus.http.auth.permission.permit1.paths=/public/*,css/*,js/*,robots.txt

This configuration only impacts resources served from the fixed or static URL, /public, which might not match your application resources if quarkus.http.root-path has been set to something other than /.

For more information, see Path Resolution in Quarkus.

Set up path-specific authorization programmatically

To set up path rules in code, for example, from configuration values that your code reads, observe the io.quarkus.vertx.http.security.HttpSecurity CDI event. Quarkus fires this event when the runtime configuration is ready.

You can also configure the authorization policies from Authorize requests in configuration programmatically. For example, consider this configuration:

quarkus.http.auth.permission.permit1.paths=/public/*
quarkus.http.auth.permission.permit1.policy=permit
quarkus.http.auth.permission.permit1.methods=GET

quarkus.http.auth.permission.deny1.paths=/forbidden
quarkus.http.auth.permission.deny1.policy=deny

quarkus.http.auth.permission.roles1.paths=/roles-secured/*,/other/*,/api/*
quarkus.http.auth.permission.roles1.policy=role-policy1
quarkus.http.auth.policy.role-policy1.roles-allowed=user,admin

The same authorization policies can be configured programmatically:

package org.acme.http.security;

import jakarta.enterprise.event.Observes;

import io.quarkus.vertx.http.security.HttpSecurity;

public class HttpSecurityConfiguration {

    void configure(@Observes HttpSecurity httpSecurity) {
        httpSecurity
                .get("/public/*").permit()
                .path("/roles-secured/*", "/other/*", "/api/*").roles("admin", "user")
                .path("/forbidden").authorization().deny();
    }

}

The HttpSecurity CDI event can also select the authentication mechanism and the policy for each path:

package org.acme.http.security;

import jakarta.enterprise.event.Observes;

import org.eclipse.microprofile.config.inject.ConfigProperty;

import io.quarkus.vertx.http.security.Form;
import io.quarkus.vertx.http.security.HttpSecurity;

public class HttpSecurityConfiguration {

    void configure(@Observes HttpSecurity httpSecurity, CustomNamedHttpSecPolicy customHttpSecurityPolicy,
                        @ConfigProperty(name = "secured-path") String securedPath) {

        httpSecurity.basic().mechanism(Form.create()); (1)

        httpSecurity.path("/other/*").basic().policy(customHttpSecurityPolicy); (2)

        httpSecurity.path("/roles-secured/*").bearer().authorization()
                .policy(identity -> identity.hasRole("user") || "root".equals(identity.getPrincipal().getName()));  (3)

        httpSecurity.path("/other/administration").authorizationCodeFlow()
                .authorization().policy((identity, routingContext) -> {
                    if (!identity.isAnonymous()) {
                        String customAuthorization = routingContext.request().getHeader("Custom-Authorization");
                        return isAllowed(customAuthorization);
                    }
                    return false;
                });     (4)

        httpSecurity.path(securedPath).form();  (5)

        httpSecurity.path("/user-info").bearer().authorization().permissions("openid", "email", "profile"); (6)
    }

    private static boolean isAllowed(String customAuthorization) {
        // here comes your own security check
        return "allowed".equals(customAuthorization);
    }
}
1 Register the Basic and form-based authentication mechanisms, so that the paths in this example can select them.
2 Use the Basic authentication and authorize the requests with your own io.quarkus.vertx.http.runtime.security.HttpSecurityPolicy, such as the CustomNamedHttpSecPolicy bean from Write a custom HTTP security policy. A policy that is a CDI bean without a name is also a global policy. To apply a policy only to this path, give the bean a name, as CustomNamedHttpSecPolicy does, or do not declare the class as a CDI bean and pass an instance created with new.
3 Use the Bearer token authentication and authorize the SecurityIdentity with your own policy. Bearer token authentication requires the quarkus-oidc, quarkus-smallrye-jwt, or quarkus-elytron-security-oauth2 extension.
4 Use Authorization Code Flow mechanism, which requires the quarkus-oidc extension, and write your own policy based on incoming request headers. A policy with this signature also runs for anonymous requests, so it checks for them first.
5 When Quarkus fires the HttpSecurity CDI event, the runtime configuration is ready, so you can inject configuration properties.
6 Require that all the requests to the /user-info path have string permissions openid, email and profile. The same authorization can be required with the @PermissionsAllowed(value = { "openid", "email", "profile" }, inclusive = true) annotation instance placed on an endpoint.

When permissions from the application.properties file and from the HttpSecurity event match the same request, the path-matching rules decide between them: the more specific permission wins, whether it has the longer path or lists the request method. Both permissions apply only when they are equally specific, as described in Several winning permission sets: all must permit, or when one of them is a shared permission. Programmatic setup for the management interface is not supported.