Authentication mechanisms in Quarkus

The Quarkus Security framework supports multiple authentication mechanisms, which you can use to secure your applications. You can also combine authentication mechanisms.

Before you choose an authentication mechanism for securing your Quarkus applications, review the information provided.

Overview of supported authentication mechanisms

Some supported authentication mechanisms are built into Quarkus, while others require you to add an extension. All of these mechanisms are detailed in the following sections:

The following table maps specific authentication requirements to a supported mechanism that you can use in Quarkus:

Table 1. Authentication requirements and mechanisms
Authentication requirement Authentication mechanism

Username and password

Basic, Form-based authentication

Bearer access token

OIDC Bearer token authentication, JWT, OAuth2

Single sign-on (SSO)

OIDC Code Flow, Form-based authentication

Client certificate

Mutual TLS authentication

WebAuthn

WebAuthn

Kerberos ticket

Kerberos

For more information, see the following Token authentication mechanism comparison table.

Built-in authentication mechanisms

Quarkus Security provides the following built-in authentication support:

Basic authentication

You can secure your Quarkus application endpoints with the built-in HTTP Basic authentication mechanism. For more information, see the following documentation:

Form-based authentication

Quarkus provides form-based authentication that works similarly to traditional Servlet form-based auth. Unlike traditional form authentication, the authenticated user is not stored in an HTTP session because Quarkus does not support clustered HTTP sessions. Instead, the authentication information is stored in an encrypted cookie, which can be read by all cluster members who share the same encryption key.

To apply encryption, add the quarkus.http.auth.session.encryption-key property, and ensure the value you set is at least 16 characters long. The encryption key is hashed by using SHA-256. The resulting digest is used as a key for AES-256 encryption of the cookie value. The cookie contains an expiry time as part of the encrypted value, so all nodes in the cluster must have their clocks synchronized. At one-minute intervals, a new cookie gets generated with an updated expiry time if the session is in use.

With single-page applications (SPA), you typically want to avoid redirects by removing default page paths, as shown in the following example:

# do not redirect, respond with HTTP 200 OK
quarkus.http.auth.form.landing-page=

# do not redirect, respond with HTTP 401 Unauthorized
quarkus.http.auth.form.login-page=
quarkus.http.auth.form.error-page=

The following properties can be used to configure form-based authentication:

Configuration property fixed at build time - All other configuration properties are overridable at runtime

Configuration property

类型

默认

If form authentication is enabled.

Environment variable: QUARKUS_HTTP_AUTH_FORM_ENABLED

Show more

boolean

false

The login page. Redirect to login page can be disabled by setting quarkus.http.auth.form.login-page=.

Environment variable: QUARKUS_HTTP_AUTH_FORM_LOGIN_PAGE

Show more

string

/login.html

The post location.

Environment variable: QUARKUS_HTTP_AUTH_FORM_POST_LOCATION

Show more

string

/j_security_check

The username field name.

Environment variable: QUARKUS_HTTP_AUTH_FORM_USERNAME_PARAMETER

Show more

string

j_username

The password field name.

Environment variable: QUARKUS_HTTP_AUTH_FORM_PASSWORD_PARAMETER

Show more

string

j_password

The error page. Redirect to error page can be disabled by setting quarkus.http.auth.form.error-page=.

Environment variable: QUARKUS_HTTP_AUTH_FORM_ERROR_PAGE

Show more

string

/error.html

The landing page to redirect to if there is no saved page to redirect back to. Redirect to landing page can be disabled by setting quarkus.http.auth.form.landing-page=.

Environment variable: QUARKUS_HTTP_AUTH_FORM_LANDING_PAGE

Show more

string

/index.html

Option to control the name of the cookie used to redirect the user back to where he wants to get access to.

Environment variable: QUARKUS_HTTP_AUTH_FORM_LOCATION_COOKIE

Show more

string

quarkus-redirect-location

The inactivity (idle) timeout When inactivity timeout is reached, cookie is not renewed and a new login is enforced.

Environment variable: QUARKUS_HTTP_AUTH_FORM_TIMEOUT

Show more

Duration

PT30M

How old a cookie can get before it will be replaced with a new cookie with an updated timeout, also referred to as "renewal-timeout". Note that smaller values will result in slightly more server load (as new encrypted cookies will be generated more often), however larger values affect the inactivity timeout as the timeout is set when a cookie is generated. For example if this is set to 10 minutes, and the inactivity timeout is 30m, if a users last request is when the cookie is 9m old then the actual timeout will happen 21m after the last request, as the timeout is only refreshed when a new cookie is generated. In other words no timeout is tracked on the server side; the timestamp is encoded and encrypted in the cookie itself, and it is decrypted and parsed with each request.

Environment variable: QUARKUS_HTTP_AUTH_FORM_NEW_COOKIE_INTERVAL

Show more

Duration

PT1M

The cookie that is used to store the persistent session

Environment variable: QUARKUS_HTTP_AUTH_FORM_COOKIE_NAME

Show more

string

quarkus-credential

The cookie path for the session and location cookies.

Environment variable: QUARKUS_HTTP_AUTH_FORM_COOKIE_PATH

Show more

string

/

Set the HttpOnly attribute to prevent access to the cookie via JavaScript.

Environment variable: QUARKUS_HTTP_AUTH_FORM_HTTP_ONLY_COOKIE

Show more

boolean

false

SameSite attribute for the session and location cookies.

Environment variable: QUARKUS_HTTP_AUTH_FORM_COOKIE_SAME_SITE

Show more

strict, lax, none

strict

About the Duration format

To write duration values, use the standard java.time.Duration format. See the Duration#parse() javadoc for more information.

You can also use a simplified format, starting with a number:

  • If the value is only a number, it represents time in seconds.

  • If the value is a number followed by ms, it represents time in milliseconds.

In other cases, the simplified format is translated to the java.time.Duration format for parsing:

  • If the value is a number followed by h, m, or s, it is prefixed with PT.

  • If the value is a number followed by d, it is prefixed with P.

Mutual TLS authentication

Quarkus provides mutual TLS (mTLS) authentication so that you can authenticate users based on their X.509 certificates.

To use this authentication method, you must first enable SSL/TLS for your application. For more information, see the Supporting secure connections with SSL section of the Quarkus "HTTP reference" guide.

After your application accepts secure connections, the next step is to configure the quarkus.http.ssl.certificate.trust-store-file property with the name of that file that holds all the certificates your application trusts. The specified file also includes information about how your application asks for certificates when a client, such as a browser or other service, tries to access one of its protected resources.

quarkus.http.ssl.certificate.key-store-file=server-keystore.jks            (1)
quarkus.http.ssl.certificate.key-store-password=the_key_store_secret
quarkus.http.ssl.certificate.trust-store-file=server-truststore.jks        (2)
quarkus.http.ssl.certificate.trust-store-password=the_trust_store_secret
quarkus.http.ssl.client-auth=required                                      (3)
quarkus.http.auth.permission.default.paths=/*                              (4)
quarkus.http.auth.permission.default.policy=authenticated
1 The keystore where the server’s private key is located.
2 The truststore from which the trusted certificates are loaded.
3 With this value set to required, the server requires certificates from clients. To relax this requirement so that the server accepts requests without a certificate, set the value to REQUEST. This option is useful when you are also supporting authentication methods other than mTLS.
4 Defines a policy where only authenticated users should have access to resources from your application.

When the incoming request matches a valid certificate in the truststore, your application can obtain the subject by injecting a SecurityIdentity as follows:

Obtaining the subject
@Inject
SecurityIdentity identity;

@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
    return String.format("Hello, %s", identity.getPrincipal().getName());
}

You can also get the certificate by using the code outlined in the following example:

Obtaining the certificate
import java.security.cert.X509Certificate;
import io.quarkus.security.credential.CertificateCredential;

CertificateCredential credential = identity.getCredential(CertificateCredential.class);
X509Certificate certificate = credential.getCertificate();

授权

The information from the client certificate can be used to enhance Quarkus SecurityIdentity. For example, you can add new roles after checking a client certificate subject name, and so on. For more information about customizing SecurityIdentity, see the Security identity customization section in the Quarkus "Security tips and tricks" guide.

Other supported authentication mechanisms

Quarkus Security also supports the following authentication mechanisms through extensions:

WebAuthn认证机制

WebAuthn is an authentication mechanism that replaces passwords. When you write a service for registering new users, or logging them in, instead of asking for a password, you can use WebAuthn, which replaces the password. For more information, see the Secure a Quarkus application by using the WebAuthn authentication mechanism guide.

OpenID Connect authentication

OpenID Connect (OIDC) is an identity layer that works on top of the OAuth 2.0 protocol. OIDC enables client applications to verify the identity of a user based on the authentication performed by the OIDC provider and retrieve basic information about that user.

The Quarkus quarkus-oidc extension provides a reactive, interoperable, multitenant-enabled OIDC adapter that supports Bearer token and Authorization Code Flow authentication mechanisms. The Bearer token authentication mechanism extracts the token from the HTTP Authorization header. The Authorization Code Flow mechanism redirects the user to an OIDC provider to authenticate the user’s identity. After the user is redirected back to Quarkus, the mechanism completes the authentication process by exchanging the provided code that was granted for the ID, access, and refresh tokens.

You can verify ID and access JSON Web Token (JWT) tokens by using the refreshable JSON Web Key (JWK) set or introspect them remotely. However, opaque, also known as binary tokens, can only be introspected remotely.

Using the Quarkus OIDC extension, both the Bearer token and Authorization Code Flow authentication mechanisms use SmallRye JWT authentication to represent JWT tokens as MicroProfile JWT org.eclipse.microprofile.jwt.JsonWebToken.

用于OIDC认证的其他Quarkus资源

For more information about OIDC authentication and authorization methods that you can use to secure your Quarkus applications, see the following resources:

OIDC topic Quarkus information resource

Bearer token authentication mechanism

OIDC Bearer token authentication

Authorization Code Flow authentication mechanism

OpenID Connect (OIDC) Authorization Code Flow mechanism

Multiple tenants that can support the Bearer token authentication or Authorization Code Flow mechanisms

使用OpenID连接(OIDC)多租户

Securing Quarkus with commonly-used OpenID Connect providers

Configuring well-known OpenID Connect providers

使用Keycloak进行集中授权

使用OpenID连接(OIDC)和Keycloak来集中授权

以编程方式配置Keycloak

Using the Keycloak admin client

To enable the Quarkus OIDC extension at runtime, set quarkus.oidc.tenant-enabled=false at build time. Then re-enable it at runtime by using a system property.

For more information about managing the individual tenant configurations in multitenant OIDC deployments, see the Disabling tenant configurations section in the "Using OpenID Connect (OIDC) multi-tenancy" guide.

OpenID Connect client and filters

quarkus-oidc-client 扩展提供 OidcClient ,用于从支持以下token授权的OpenID Connect和OAuth2提供者那里获取和刷新访问token:

  • client-credentials

  • password

  • refresh_token

The quarkus-oidc-client-filter extension requires the quarkus-oidc-client extension. It provides JAX-RS RESTful Web Services OidcClientRequestFilter, which sets the access token acquired by OidcClient as the Bearer scheme value of the HTTP Authorization header. This filter can be registered with MicroProfile REST client implementations injected into the current Quarkus endpoint, but it is not related to the authentication requirements of this service endpoint. For example, it can be a public endpoint or be protected with mTLS.

在这种情况下,您不需要通过使用Quarkus OpenID Connect适配器来保护您的Quarkus节点。

The quarkus-oidc-token-propagation extension requires the quarkus-oidc extension. It provides Jakarta REST TokenCredentialRequestFilter, which sets the OpenID Connect Bearer token or Authorization Code Flow access token as the Bearer scheme value of the HTTP Authorization header. This filter can be registered with MicroProfile REST client implementations injected into the current Quarkus endpoint, which must be protected by using the Quarkus OIDC adapter. This filter can propagate the access token to the downstream services.

更多信息请参见《 使用OpenID Connect客户端和token传递quickstart 》和 《 link:security-openid-connect-client-reference.htmlOpenID Connect (OIDC) 和 OAuth2 客户端以及过滤器参考] 》指南。

SmallRye JWT authentication

The quarkus-smallrye-jwt extension provides a MicroProfile JSON Web Token (JWT) 2.1 implementation and multiple options to verify signed and encrypted JWT tokens. It represents them as org.eclipse.microprofile.jwt.JsonWebToken.

quarkus-smallrye-jwt is an alternative to the quarkus-oidc Bearer token authentication mechanism and verifies only JWT tokens by using either Privacy Enhanced Mail (PEM) keys or the refreshable JWK key set. quarkus-smallrye-jwt also provides the JWT generation API, which you can use to easily create signed, inner-signed, and encrypted JWT tokens.

For more information, see the Using JWT RBAC guide.

OAuth2 认证机制

quarkus-elytron-security-oauth2 provides an alternative to the Quarkus quarkus-oidc Bearer token authentication mechanism extension. quarkus-elytron-security-oauth2 is based on Elytron and is primarily intended for introspecting opaque tokens remotely. For more information, see the Quarkus Using OAuth2 guide.

在OpenID Connect、SmallRye JWT和OAuth2扩展之间做出选择

Use the following information to select the appropriate token authentication mechanism to secure your Quarkus applications.

List of authentication mechanism use-cases
  • quarkus-oidc requires an OpenID Connect provider such as Keycloak, which can verify the bearer tokens or authenticate the end users with the Authorization Code flow. In both cases, quarkus-oidc requires a connection to the specified OpenID Connect provider.

  • If the user authentication requires Authorization Code flow, or you need to support multiple tenants, use quarkus-oidc. quarkus-oidc can also request user information by using both Authorization Code Flow and Bearer access tokens.

  • If your bearer tokens must be verified, use quarkus-oidc, quarkus-smallrye-jwt, or quarkus-elytron-security-oauth2.

  • If your bearer tokens are in a JSON web token (JWT) format, you can use any extensions in the preceding list. Both quarkus-oidc and quarkus-smallrye-jwt support refreshing the JsonWebKey (JWK) set when the OpenID Connect provider rotates the keys. Therefore, if remote token introspection must be avoided or is unsupported by the providers, use quarkus-oidc or quarkus-smallrye-jwt for verifying JWT tokens.

  • To introspect the JWT tokens remotely, you can use either quarkus-oidc or quarkus-elytron-security-oauth2 because they support verifying the opaque or binary tokens by using remote introspection. quarkus-smallrye-jwt does not support the remote introspection of both opaque or JWT tokens but instead relies on the locally available keys that are usually retrieved from the OpenID Connect provider.

  • quarkus-oidc and quarkus-smallrye-jwt support the JWT and opaque token injection into the endpoint code. Injected JWT tokens provide more information about the user. All extensions can have the tokens injected as Principal.

  • quarkus-smallrye-jwtquarkus-oidc 支持更多的密钥格式。后者只使用属于JWK集的JWK格式的密钥,反之前者还支持PEM密钥。

  • quarkus-smallrye-jwt handles locally signed, inner-signed-and-encrypted, and encrypted tokens. In contrast, although quarkus-oidc and quarkus-elytron-security-oauth2 can also verify such tokens, they treat them as opaque tokens and verify them through remote introspection.

  • 如果您需要一个轻量级的库来进行不透明或JWT token 的远程自查,请使用 quarkus-elytron-security-oauth2

Architectural considerations drive your decision to use opaque or JSON web token (JWT) token format. Opaque tokens tend to be much shorter than JWT tokens but need most of the token-associated state to be maintained in the provider database. Opaque tokens are effectively database pointers.

JWT tokens are significantly longer than opaque tokens. Nonetheless, the providers effectively delegate most of the token-associated state to the client by storing it as the token claims and either signing or encrypting them.

Table 2. Token authentication mechanism comparison
Feature required Authentication mechanism

quarkus-oidc

quarkus-smallrye-jwt

quarkus-elytron-security-oauth2

Bearer JWT verification

本地验证或自查

本地验证

自查

Bearer opaque token verification

自查

自查

刷新 JsonWebKey 集以验证JWT tokens

Represent token as Principal

Inject JWT as MP JWT

Authorization code flow

多租户

User information support

支持Pem密钥格式

支持SecretKey

以JsonWebKey (JWK) 格式

Inner-Signed/Encrypted 或 Encrypted tokens

自查

本地验证

自查

自定义token验证

使用注入的JWT Parser

JWT as a cookie support

组合认证机制

If different sources provide the user credentials, you can combine authentication mechanisms. For example, you can combine the built-in Basic and the Quarkus quarkus-oidc Bearer token authentication mechanisms.

You cannot combine the Quarkus quarkus-oidc Bearer token and smallrye-jwt authentication mechanisms because both mechanisms attempt to verify the token extracted from the HTTP Bearer token authentication scheme.

特定路径认证机制

以下配置示例演示了如何强制要求对一个给定的请求路径选择一个认证机制:

quarkus.http.auth.permission.basic-or-bearer.paths=/service
quarkus.http.auth.permission.basic-or-bearer.policy=authenticated

quarkus.http.auth.permission.basic.paths=/basic-only
quarkus.http.auth.permission.basic.policy=authenticated
quarkus.http.auth.permission.basic.auth-mechanism=basic

quarkus.http.auth.permission.bearer.paths=/bearer-only
quarkus.http.auth.permission.bearer.policy=authenticated
quarkus.http.auth.permission.bearer.auth-mechanism=bearer

auth-mechanism 属性值必须与 HttpAuthenticationMechanism 支持的认证方案相匹配,如 basicbearerform 等等。

主动认证

Proactive authentication is enabled in Quarkus by default. This means that if an incoming request has a credential, the request will always be authenticated, even if the target page does not require authentication. For more information, see the Quarkus Proactive authentication guide.