Quarkus - Quarkus Extension for Spring Security API

While users are encouraged to use Java standard annotations for security authorizations, Quarkus provides a compatibility layer for Spring Security in the form of the spring-security extension.

This guide explains how a Quarkus application can leverage the well known Spring Security annotations to define authorizations on RESTful services using roles.

This technology is considered preview.

In preview, backward compatibility and presence in the ecosystem is not guaranteed. Specific improvements might require to change configuration or APIs and plans to become stable are under way. Feedback is welcome on our mailing list or as issues in our GitHub issue tracker.

For a full list of possible extension statuses, check our FAQ entry.

Prerequisites

To complete this guide, you need:

  • less than 15 minutes

  • an IDE

  • JDK 1.8+ installed with JAVA_HOME configured appropriately

  • Apache Maven 3.6.2+

  • Some familiarity with the Spring Web extension

Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

Clone the Git repository: git clone [https://github.com/quarkusio/quarkus-quickstarts.git](https://github.com/quarkusio/quarkus-quickstarts.git), or download an archive.

The solution is located in the spring-security-quickstart directory.

Creating the Maven project

First, we need a new project. Create a new project with the following command:

  1. mvn io.quarkus:quarkus-maven-plugin:1.7.6.Final:create \
  2. -DprojectGroupId=org.acme \
  3. -DprojectArtifactId=spring-security-quickstart \
  4. -DclassName="org.acme.spring.security.GreetingController" \
  5. -Dpath="/greeting" \
  6. -Dextensions="spring-web, spring-security, quarkus-elytron-security-properties-file"
  7. cd spring-security-quickstart

This command generates a Maven project with a REST endpoint and imports the spring-web, spring-security and security-properties-file extensions.

If you already have your Quarkus project configured, you can add the spring-web, spring-security and security-properties-file extensions to your project by running the following command in your project base directory:

  1. ./mvnw quarkus:add-extension -Dextensions="spring-web, spring-security, quarkus-elytron-security-properties-file"

This will add the following to your pom.xml:

  1. <dependency>
  2. <groupId>io.quarkus</groupId>
  3. <artifactId>quarkus-spring-web</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>io.quarkus</groupId>
  7. <artifactId>quarkus-spring-security</artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>io.quarkus</groupId>
  11. <artifactId>quarkus-elytron-security-properties-file</artifactId>
  12. </dependency>

For more information about security-properties-file, you can check out the guide of the quarkus-elytron-security-properties-file extension.

GreetingController

The Quarkus Maven plugin automatically generated a controller with the Spring Web annotations to define our REST endpoint (instead of the JAX-RS ones used by default). The src/main/java/org/acme/spring/web/GreetingController.java file looks as follows:

  1. package org.acme.spring.security;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. @RestController
  6. @RequestMapping("/greeting")
  7. public class GreetingController {
  8. @GetMapping
  9. public String hello() {
  10. return "hello";
  11. }
  12. }

GreetingControllerTest

Note that a test for the controller has been created as well:

  1. package org.acme.spring.security;
  2. import io.quarkus.test.junit.QuarkusTest;
  3. import org.junit.jupiter.api.Test;
  4. import static io.restassured.RestAssured.given;
  5. import static org.hamcrest.CoreMatchers.is;
  6. @QuarkusTest
  7. public class GreetingControllerTest {
  8. @Test
  9. public void testHelloEndpoint() {
  10. given()
  11. .when().get("/greeting")
  12. .then()
  13. .statusCode(200)
  14. .body(is("hello"));
  15. }
  16. }

Package and run the application

Run the application with: ./mvnw quarkus:dev. Open your browser to http://localhost:8080/greeting.

The result should be: {"message": "hello"}.

Modify the controller to secure the hello method

In order to restrict access to the hello method to users with certain roles, the @Secured annotation will be utilized. The updated controller will be:

  1. package org.acme.spring.security;
  2. import org.springframework.security.access.annotation.Secured;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. @RestController
  7. @RequestMapping("/greeting")
  8. public class GreetingController {
  9. @Secured("admin")
  10. @GetMapping
  11. public String hello() {
  12. return "hello";
  13. }
  14. }

The easiest way to setup users and roles for our example is to use the security-properties-file extension. This extension essentially allows users and roles to be defined in the main Quarkus configuration file - application.properties. For more information about this extension check the associated guide. An example configuration would be the following:

  1. quarkus.security.users.embedded.enabled=true
  2. quarkus.security.users.embedded.plain-text=true
  3. quarkus.security.users.embedded.users.scott=jb0ss
  4. quarkus.security.users.embedded.roles.scott=admin,user
  5. quarkus.security.users.embedded.users.stuart=test
  6. quarkus.security.users.embedded.roles.stuart=user

Note that the test also needs to be updated. It could look like:

GreetingControllerTest

  1. package org.acme.spring.security;
  2. import io.quarkus.test.junit.QuarkusTest;
  3. import org.junit.jupiter.api.Test;
  4. import static io.restassured.RestAssured.given;
  5. import static org.hamcrest.CoreMatchers.is;
  6. @QuarkusTest
  7. public class GreetingControllerTest {
  8. @Test
  9. public void testHelloEndpointForbidden() {
  10. given().auth().preemptive().basic("stuart", "test")
  11. .when().get("/greeting")
  12. .then()
  13. .statusCode(403);
  14. }
  15. @Test
  16. public void testHelloEndpoint() {
  17. given().auth().preemptive().basic("scott", "jb0ss")
  18. .when().get("/greeting")
  19. .then()
  20. .statusCode(200)
  21. .body(is("hello"));
  22. }
  23. }

Test the changes

Access allowed

Open your browser again to http://localhost:8080/greeting and introduce scott and jb0ss in the dialog displayed.

The word hello should be displayed.

Access forbidden

Open your browser again to http://localhost:8080/greeting and let empty the dialog displayed.

The result should be:

  1. Access to localhost was denied
  2. You don't have authorization to view this page.
  3. HTTP ERROR 403

Run the application as a native executable

You can of course create a native image using the instructions of the Building a native executable guide.

Supported Spring Security functionalities

Quarkus currently only supports a subset of the functionalities that Spring Security provides with more features being planned. More specifically, Quarkus supports the security related features of role-based authorization semantics (think of @Secured instead of @RolesAllowed).

Annotations

The table below summarizes the supported annotations:

Table 1. Supported Spring Security annotations
NameComments

@Secured

@PreAuthorize

See next section for more details

@PreAuthorize

Quarkus provides support for some of the most used features of Spring Security’s @PreAuthorize annotation. The expressions that are supported are the following:

hasRole

To test if the current user has a specific role, the hasRole expression can be used inside @PreAuthorize.

Some examples are: @PreAuthorize("hasRole('admin')"), @PreAuthorize("hasRole(@roles.USER)") where the roles is a bean that could be defined like so:

  1. import org.springframework.stereotype.Component;
  2. @Component
  3. public class Roles {
  4. public final String ADMIN = "admin";
  5. public final String USER = "user";
  6. }

hasAnyRole

In the same fashion as hasRole, users can use hasAnyRole to check if the logged in user has any of the specified roles.

Some examples are: @PreAuthorize("hasAnyRole('admin')"), @PreAuthorize("hasAnyRole(@roles.USER, 'view')")

permitAll

Adding @PreAuthorize("permitAll()") to a method will ensure that that method is accessible by any user (including anonymous users). Adding it to a class will ensure that all public methods of the class that are not annotated with any other Spring Security annotation will be accessible.

denyAll

Adding @PreAuthorize("denyAll()") to a method will ensure that that method is not accessible by any user. Adding it to a class will ensure that all public methods of the class that are not annotated with any other Spring Security annotation will not be accessible to any user.

isAnonymous

When annotating a bean method with @PreAuthorize("isAnonymous()") the method will only be accessible if the current user is anonymous - i.e. a non logged in user.

isAuthenticated

When annotating a bean method with @PreAuthorize("isAuthenticated()") the method will only be accessible if the current user is a logged in user. Essentially the method is only unavailable for anonymous users.

paramName == authentication.principal.username

This syntax allows users to check if a parameter (or a field of the parameter) of the secured method is equal to the logged in username.

Examples of this use case are:

  1. public class Person {
  2. private final String name;
  3. public Person(String name) {
  4. this.name = name;
  5. }
  6. public String getName() {
  7. return name;
  8. }
  9. }
  10. @Component
  11. public class MyComponent {
  12. @PreAuthorize("#username == authentication.principal.username") (1)
  13. public void doSomething(String username, String other){
  14. }
  15. @PreAuthorize("#person.name == authentication.principal.username") (2)
  16. public void doSomethingElse(Person person){
  17. }
  18. }
1doSomething can be executed if the current logged in user is the same as the username method parameter
2doSomethingElse can be executed if the current logged in user is the same as the name field of person method parameter
the use of authentication. is optional, so using principal.username has the same result.

paramName != authentication.principal.username

This is similar to the previous expression with the difference being that the method parameter must be different than the logged in username.

@beanName.method()

This syntax allows developers to specify that the execution of method of a specific bean will determine if the current user can access the secured method.

The syntax is best explained with an example. Let’s assume that a MyComponent bean has been created like so:

  1. @Component
  2. public class MyComponent {
  3. @PreAuthorize("@personChecker.check(#person, authentication.principal.username)")
  4. public void doSomething(Person person){
  5. }
  6. }

The doSomething method has been annotated with @PreAuthorize using an expression that indicates that method check of a bean named personChecker needs to be invoked to determine whether the current user is authorized to invoke the doSomething method.

An example of the PersonChecker could be:

  1. @Component
  2. public class PersonChecker {
  3. @Override
  4. public boolean check(Person person, String username) {
  5. return person.getName().equals(username);
  6. }
  7. }

Note that for the check method the parameter types must match what is specified in @PreAuthorize and that the return type must be a boolean.

Combining expressions

The @PreAuthorize annotations allows for the combination of expressions using logical AND / OR. Currently there is a limitation where only a single logical operation can be used (meaning mixing AND and OR isn’t allowed).

Some examples of allowed expressions are:

  1. @PreAuthorize("hasAnyRole('user', 'admin') AND #user == principal.username")
  2. public void allowedForUser(String user) {
  3. }
  4. @PreAuthorize("hasRole('user') OR hasRole('admin')")
  5. public void allowedForUserOrAdmin() {
  6. }
  7. @PreAuthorize("hasAnyRole('view1', 'view2') OR isAnonymous() OR hasRole('test')")
  8. public void allowedForAdminOrAnonymous() {
  9. }

Also to be noted that currently parentheses are not supported and expressions are evaluated from left to right when needed.

Important Technical Note

Please note that the Spring support in Quarkus does not start a Spring Application Context nor are any Spring infrastructure classes run. Spring classes and annotations are only used for reading metadata and / or are used as user code method return types or parameter types. What that means for end users, is that adding arbitrary Spring libraries will not have any effect. Moreover Spring infrastructure classes (like org.springframework.beans.factory.config.BeanPostProcessor for example) will not be executed.

Conversion Table

The following table shows how Spring Security annotations can be converted to JAX-RS annotations.

SpringJAX-RSComments

@Secured(“admin”)

@RolesAllowed(“admin”)

More Spring guides

Quarkus has more Spring compatibility features. See the following guides for more details: