Authentication mechanisms in Quarkus

Quarkus Security framework 支持多种身份验证机制,您可以用它们来保护您的应用程序。您还可以组合身份验证机制。

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

在为保护您的 Quarkus 应用程序选择一种身份验证机制前,请先查看提供的信息。

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

Overview of supported authentication mechanisms

一些支持的身份验证机制内置于 Quarkus 中,而另一些则需要您添加扩展。所有这些机制都在以下部分中进行了详细说明:

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:

下表将特定身份验证要求映射到您可以在 Quarkus 中使用的支持机制:

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

有关更多信息,请参阅以下 Token authentication mechanism comparison 表。

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

Built-in authentication mechanisms

Quarkus Security 提供以下内置的身份验证支持:

Quarkus Security provides the following built-in authentication support:

Basic authentication

您可以使用内置的 HTTP 基本身份验证机制保护您的 Quarkus 应用程序端点。有关更多信息,请参阅以下文档:

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 提供表单认证,其工作方式与传统的 Servlet 表单认证类似。与传统的表单认证不同,经过身份验证的用户不会存储在 HTTP 会话中,因为 Quarkus 不支持集群 HTTP 会话。相反,身份验证信息存储在加密 cookie 中,所有共享相同加密密钥的集群成员都可以读取该 cookie。

Quarkus provides form-based authentication that works similarly to traditional Servlet form-based authentication. 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.

要应用加密,请添加 quarkus.http.auth.session.encryption-key 属性,并确保您设置的值的长度至少为 16 个字符。加密密钥使用 SHA-256 进行哈希。产生的提取物用作 cookie 值的 AES-256 加密的密钥。cookie 包含到期时间作为加密值的一部分,因此集群中的所有节点的时钟都必须同步。在一分钟的间隔内,如果会话正在使用,则会使用更新的到期时间生成新的 cookie。

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.

要开始进行表单认证,你应该拥有类似于 Enable Basic authentication 中所述的设置,并且属性 quarkus.http.auth.form.enabled 必须设为 true

To get started with form authentication, you should have similar settings as described in Enable Basic authentication and property quarkus.http.auth.form.enabled must be set to true.

使用基于表单的认证,简单的 application.properties 可能会看起来类似于此:

Simple application.properties with form-base authentication can look similar to this:

quarkus.http.auth.form.enabled=true

quarkus.http.auth.form.login-page=login.html
quarkus.http.auth.form.landing-page=hello
quarkus.http.auth.form.error-page=

# Define testing user
quarkus.security.users.embedded.enabled=true
quarkus.security.users.embedded.plain-text=true
quarkus.security.users.embedded.users.alice=alice
quarkus.security.users.embedded.roles.alice=user

在该 application.properties 文件中配置用户名、密钥和角色仅适用于测试场景。为了保护生产应用程序,使用数据库或 LDAP 来存储此信息至关重要。有关详细信息,你可以查看 Quarkus Security with Jakarta Persistence 或在 Enable Basic authentication 中提到的其他内容。

Configuring user names, secrets, and roles in the application.properties file is appropriate only for testing scenarios. For securing a production application, it is crucial to use a database or LDAP to store this information. For more information you can take a look at Quarkus Security with Jakarta Persistence or other mentioned in Enable Basic authentication.

并且应用程序登录页面将包含类似于此的 HTML 表单:

and application login page will contain HTML form similar to this:

<form action="/j_security_check" method="post">
    <label>Username</label>
    <input type="text" placeholder="Username" name="j_username" required>
    <label>Password</label>
    <input type="password" placeholder="Password" name="j_password" required>
    <button type="submit">Login</button>
</form>

对于单页应用 (SPA),你通常可以通过移除默认页面路径来避免重定向,如以下示例所示:

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=

# HttpOnly must be false if you want to log out on the client; it can be true if logging out from the server
quarkus.http.auth.form.http-only-cookie=false

现在你已经为 SPA 禁用重定向,你必须从你的客户端以编程方式登录和注销。以下是用于登录到 j_security_check 端点和通过销毁 Cookie 来注销应用程序的 JavaScript 方法示例。

Now that you have disabled redirects for the SPA, you must log in and log out programmatically from your client. Below are examples of JavaScript methods for logging into the j_security_check endpoint and logging out of the application by destroying the cookie.

const login = () => {
    // Create an object to represent the form data
    const formData = new URLSearchParams();
    formData.append("j_username", username);
    formData.append("j_password", password);

    // Make an HTTP POST request using fetch against j_security_check endpoint
    fetch("j_security_check", {
        method: "POST",
        body: formData,
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
    })
    .then((response) => {
        if (response.status === 200) {
            // Authentication was successful
            console.log("Authentication successful");
        } else {
            // Authentication failed
            console.error("Invalid credentials");
        }
    })
    .catch((error) => {
        console.error(error);
    });
};

要从客户端注销 SPA,必须将 Cookie 设置为 quarkus.http.auth.form.http-only-cookie=false,以便你可以销毁 Cookie,并且可能重定向回你的主页。

To log out of the SPA from the client, the cookie must be set to quarkus.http.auth.form.http-only-cookie=false so you can destroy the cookie and possibly redirect back to your main page.

const logout= () => {
    // delete the credential cookie, essentially killing the session
    const removeCookie = `quarkus-credential=; Max-Age=0;path=/`;
    document.cookie = removeCookie;

    // perform post-logout actions here, such as redirecting back to your login page
};

要从服务器注销 SPA,可以将 Cookie 设置为 quarkus.http.auth.form.http-only-cookie=true,并使用此示例代码来销毁 Cookie。

To log out of the SPA from the server, the cookie can be set to quarkus.http.auth.form.http-only-cookie=true and use this example code to destroy the cookie.

@ConfigProperty(name = "quarkus.http.auth.form.cookie-name")
String cookieName;

@Inject
CurrentIdentityAssociation identity;

@POST
public Response logout() {
    if (identity.getIdentity().isAnonymous()) {
        throw new UnauthorizedException("Not authenticated");
    }
    final NewCookie removeCookie = new NewCookie.Builder(cookieName)
            .maxAge(0)
            .expiry(Date.from(Instant.EPOCH))
            .path("/")
            .build();
    return Response.noContent().cookie(removeCookie).build();
}

以下属性可用于配置基于表单的认证:

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

Unresolved directive in security-authentication-mechanisms.adoc - include::{generated-dir}/config/quarkus-vertx-http_quarkus.http.auth.adoc[]

Mutual TLS authentication

Quarkus 提供了双向 TLS (mTLS) 认证,以便你可以基于用户的 X.509 证书来认证用户。

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

要使用此认证方法,你必须首先为你的应用程序启用 SSL/TLS。有关详细信息,请参阅 Quarkus“HTTP 参考”指南的 Supporting secure connections with SSL/TLS 部分。

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

在你的应用程序接受安全连接后,下一步是使用包含你的应用程序信任的所有证书的文件名来配置 quarkus.http.ssl.certificate.trust-store-file 属性。指定的文件还包括有关你的应用程序如何要求证书的信息,当客户端(比如浏览器或其他服务)尝试访问其保护的资源之一时。

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
quarkus.http.insecure-requests=disabled                                    5
1 The keystore where the server’s private key is located.
2 The truststore from which the trusted certificates are loaded.
3 With the value set to required, the server demands client certificates. Set the value to REQUEST to allow the server to accept requests without a certificate. This setting is beneficial when supporting authentication methods besides mTLS.
4 Defines a policy where only authenticated users should have access to resources from your application.
5 You can explicitly disable the plain HTTP protocol, thus requiring all requests to use HTTPS. When you set quarkus.http.ssl.client-auth to required, the system automatically sets quarkus.http.insecure-requests to disabled.

当传入请求与信任库中的有效证书匹配时,你的应用程序可以通过注入 SecurityIdentity 如下所示来获取主题:

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();

Mapping certificate attributes to roles

客户端证书中的信息可用于向 Quarkus 添加角色 SecurityIdentity.

The information from the client certificate can be used to add roles to Quarkus SecurityIdentity.

在检查客户端证书的公用名称 (CN) 属性后,你可以向 SecurityIdentity 添加新角色。添加新角色的最简单方法是使用证书属性到角色映射功能。

You can add new roles to SecurityIdentity after checking a client certificate’s common name (CN) attribute. The easiest way to add new roles is to use a certificate attribute to role mapping feature.

例如,你可以按如下方式更新 Mutual TLS authentication 简介部分中所示的属性:

For example, you can update the properties shown in the section which introduces Mutual TLS authentication as follows:

quarkus.http.ssl.certificate.key-store-file=server-keystore.jks
quarkus.http.ssl.certificate.key-store-password=the_key_store_secret
quarkus.http.ssl.certificate.trust-store-file=server-truststore.jks
quarkus.http.ssl.certificate.trust-store-password=the_trust_store_secret
quarkus.http.ssl.client-auth=required
quarkus.http.insecure-requests=disabled

quarkus.http.auth.certificate-role-properties=cert-role-mappings.properties 1

quarkus.http.auth.permission.certauthenticated.paths=/*   2
quarkus.http.auth.permission.certauthenticated.policy=role-policy-cert 2
quarkus.http.auth.policy.role-policy-cert.roles-allowed=user,admin     2
1 The cert-role-mappings.properties classpath resource contains a map of certificate’s CN values to roles in the form CN=role or CN=role1,role2, etc. Let’s assume it contains three entries: alice=user,admin, bob=user and jdoe=tester.
2 Use HTTP security policy to require that SecurityIdentity must have either user or admin roles for the requests to be authorized.

鉴于前面提到的配置,如果客户端证书的 CN 属性等于 alicebob,则会授权该请求,如果等于 jdoe,则会禁止该请求。

Given the preceeding configuration, the request is authorized if the client certificate’s CN attribute is equal to alice or bob and forbidden if it is equal to jdoe.

Using certificate attributes to augment SecurityIdentity

如果你认为自动 Mapping certificate attributes to roles 选项不合适,你可以随时注册 SecurityIdentityAugmentor。自定义 SecurityIdentityAugmentor 可以检查不同客户端证书属性的值并相应地扩充 SecurityIdentity

You can always register SecurityIdentityAugmentor if the automatic Mapping certificate attributes to roles option does not suit. Custom SecurityIdentityAugmentor can check the values of different client certificate attributes and augment the SecurityIdentity accordingly.

有关自定义 SecurityIdentity 的详细信息,请参阅 Quarkus“安全提示和技巧”指南中的 Security identity customization 部分。

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 安全性还通过扩展程序支持以下认证机制:

Quarkus Security also supports the following authentication mechanisms through extensions:

WebAuthn authentication

WebAuthn 是一种取代密码的认证机制。在编写用于注册新用户或让用户登录的服务时,你可以使用 WebAuthn 替代密码,而无需询问密码。有关详细信息,请参阅 Secure a Quarkus application by using the WebAuthn authentication mechanism 指南。

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) 是一个在 OAuth 2.0 协议基础上工作的身份层。OIDC 使得客户端应用程序能够基于 OIDC 提供程序执行的认证来验证用户的身份,并检索该用户的基本信息。

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.

Quarkus quarkus-oidc 扩展提供了一个支持承载令牌和鉴权码流程认证机制的响应式、可互操作且支持多租户的 OIDC 适配器。承载令牌认证机制从 HTTP Authorization 标头中提取令牌。

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.

鉴权码流程机制将用户重定向到 OIDC 提供程序以认证用户的身份。在将用户重定向回 Quarkus 后,该机制通过交换授予 ID、访问和刷新令牌的提供的代码来完成认证流程。

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.

你可以使用可刷新的 JSON Web 密钥 (JWK) 集验证 ID 和访问 JSON Web 令牌 (JWT) 令牌,或远程验证它们。但是,不透明的(也称为二进制令牌)只能远程验证。

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.

使用 Quarkus OIDC 扩展时,承载令牌和鉴权码流程认证机制都会使用 SmallRye JWT authentication 来表示 JWT 令牌,如 MicroProfile JWT org.eclipse.microprofile.jwt.JsonWebToken.

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.

Additional Quarkus resources for OIDC authentication

有关可用于保护 Quarkus 应用程序的 OIDC 认证和授权方法的详细信息,请参阅以下资源:

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

OIDC and SAML Identity broker

OpenID Connect (OIDC) Authorization Code Flow and SAML Identity broker

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

Using OpenID Connect (OIDC) multi-tenancy

Securing Quarkus with commonly used OpenID Connect providers

Configuring well-known OpenID Connect providers

Using Keycloak to centralize authorization

Using OpenID Connect (OIDC) and Keycloak to centralize authorization

Configuring Keycloak programmatically

Using the Keycloak admin client

要在运行时启用 Quarkus OIDC 扩展,请在构建时设置 quarkus.oidc.tenant-enabled=false。然后,通过使用系统属性在运行时重新启用它。

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.

有关在多租户 OIDC 部署中管理各个租户配置的更多信息,请参阅“使用 OpenID Connect (OIDC) 多租户”指南中的 Disabling tenant configurations部分。

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`用于从支持以下令牌授予的 OpenID Connect 和 OAuth2 提供程序获取和刷新访问令牌:

The quarkus-oidc-client extension provides OidcClient for acquiring and refreshing access tokens from OpenID Connect and OAuth2 providers that support the following token grants:

  • client-credentials

  • password

  • refresh_token

quarkus-resteasy-client-oidc-filter`扩展需要 `quarkus-oidc-client`扩展。它提供 JAX-RS RESTful Web 服务 `OidcClientRequestFilter,它将由 `OidcClient`获取的访问令牌设置为 HTTP `Authorization`标头的 `Bearer`方案值。此过滤器可注册到注入到当前 Quarkus 端点的 MicroProfile REST 客户端实现,但它与该服务端点的身份验证要求无关。例如,它可以是公共端点或受 mTLS 保护。

The quarkus-resteasy-client-oidc-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 端点。

In this scenario, you do not need to protect your Quarkus endpoint by using the Quarkus OpenID Connect adapter.

quarkus-resteasy-client-oidc-token-propagation`扩展需要 `quarkus-oidc`扩展。它提供 Jakarta REST `TokenCredentialRequestFilter,它将 OpenID Connect Bearer 令牌或授权码流程访问令牌设置为 HTTP `Authorization`标头的 `Bearer`方案值。此过滤器可注册到注入到当前 Quarkus 端点的 MicroProfile REST 客户端实现中,该实现必须使用 Quarkus OIDC 适配器进行保护。此过滤器可将访问令牌传播到下游服务。

The quarkus-resteasy-client-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.

SmallRye JWT authentication

quarkus-smallrye-jwt`扩展提供了一个 MicroProfile JSON Web Token (JWT) 2.1 实现和多个选项来验证已签名和已加密的 `JWT`令牌。它将它们表示为 `org.eclipse.microprofile.jwt.JsonWebToken

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`是 `quarkus-oidc`Bearer 令牌认证机制的替代方法,并且仅通过使用隐私增强电子邮件 (PEM) 密钥或可刷新的 `JWK`密钥集来验证 `JWT`令牌。`quarkus-smallrye-jwt`还提供 JWT 生成 API,您可以使用它轻松创建 `signed、`inner-signed`和 `encrypted``JWT`令牌。

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.

有关更多信息,请参阅 Using JWT RBAC指南。

For more information, see the Using JWT RBAC guide.

OAuth2 authentication

quarkus-elytron-security-oauth2`提供了对 Quarkus `quarkus-oidc`提供者令牌认证机制扩展的替代方案。`quarkus-elytron-security-oauth2`基于 `Elytron,并且主要用于远程检查不透明令牌。

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.

有关更多信息,请参阅 Quarkus Using OAuth2指南。

For more information, see the Quarkus Using OAuth2 guide.

Choosing between OpenID Connect, SmallRye JWT, and OAuth2 authentication mechanisms

使用以下信息选择合适的令牌认证机制以保护您的 Quarkus 应用程序。

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-elytron-security-oauth2, or quarkus-smallrye-jwt.

  • 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 to verify JWT tokens.

  • To introspect the JWT tokens remotely, you can use quarkus-oidc or quarkus-elytron-security-oauth2 for 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-jwt supports more key formats than quarkus-oidc. quarkus-oidc uses only the JWK-formatted keys that are part of a JWK set, whereas quarkus-smallrye-jwt supports PEM keys.

  • 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.

  • If you need a lightweight library for the remote introspection of opaque or JWT tokens, use quarkus-elytron-security-oauth2.

架构考虑决定了使用不透明或 JSON Web 令牌 (JWT) 令牌格式。不透明令牌往往比 JWT 令牌短得多,但需要在提供程序数据库中维护大多数令牌关联状态。不透明令牌实际上是数据库指针。

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 令牌比不透明令牌长得多。尽管如此,提供程序有效地将大多数令牌关联状态委派给了客户端,方法是将其存储为令牌声明,并对它们进行签名或加密。

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

Local verification or introspection

Local verification

Introspection

Bearer opaque token verification

Introspection

No

Introspection

Refreshing JsonWebKey set to verify JWT tokens

Yes

Yes

No

Represent token as Principal

Yes

Yes

Yes

Inject JWT as MP JWT

Yes

Yes

No

Authorization code flow

Yes

No

No

Multi-tenancy

Yes

No

No

User information support

Yes

No

No

PEM key format support

No

Yes

No

SecretKey support

No

In JSON Web Key (JWK) format

No

Inner-signed and encrypted or encrypted tokens

Introspection

Local verification

Introspection

Custom token verification

No

With injected JWT parser

No

JWT as a cookie support

No

Yes

Yes

Combining authentication mechanisms

如果不同的来源提供用户凭证,您可以结合认证机制。例如,您可以结合内置的基本和 Quarkus @“1” 提供方令牌认证机制。

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.

您不能结合 Quarkus @“2” 提供方令牌和 @“3” 认证机制,因为这两个机制都会尝试验证从 HTTP 提供方令牌认证方案中提取的令牌。

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.

Use HTTP Security Policy to enable path-based authentication

下面的配置文件示例展示了如何针对给定的请求路径强制执行一个单一的可选认证机制:

The following configuration example demonstrates how you can enforce a single selectable authentication mechanism for a given request path:

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

确保 @“4” 属性的值与由 @“5” 支持的认证方案匹配,例如 @“6”、@“7” 或 @“8”。

Ensure that the value of the auth-mechanism property matches the authentication scheme supported by HttpAuthenticationMechanism, for example, basic, bearer, or form.

Use annotations to enable path-based authentication for Jakarta REST endpoints

可以使用注释来为每个 Jakarta REST 端点选择一个特定的认证机制。当 @“9” 禁用时,才会启用此功能,这是由于注释只能用于在匹配 REST 端点后选择认证机制。以下是您如何为 REST 端点基础选择认证机制:

It is possible to use annotations to select an authentication mechanism specific to each Jakarta REST endpoint. This feature is only enabled when Proactive authentication is disabled due to the fact that the annotations can only be used to select authentication mechanisms after a REST endpoint has been matched. Here is how you can select an authentication mechanism per a REST endpoint basis:

quarkus.http.auth.proactive=false
import io.quarkus.oidc.AuthorizationCodeFlow;
import io.quarkus.vertx.http.runtime.security.annotation.BasicAuthentication;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;

@Path("hello")
public class HelloResource {

    @GET
    @BasicAuthentication 1 2
    @Path("basic")
    public String basicAuthMechanism() {
        return "basic";
    }

    @GET
    @RolesAllowed("admin") 3
    @AuthorizationCodeFlow 4
    @Path("code-flow")
    public String codeFlowAuthMechanism() {
        return "code-flow";
    }
}
1 The REST endpoint /hello/basic can only ever be accessed by using the Basic authentication.
2 This endpoint requires authentication, because when no standard security annotation accompanies the @BasicAuthentication annotation, the @Authenticated annotation is added by default.
3 The @AuthorizationCodeFlow annotation can be combined with any other standard security annotation like @RolesAllowed, @PermissionsAllowed and others.
4 The REST endpoint /hello/code-flow can only ever be accessed by using the OIDC authorization code flow mechanism.
Table 3. Supported authentication mechanism annotations
Authentication mechanism^ Annotation

Basic authentication mechanism

io.quarkus.vertx.http.runtime.security.annotation.BasicAuthentication

Form-based authentication mechanism

io.quarkus.vertx.http.runtime.security.annotation.FormAuthentication

Mutual TLS authentication mechanism

io.quarkus.vertx.http.runtime.security.annotation.MTLSAuthentication

WebAuthn authentication mechanism

io.quarkus.security.webauthn.WebAuthn

Bearer token authentication mechanism

io.quarkus.oidc.BearerTokenAuthentication

OIDC authorization code flow mechanism

io.quarkus.oidc.AuthorizationCodeFlow

SmallRye JWT authentication mechanism

io.quarkus.smallrye.jwt.runtime.auth.BearerTokenAuthentication

Quarkus 自动保护用认证机制注释注释的端点。当 REST 端点和资源上不存在标准安全注释时,@“19” 注释会为您添加。

Quarkus automatically secures endpoints annotated with the authentication mechanism annotation. When no standard security annotation is present on the REST endpoint and resource, the io.quarkus.security.Authenticated annotation is added for you.

还可以使用 @“20” 注释根据方案选择任何认证机制。基于注释的 @“21” 配置属性的类比是 @“22” 注释。

It is also possible to use the io.quarkus.vertx.http.runtime.security.annotation.HttpAuthenticationMechanism annotation to select any authentication mechanism based on its scheme. Annotation-based analogy to the quarkus.http.auth.permission.basic.auth-mechanism=custom configuration property is the @HttpAuthenticationMechanism("custom") annotation.

为了与各种 Jakarta EE 规范保持一致,建议始终重复注释,而不是依赖于注释继承。

For consistency with various Jakarta EE specifications, it is recommended to always repeat annotations instead of relying on annotation inheritance.

How to combine it with HTTP Security Policy

定义允许访问单个资源的角色的最简单方法是 @“23” 注释。不过,也可以像以下示例中那样使用 HTTP 安全策略:

The easiest way to define roles that are allowed to access individual resources is the @RolesAllowed annotation. Nevertheless, it’s also possible to use the HTTP Security Policy like in the example below:

quarkus.http.auth.policy.roles1.roles-allowed=user
quarkus.http.auth.permission.roles1.paths=/hello/code-flow
quarkus.http.auth.permission.roles1.applies-to=JAXRS 1
quarkus.http.auth.permission.roles1.policy=roles1
quarkus.http.auth.permission.roles1.methods=GET 2
1 Delay this policy’s permission check after the endpoint-specific authentication mechanism has been selected.
2 Make the roles1 permission match only the endpoint annotated with the @AuthorizationCodeFlow annotation. Unannotated endpoints must avoid the delay caused by the applies-to=JAXRS option.

Proactive authentication

Quarkus 中默认启用主动认证。这意味着如果传入请求包含凭证,那么该请求将始终经过认证,即使目标页面不需要认证。如需了解更多信息,请参阅 Quarkus @“27” 指南。

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.