The English version of quarkus.io is the official project site. Translated sites are community supported on a best-effort basis.

Using Security with an LDAP Realm

This guide demonstrates how your Quarkus application can use an LDAP server to authenticate and authorize your user identities.

Prerequisites

要完成这个指南,你需要:

  • 大概15分钟

  • 编辑器

  • 安装JDK 11以上版本并正确配置了 JAVA_HOME

  • Apache Maven 3.8.1+

  • 如果你愿意的话,还可以选择使用Quarkus CLI

  • 如果你想构建原生可执行程序,可以选择安装Mandrel或者GraalVM,并正确配置(或者使用Docker在容器中进行构建)

Architecture

In this example, we build a very simple microservice which offers three endpoints:

  • /api/public

  • /api/users/me

  • /api/admin

The /api/public endpoint can be accessed anonymously. The /api/admin endpoint is protected with RBAC (Role-Based Access Control) where only users granted with the adminRole role can access. At this endpoint, we use the @RolesAllowed annotation to declaratively enforce the access constraint. The /api/users/me endpoint is also protected with RBAC (Role-Based Access Control) where only users granted with the standardRole role can access. As a response, it returns a JSON document with details about the user.

By default, Quarkus will restrict the use of JNDI within an application, as a precaution to try and mitigate any future vulnerabilities similar to Log4Shell. Because LDAP based auth requires JNDI this protection will be automatically disabled.

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, or download an archive.

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

Creating the Maven Project

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

CLI
quarkus create app org.acme:security-ldap-quickstart \
    --extension=elytron-security-ldap,resteasy-reactive \
    --no-code
cd security-ldap-quickstart

创建Grade项目,请添加 --gradle 或者 --gradle-kotlin-dsl 参数。

关于如何安装并使用Quarkus CLI的更多信息,请参考Quarkus CLI指南

Maven
mvn io.quarkus.platform:quarkus-maven-plugin:2.11.2.Final:create \
    -DprojectGroupId=org.acme \
    -DprojectArtifactId=security-ldap-quickstart \
    -Dextensions="elytron-security-ldap,resteasy-reactive" \
    -DnoCode
cd security-ldap-quickstart

创建Grade项目,请添加 -DbuildTool=gradle 或者 -DbuildTool=gradle-kotlin-dsl 参数。

This command generates a project, importing the elytron-security-ldap extension which is a wildfly-elytron-realm-ldap adapter for Quarkus applications.

If you already have your Quarkus project configured, you can add the elytron-security-ldap extension to your project by running the following command in your project base directory:

CLI
quarkus extension add 'elytron-security-ldap'
Maven
./mvnw quarkus:add-extension -Dextensions="elytron-security-ldap"
Gradle
./gradlew addExtension --extensions="elytron-security-ldap"

This will add the following to your build file:

pom.xml
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-elytron-security-ldap</artifactId>
</dependency>
build.gradle
implementation("io.quarkus:quarkus-elytron-security-ldap")

Writing the application

Let’s start by implementing the /api/public endpoint. As you can see from the source code below, it is just a regular JAX-RS resource:

package org.acme.elytron.security.ldap;

import javax.annotation.security.PermitAll;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/api/public")
public class PublicResource {

    @GET
    @PermitAll
    @Produces(MediaType.TEXT_PLAIN)
    public String publicResource() {
        return "public";
   }
}

The source code for the /api/admin endpoint is also very simple. The main difference here is that we are using a @RolesAllowed annotation to make sure that only users granted with the adminRole role can access the endpoint:

package org.acme.elytron.security.ldap;

import javax.annotation.security.RolesAllowed;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/api/admin")
public class AdminResource {

    @GET
    @RolesAllowed("adminRole")
    @Produces(MediaType.TEXT_PLAIN)
    public String adminResource() {
         return "admin";
    }
}

Finally, let’s consider the /api/users/me endpoint. As you can see from the source code below, we are trusting only users with the standardRole role. We are using SecurityContext to get access to the current authenticated Principal, and we return the user’s name. This information is loaded from the LDAP server.

package org.acme.elytron.security.ldap;

import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.SecurityContext;

@Path("/api/users")
public class UserResource {

    @GET
    @RolesAllowed("standardRole")
    @Path("/me")
    public String me(@Context SecurityContext securityContext) {
        return securityContext.getUserPrincipal().getName();
    }
}

Configuring the Application

quarkus.security.ldap.enabled=true

quarkus.security.ldap.dir-context.principal=uid=tool,ou=accounts,o=YourCompany,c=DE
quarkus.security.ldap.dir-context.url=ldaps://ldap.server.local
quarkus.security.ldap.dir-context.password=PASSWORD

quarkus.security.ldap.identity-mapping.rdn-identifier=uid
quarkus.security.ldap.identity-mapping.search-base-dn=ou=users,ou=tool,o=YourCompany,c=DE

quarkus.security.ldap.identity-mapping.attribute-mappings."0".from=cn
quarkus.security.ldap.identity-mapping.attribute-mappings."0".to=groups
quarkus.security.ldap.identity-mapping.attribute-mappings."0".filter=(member=uid={0})
quarkus.security.ldap.identity-mapping.attribute-mappings."0".filter-base-dn=ou=roles,ou=tool,o=YourCompany,c=DE

{0} is substituted by the uid, whereas {1} will be substituted by the dn of the user entry.

The elytron-security-ldap extension requires a dir-context and an identity-mapping with at least one attribute-mapping to authenticate the user and its identity.

Testing the Application

The application is now protected and the identities are provided by our LDAP server. Let’s start the application in dev mode:

CLI
quarkus dev
Maven
./mvnw quarkus:dev
Gradle
./gradlew --console=plain quarkusDev

The very first thing to check is to ensure the anonymous access works.

$ curl -i -X GET http://localhost:8080/api/public
HTTP/1.1 200 OK
Content-Length: 6
Content-Type: text/plain;charset=UTF-8

public%

Now, let’s try to hit a protected resource anonymously.

$ curl -i -X GET http://localhost:8080/api/admin
HTTP/1.1 401 Unauthorized
Content-Length: 14
Content-Type: text/html;charset=UTF-8

Not authorized%

So far so good, now let’s try with an allowed user.

$ curl -i -X GET -u adminUser:adminUserPassword http://localhost:8080/api/admin
HTTP/1.1 200 OK
Content-Length: 5
Content-Type: text/plain;charset=UTF-8

admin%

By providing the adminUser:adminUserPassword credentials, the extension authenticated the user and loaded their roles. The adminUser user is authorized to access to the protected resources.

The user adminUser should be forbidden to access a resource protected with @RolesAllowed("standardRole") because it doesn’t have this role.

$ curl -i -X GET -u adminUser:adminUserPassword http://localhost:8080/api/users/me
HTTP/1.1 403 Forbidden
Content-Length: 34
Content-Type: text/html;charset=UTF-8

Forbidden%

Finally, using the user standardUser works and the security context contains the principal details (username for instance).

$ curl -i -X GET -u standardUser:standardUserPassword http://localhost:8080/api/users/me
HTTP/1.1 200 OK
Content-Length: 4
Content-Type: text/plain;charset=UTF-8

user%

配置参考

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

Configuration property

类型

默认

The option to enable the ldap elytron module

Environment variable: QUARKUS_SECURITY_LDAP_ENABLED

boolean

false

The elytron realm name

Environment variable: QUARKUS_SECURITY_LDAP_REALM_NAME

string

Quarkus

Provided credentials are verified against ldap?

Environment variable: QUARKUS_SECURITY_LDAP_DIRECT_VERIFICATION

boolean

true

The url of the ldap server

Environment variable: QUARKUS_SECURITY_LDAP_DIR_CONTEXT_URL

string

required

The principal: user which is used to connect to ldap server (also named "bindDn")

Environment variable: QUARKUS_SECURITY_LDAP_DIR_CONTEXT_PRINCIPAL

string

The password which belongs to the principal (also named "bindCredential")

Environment variable: QUARKUS_SECURITY_LDAP_DIR_CONTEXT_PASSWORD

string

how ldap redirects are handled

Environment variable: QUARKUS_SECURITY_LDAP_DIR_CONTEXT_REFERRAL_MODE

ignore, follow, throw

ignore

The connect timeout

Environment variable: QUARKUS_SECURITY_LDAP_DIR_CONTEXT_CONNECT_TIMEOUT

Duration

5S

The read timeout

Environment variable: QUARKUS_SECURITY_LDAP_DIR_CONTEXT_READ_TIMEOUT

Duration

60S

The identifier which correlates to the provided user (also named "baseFilter")

Environment variable: QUARKUS_SECURITY_LDAP_IDENTITY_MAPPING_RDN_IDENTIFIER

string

uid

The dn where we look for users

Environment variable: QUARKUS_SECURITY_LDAP_IDENTITY_MAPPING_SEARCH_BASE_DN

string

required

If the child nodes are also searched for identities

Environment variable: QUARKUS_SECURITY_LDAP_IDENTITY_MAPPING_SEARCH_RECURSIVE

boolean

false

The roleAttributeId from which is mapped (e.g. "cn")

Environment variable: QUARKUS_SECURITY_LDAP_IDENTITY_MAPPING_ATTRIBUTE_MAPPINGS__ATTRIBUTE_MAPPINGS__FROM

string

required

The identifier whom the attribute is mapped to (in Quarkus: "groups", in WildFly this is "Roles")

Environment variable: QUARKUS_SECURITY_LDAP_IDENTITY_MAPPING_ATTRIBUTE_MAPPINGS__ATTRIBUTE_MAPPINGS__TO

string

groups

The filter (also named "roleFilter")

Environment variable: QUARKUS_SECURITY_LDAP_IDENTITY_MAPPING_ATTRIBUTE_MAPPINGS__ATTRIBUTE_MAPPINGS__FILTER

string

required

The filter base dn (also named "rolesContextDn")

Environment variable: QUARKUS_SECURITY_LDAP_IDENTITY_MAPPING_ATTRIBUTE_MAPPINGS__ATTRIBUTE_MAPPINGS__FILTER_BASE_DN

string

required

About the Duration format

持续时间的格式使用标准的 java.time.Duration 格式您可以在 Duration#parse() javadoc 中了解更多信息。

您还可以提供以数字开头的持续时间值。 在这种情况下,如果该值仅包含一个数字,则转换器将该值视为秒。 否则,PT 会隐式添加到值的前面,以获得标准的 java.time.Duration 格式。

参考文献