Getting started with security
Abstract
Providing feedback on Red Hat build of Quarkus documentation Copy linkLink copied to clipboard!
To report an error or to improve our documentation, log in to your Red Hat Jira account and submit an issue. If you do not have a Red Hat Jira account, then you will be prompted to create an account.
Procedure
- Click the following link to create a ticket.
- Enter a brief description of the issue in the Summary.
- Provide a detailed description of the issue or enhancement in the Description. Include a URL to where the issue occurs in the documentation.
- Clicking Submit creates and routes the issue to the appropriate documentation team.
Making open source more inclusive Copy linkLink copied to clipboard!
Red Hat is committed to replacing problematic language in our code, documentation, and web properties. We are beginning with these four terms: master, slave, blacklist, and whitelist. Because of the enormity of this endeavor, these changes will be implemented gradually over several upcoming releases. For more details, see our CTO Chris Wright’s message.
Chapter 1. Getting started with Security by using Basic authentication and Jakarta Persistence Copy linkLink copied to clipboard!
Get started with Quarkus Security by securing your Quarkus application endpoints with the built-in Quarkus Basic authentication and the Jakarta Persistence identity provider, enabling role-based access control.
The Jakarta Persistence IdentityProvider verifies and converts a Basic authentication user name and password pair to a SecurityIdentity instance, which is used to authorize access requests, making your Quarkus application secure.
For more information about Jakarta Persistence, see the Quarkus Security with Jakarta Persistence guide.
This tutorial prepares you to implement more advanced security mechanisms in Quarkus, for example, how to use the OpenID Connect (OIDC) authentication mechanism.
1.1. Prerequisites Copy linkLink copied to clipboard!
To complete this guide, you need:
- Roughly 15 minutes
- An IDE
-
JDK 17+ installed with
JAVA_HOMEconfigured appropriately - Apache Maven 3.9.6
- Optionally the Quarkus CLI if you want to use it
- Optionally Mandrel or GraalVM installed and configured appropriately if you want to build a native executable (or Docker if you use a native container build)
1.2. Building your application Copy linkLink copied to clipboard!
This tutorial gives detailed steps for creating an application with endpoints that illustrate various authorization policies:
| Endpoint | Description |
|---|---|
|
| Accessible without authentication, this endpoint allows anonymous access. |
|
|
Secured with role-based access control (RBAC), this endpoint is accessible only to users with the |
|
|
Also secured by RBAC, this endpoint is accessible only to users with the |
To examine the completed example, download the archive or clone the Git repository:
git clone https://github.com/quarkusio/quarkus-quickstarts.git -b 3.8
git clone https://github.com/quarkusio/quarkus-quickstarts.git -b 3.8
You can find the solution in the security-jpa-quickstart directory.
1.3. Create and verify the Maven project Copy linkLink copied to clipboard!
For Quarkus Security to be able to map your security source to Jakarta Persistence entities, ensure that the Maven project in this tutorial includes the quarkus-security-jpa extension.
Hibernate ORM with Panache is used to store your user identities, but you can also use Hibernate ORM with the quarkus-security-jpa extension.
You must also add your preferred database connector library. The instructions in this example tutorial use a PostgreSQL database for the identity store.
1.3.1. Create the Maven project Copy linkLink copied to clipboard!
You can create a new Maven project with the Security Jakarta Persistence extension or add the extension to an existing Maven project. You can use either Hibernate ORM or Hibernate Reactive.
To create a new Maven project with the Jakarta Persistence extension, complete one of the following steps:
- To create the Maven project with Hibernate ORM, use the following command:
Using the Quarkus CLI:
quarkus create app org.acme:security-jpa-quickstart \ --extension='security-jpa,jdbc-postgresql,resteasy-reactive,hibernate-orm-panache' \ --no-code cd security-jpa-quickstartquarkus create app org.acme:security-jpa-quickstart \ --extension='security-jpa,jdbc-postgresql,resteasy-reactive,hibernate-orm-panache' \ --no-code cd security-jpa-quickstartCopy to Clipboard Copied! Toggle word wrap Toggle overflow To create a Gradle project, add the
--gradleor--gradle-kotlin-dsloption.For more information about how to install and use the Quarkus CLI, see the Quarkus CLI guide.
Using Maven:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow To create a Gradle project, add the
-DbuildTool=gradleor-DbuildTool=gradle-kotlin-dsloption.
For Windows users:
-
If using cmd, (don’t use backward slash
\and put everything on the same line) If using Powershell, wrap
-Dparameters in double quotes e.g."-DprojectArtifactId=security-jpa-quickstart"To add the Jakarta Persistence extension to an existing Maven project, complete one of the following steps:
To add the Security Jakarta Persistence extension to an existing Maven project with Hibernate ORM, run the following command from your project base directory:
Using the Quarkus CLI:
quarkus extension add security-jpa
quarkus extension add security-jpaCopy to Clipboard Copied! Toggle word wrap Toggle overflow Using Maven:
./mvnw quarkus:add-extension -Dextensions='security-jpa'
./mvnw quarkus:add-extension -Dextensions='security-jpa'Copy to Clipboard Copied! Toggle word wrap Toggle overflow Using Gradle:
./gradlew addExtension --extensions='security-jpa'
./gradlew addExtension --extensions='security-jpa'Copy to Clipboard Copied! Toggle word wrap Toggle overflow
1.3.2. Verify the quarkus-security-jpa dependency Copy linkLink copied to clipboard!
After you have run either of the preceding commands to create the Maven project, verify that the quarkus-security-jpa dependency was added to your project build XML file.
To verify the
quarkus-security-jpaextension, check for the following configuration:Using Maven:
<dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-security-jpa</artifactId> </dependency><dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-security-jpa</artifactId> </dependency>Copy to Clipboard Copied! Toggle word wrap Toggle overflow Using Gradle:
implementation("io.quarkus:quarkus-security-jpa")implementation("io.quarkus:quarkus-security-jpa")Copy to Clipboard Copied! Toggle word wrap Toggle overflow
1.4. Write the application Copy linkLink copied to clipboard!
Secure the API endpoint to determine who can access the application by using one of the following approaches:
Implement the
/api/publicendpoint to allow all users access to the application. Add a regular Jakarta REST resource to your Java source code, as shown in the following code snippet:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Implement an /api/admin endpoint that can only be accessed by users who have the admin role. The source code for the
/api/adminendpoint is similar, but instead, you use a@RolesAllowedannotation to ensure that only users granted theadminrole can access the endpoint. Add a Jakarta REST resource with the following@RolesAllowedannotation:Copy to Clipboard Copied! Toggle word wrap Toggle overflow Implement an
/api/users/meendpoint that can only be accessed by users who have theuserrole. UseSecurityContextto get access to the currently authenticatedPrincipaluser and to return their username, all of which is retrieved from the database.Copy to Clipboard Copied! Toggle word wrap Toggle overflow
1.5. Define the user entity Copy linkLink copied to clipboard!
-
You can now describe how you want security information to be stored in the model by adding annotations to the
userentity, as outlined in the following code snippet:
The quarkus-security-jpa extension only initializes if a single entity is annotated with @UserDefinition.
- 1
- The
@UserDefinitionannotation must be present on a single entity, either a regular Hibernate ORM entity or a Hibernate ORM with Panache entity. - 2
- Indicates the field used for the username.
- 3
- Indicates the field used for the password. By default, it uses bcrypt-hashed passwords. You can configure it to use plain text or custom passwords.
- 4
- Indicates the comma-separated list of roles added to the target principal representation attributes.
- 5
- Allows us to add users while hashing passwords with the proper bcrypt hash.
Don’t forget to set up the Panache and PostgreSQL JDBC driver, please see Setting up and configuring Hibernate ORM with Panache for more information.
1.6. Configure the application Copy linkLink copied to clipboard!
Enable the built-in Quarkus Basic authentication mechanism by setting the
quarkus.http.auth.basicproperty totrue:quarkus.http.auth.basic=trueNoteWhen secure access is required, and no other authentication mechanisms are enabled, the built-in Basic authentication of Quarkus is the fallback authentication mechanism. Therefore, in this tutorial, you do not need to set the property
quarkus.http.auth.basictotrue.Configure at least one data source in the
application.propertiesfile so thequarkus-security-jpaextension can access your database. For example:Copy to Clipboard Copied! Toggle word wrap Toggle overflow -
To initialize the database with users and roles, implement the
Startupclass, as outlined in the following code snippet:
The preceding example demonstrates how the application can be protected and identities provided by the specified database.
In a production environment, do not store plain text passwords. As a result, the quarkus-security-jpa defaults to using bcrypt-hashed passwords.
1.7. Test your application by using Dev Services for PostgreSQL Copy linkLink copied to clipboard!
Complete the integration testing of your application in JVM and native modes by using Dev Services for PostgreSQL before you run your application in production mode.
Start by adding the following dependencies to your test project:
Using Maven:
<dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <scope>test</scope> </dependency><dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <scope>test</scope> </dependency>Copy to Clipboard Copied! Toggle word wrap Toggle overflow Using Gradle:
testImplementation("io.rest-assured:rest-assured")testImplementation("io.rest-assured:rest-assured")Copy to Clipboard Copied! Toggle word wrap Toggle overflow - To run your application in dev mode:
Using the Quarkus CLI:
quarkus dev
quarkus devCopy to Clipboard Copied! Toggle word wrap Toggle overflow Using Maven:
./mvnw quarkus:dev
./mvnw quarkus:devCopy to Clipboard Copied! Toggle word wrap Toggle overflow Using Gradle:
./gradlew --console=plain quarkusDev
./gradlew --console=plain quarkusDevCopy to Clipboard Copied! Toggle word wrap Toggle overflow -
The following properties configuration demonstrates how to enable PostgreSQL testing to run only in production (
prod) mode. In this scenario,Dev Services for PostgreSQLlaunches and configures aPostgreSQLtest container.
-
If you add the
%prod.profile prefix, data source properties are not visible toDev Services for PostgreSQLand are only observed by an application running in production mode. - To write the integration test, use the following code sample:
As you can see in this code sample, you do not need to start the test container from the test code.
When you start your application in dev mode, Dev Services for PostgreSQL launches a PostgreSQL dev mode container so that you can start developing your application. While developing your application, you can add and run tests individually by using the Continuous Testing feature. Dev Services for PostgreSQL supports testing while you develop by providing a separate PostgreSQL test container that does not conflict with the dev mode container.
1.7.1. Use curl or a browser to test your application Copy linkLink copied to clipboard!
- Use the following example to start the PostgreSQL server:
docker run --rm=true --name security-getting-started -e POSTGRES_USER=quarkus \
-e POSTGRES_PASSWORD=quarkus -e POSTGRES_DB=elytron_security_jpa \
-p 5432:5432 postgres:14.1
docker run --rm=true --name security-getting-started -e POSTGRES_USER=quarkus \
-e POSTGRES_PASSWORD=quarkus -e POSTGRES_DB=elytron_security_jpa \
-p 5432:5432 postgres:14.1
1.7.2. Compile and run the application Copy linkLink copied to clipboard!
Compile and run your Quarkus application by using one of the following methods:
JVM mode
Compile the application:
Using the Quarkus CLI:
quarkus build
quarkus buildCopy to Clipboard Copied! Toggle word wrap Toggle overflow Using Maven:
./mvnw install
./mvnw installCopy to Clipboard Copied! Toggle word wrap Toggle overflow Using Gradle:
./gradlew build
./gradlew buildCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Run the application:
java -jar target/quarkus-app/quarkus-run.jar
java -jar target/quarkus-app/quarkus-run.jarCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Native mode
Compile the application:
Using the Quarkus CLI:
quarkus build --native
quarkus build --nativeCopy to Clipboard Copied! Toggle word wrap Toggle overflow Using Maven:
./mvnw install -Dnative
./mvnw install -DnativeCopy to Clipboard Copied! Toggle word wrap Toggle overflow Using Gradle:
./gradlew build -Dquarkus.package.type=native
./gradlew build -Dquarkus.package.type=nativeCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Run the application:
./target/security-jpa-quickstart-1.0.0-SNAPSHOT-runner
./target/security-jpa-quickstart-1.0.0-SNAPSHOT-runnerCopy to Clipboard Copied! Toggle word wrap Toggle overflow
1.7.3. Access and test the application security Copy linkLink copied to clipboard!
When your application is running, you can access its endpoints by using one of the following Curl commands.
Connect to a protected endpoint anonymously:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow Connect to a protected endpoint anonymously:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow Connect to a protected endpoint as an authorized user:
Copy to Clipboard Copied! Toggle word wrap Toggle overflow
You can also access the same endpoint URLs by using a browser.
If you use a browser to connect to a protected resource anonymously, a Basic authentication form displays, prompting you to enter credentials.
1.7.4. Results Copy linkLink copied to clipboard!
When you provide the credentials of an authorized user, for example, admin:admin, the Jakarta Persistence security extension authenticates and loads the user’s roles. The admin user is authorized to access the protected resources.
If a resource is protected with @RolesAllowed("user"), the user admin is not authorized to access the resource because it is not assigned to the "user" role, as shown in the following example:
Finally, the user named user is authorized, and the security context contains the principal details, for example, the username.
1.8. What’s next Copy linkLink copied to clipboard!
You have successfully learned how to create and test a secure Quarkus application. This was achieved by integrating the built-in Basic authentication in Quarkus with the Jakarta Persistence identity provider.
After completing this tutorial, you can explore more advanced security mechanisms in Quarkus. The following information shows you how to use OpenID Connect for secure single sign-on access to your Quarkus endpoints:
1.9. References Copy linkLink copied to clipboard!
Chapter 2. Quarkus Security with Jakarta Persistence Copy linkLink copied to clipboard!
You can configure your application to use Jakarta Persistence to store users' identities.
Quarkus provides a Jakarta Persistence identity provider, similar to the JDBC identity provider. Jakarta Persistence is suitable for use with the Basic and Form-based Quarkus Security mechanisms, which require username and password credentials.
The Jakarta Persistence IdentityProvider creates a SecurityIdentity instance. During user authentication, this instance is used to verify and authorize access requests.
For a practical example, see the Getting started with Security using Basic authentication and Jakarta Persistence tutorial.
2.1. Jakarta Persistence entity specification Copy linkLink copied to clipboard!
Quarkus security offers a Jakarta Persistence integration to collect usernames, passwords, and roles and store them into Jakarta Persistence database entities.
The following Jakarta Persistence entity specification demonstrates how users' information needs to be stored in a Jakarta Persistence entity and correctly mapped so that Quarkus can retrieve this information from a database.
-
The
@UserDefinitionannotation must be present on a Jakarta Persistence entity, regardless of whether simplified Hibernate ORM with Panache is used or not. -
The
@Usernameand@Passwordfield types are alwaysString. -
The
@Rolesfield must either beString,Collection<String>, or aCollection<X>, whereXis an entity class with a singleStringfield annotated as@RolesValue. -
Each
Stringrole element type is parsed as a comma-separated list of roles.
The following example demonstrates storing security information by adding annotations to the user entity:
The quarkus-security-jpa extension initializes only if a single entity is annotated with @UserDefinition.
- 1
- The
@UserDefinitionannotation must be present on a single entity, either a regular Hibernate ORM entity or a Hibernate ORM with Panache entity. - 2
- Indicates the field used for the username.
- 3
- Indicates the field used for the password. By default,
quarkus-security-jpauses bcrypt-hashed passwords, or you can configure plain text or custom passwords instead. - 4
- This indicates the comma-separated list of roles added to the target principal representation attributes.
- 5
- This method lets you add users while hashing passwords with the proper
bcrypthash.
2.2. Jakarta Persistence entity as storage of roles Copy linkLink copied to clipboard!
Use the following example to store roles inside another Jakarta Persistence entity:
This example demonstrates storing and accessing roles. To update an existing user or create a new one, annotate public List<Role> roles with @Cascade(CascadeType.ALL) or choose a specific CascadeType.
2.3. Password storage and hashing Copy linkLink copied to clipboard!
When developing applications with Quarkus, you can decide how to manage password storage and hashing. You can keep the default password and hashing settings of Quarkus, or you can hash passwords manually.
With the default option, passwords are stored and hashed with bcrypt under the Modular Crypt Format (MCF). While using MCF, the hashing algorithm, iteration count, and salt are stored as a part of the hashed value. As such, we do not need dedicated columns to keep them.
In cryptography, a salt is a name for random data used as an additional input to a one-way function that hashes data, a password, or a passphrase.
To represent passwords stored in the database that were hashed by different algorithms, create a class that implements org.wildfly.security.password.PasswordProvider as shown in the following example.
The following snippet shows how to set a custom password provider that represents a password that was hashed with the SHA256 hashing algorithm.
To quickly create a hashed password, use String BcryptUtil.bcryptHash(String password), which defaults to creating a random salt and hashing in ten iterations. This method also allows specifying the number of iterations and salt used.
For applications running in a production environment, do not store passwords as plain text.
However, it is possible to store passwords as plain text with the @Password(PasswordType.CLEAR) annotation when operating in a test environment.
The Hibernate Multitenancy is supported, and you can store the user entity in a persistence unit with enabled multitenancy. However, if your io.quarkus.hibernate.orm.runtime.tenant.TenantResolver must access the io.vertx.ext.web.RoutingContext to resolve request details, you must disable proactive authentication. For more information about proactive authentication, see the Quarkus Proactive authentication guide.
Configuration property fixed at build time - All other configuration properties are overridable at runtime
| Type | Default | |
|
Selects the Hibernate ORM persistence unit. Default persistence unit is used when no value is specified.
Environment variable: | string |
|