Communitygithub.com

Quarkus-Sicherheitsprüfung

Best Practices für die Absicherung von Quarkus-Anwendungen mit Authentifizierung, Autorisierung, Eingabevalidierung, JWT/OIDC, RBAC, CSRF, Secrets-Verwaltung und Abhängigkeitssicherheit. Verwenden Sie dies bei der Überprüfung von Quarkus-Authn/Authz, JWT oder OIDC, RBAC, Validierung oder Secrets.

Was ist Quarkus-Sicherheitsprüfung?

Diese Fähigkeit bietet eine umfassende Anleitung zur Implementierung von Sicherheitsmechanismen in Quarkus-Anwendungen. Sie deckt Authentifizierung (JWT, OIDC, Basic Auth), rollenbasierte Zugriffskontrolle (RBAC), programmatische Sicherheitsprüfungen mit SecurityIdentity und Eingabevalidierung mittels Bean Validation ab. Entwickler erhalten konkrete Codebeispiele für die Konfiguration von CORS-Headern, sicheres Passwort-Hashing mit BCrypt, Vermeidung von SQL-Injection durch parametrisierte Abfragen sowie die Integration von HashiCorp Vault zur Secrets-Verwaltung. Zusätzlich werden Ratenbegrenzung, Sicherheits-Header wie CSP und HSTS, Audit-Logging und die Durchführung von Dependency-Scans mit dem OWASP Dependency-Check behandelt. Die Fähigkeit ist für alle Quarkus-Versionen geeignet und unterstützt sowohl imperative als auch reaktive Programmiermodelle.

Funktioniert mit~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/quarkus-security

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Überprüfung der Quarkus-Sicherheit

Best Practices für die Absicherung von Quarkus-Anwendungen mit Authentifizierung, Autorisierung und Eingabevalidierung.

Wann aktivieren

  • Hinzufügen einer Authentifizierung (JWT, OIDC, Basic Auth)
  • Implementieren einer Autorisierung mit @RolesAllowed oder SecurityIdentity
  • Validieren von Benutzereingaben (Bean Validation, benutzerdefinierte Validatoren)
  • Konfigurieren von CORS oder Sicherheits-Headern
  • Verwalten von Secrets (Vault, Umgebungsvariablen, Konfigurationsquellen)
  • Hinzufügen von Ratenbegrenzung oder Brute-Force-Schutz
  • Scannen von Abhängigkeiten auf CVEs
  • Arbeiten mit MicroProfile JWT oder SmallRye JWT

Authentifizierung

JWT-Authentifizierung

// Geschützte Ressource mit JWT
@Path("/api/protected")
@Authenticated
public class ProtectedResource {

  @Inject
  JsonWebToken jwt;

  @Inject
  SecurityIdentity securityIdentity;

  @GET
  public Response getData() {
    String username = jwt.getName();
    Set<String> roles = jwt.getGroups();
    return Response.ok(Map.of(
        "username", username,
        "roles", roles,
        "principal", securityIdentity.getPrincipal().getName()
    )).build();
  }
}

Konfiguration (application.properties):

mp.jwt.verify.publickey.location=publicKey.pem
mp.jwt.verify.issuer=https://auth.example.com

# OIDC
quarkus.oidc.auth-server-url=https://auth.example.com/realms/myrealm
quarkus.oidc.client-id=backend-service
quarkus.oidc.credentials.secret=${OIDC_SECRET}

Benutzerdefinierter Authentifizierungsfilter

@Provider
@Priority(Priorities.AUTHENTICATION)
public class CustomAuthFilter implements ContainerRequestFilter {

  @Inject
  SecurityIdentity identity;

  @Override
  public void filter(ContainerRequestContext requestContext) {
    String authHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

    // Sofort ablehnen, wenn der Header fehlt oder fehlerhaft ist
    if (authHeader == null || !authHeader.startsWith("Bearer ")) {
      requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
      return;
    }

    String token = authHeader.substring(7);
    if (!validateToken(token)) {
      requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
    }
  }

  private boolean validateToken(String token) {
    // Token-Validierungslogik
    return true;
  }
}

Autorisierung

Rollenbasierte Zugriffskontrolle

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

  @GET
  @Path("/users")
  public List<UserDto> listUsers() {
    return userService.findAll();
  }

  @DELETE
  @Path("/users/{id}")
  @RolesAllowed({"ADMIN", "SUPER_ADMIN"})
  public Response deleteUser(@PathParam("id") Long id) {
    userService.delete(id);
    return Response.noContent().build();
  }
}

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

  @Inject
  SecurityIdentity securityIdentity;

  @GET
  @Path("/{id}")
  @RolesAllowed("USER")
  public Response getUser(@PathParam("id") Long id) {
    // Besitzprüfung
    if (!securityIdentity.hasRole("ADMIN") &&
        !isOwner(id, securityIdentity.getPrincipal().getName())) {
      return Response.status(Response.Status.FORBIDDEN).build();
    }
    return Response.ok(userService.findById(id)).build();
  }

  private boolean isOwner(Long userId, String username) {
    return userService.isOwner(userId, username);
  }
}

Programmatische Sicherheit

@ApplicationScoped
public class SecurityService {

  @Inject
  SecurityIdentity securityIdentity;

  public boolean canAccessResource(Long resourceId) {
    if (securityIdentity.isAnonymous()) {
      return false;
    }

    if (securityIdentity.hasRole("ADMIN")) {
      return true;
    }

    String userId = securityIdentity.getPrincipal().getName();
    return resourceRepository.isOwner(resourceId, userId);
  }
}

Eingabevalidierung

Bean Validation

// SCHLECHT: Keine Validierung
@POST
public Response createUser(UserDto dto) {
  return Response.ok(userService.create(dto)).build();
}

// GUT: Validiertes DTO
public record CreateUserDto(
    @NotBlank @Size(max = 100) String name,
    @NotBlank @Email String email,
    @NotNull @Min(18) @Max(150) Integer age,
    @Pattern(regexp = "^\\+?[1-9]\\d{1,14}$") String phone
) {}

@POST
@Path("/users")
public Response createUser(@Valid CreateUserDto dto) {
  User user = userService.create(dto);
  return Response.status(Response.Status.CREATED).entity(user).build();
}

Benutzerdefinierte Validatoren

@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UsernameValidator.class)
public @interface ValidUsername {
  String message() default "Ungültiges Benutzernamenformat";
  Class<?>[] groups() default {};
  Class<? extends Payload>[] payload() default {};
}

public class UsernameValidator implements ConstraintValidator<ValidUsername, String> {
  @Override
  public boolean isValid(String value, ConstraintValidatorContext context) {
    if (value == null) return false;
    return value.matches("^[a-zA-Z0-9_-]{3,20}$");
  }
}

// Verwendung
public record CreateUserDto(
    @ValidUsername String username,
    @NotBlank @Email String email
) {}

SQL-Injection-Prävention

Panache Active Record (Standardmäßig sicher)

// GUT: Parametrisierte Abfragen mit Panache
List<User> users = User.list("email = ?1 and active = ?2", email, true);

Optional<User> user = User.find("username", username).firstResultOptional();

// GUT: Benannte Parameter
List<User> users = User.list("email = :email and age > :minAge",
    Parameters.with("email", email).and("minAge", 18));

Native Abfragen (Parameter verwenden)

// SCHLECHT: String-Verkettung
@Query(value = "SELECT * FROM users WHERE name = '" + name + "'", nativeQuery = true)

// GUT: Parametrisierte native Abfrage
@Entity
public class User extends PanacheEntity {
  public static List<User> findByEmailNative(String email) {
    return getEntityManager()
        .createNativeQuery("SELECT * FROM users WHERE email = :email", User.class)
        .setParameter("email", email)
        .getResultList();
  }
}

Passwort-Hashing

@ApplicationScoped
public class PasswordService {

  public String hash(String plainPassword) {
    return BcryptUtil.bcryptHash(plainPassword);
  }

  public boolean verify(String plainPassword, String hashedPassword) {
    return BcryptUtil.matches(plainPassword, hashedPassword);
  }
}

// Im Service
@ApplicationScoped
public class UserService {
  @Inject
  PasswordService passwordService;

  @Transactional
  public User register(CreateUserDto dto) {
    String hashedPassword = passwordService.hash(dto.password());
    User user = new User();
    user.email = dto.email();
    user.password = hashedPassword;
    user.persist();
    return user;
  }

  public boolean authenticate(String email, String password) {
    return User.find("email", email)
        .firstResultOptional()
        .map(u -> passwordService.verify(password, u.password))
        .orElse(false);
  }
}

CORS-Konfiguration

# application.properties
quarkus.http.cors=true
quarkus.http.cors.origins=https://app.example.com,https://admin.example.com
quarkus.http.cors.methods=GET,POST,PUT,DELETE
quarkus.http.cors.headers=accept,authorization,content-type,x-requested-with
quarkus.http.cors.exposed-headers=Content-Disposition
quarkus.http.cors.access-control-max-age=24H
quarkus.http.cors.access-control-allow-credentials=true

Secrets-Verwaltung

# application.properties - KEINE Secrets hier

# Verwenden Sie Umgebungsvariablen
quarkus.datasource.username=${DB_USER}
quarkus.datasource.password=${DB_PASSWORD}
quarkus.oidc.credentials.secret=${OIDC_CLIENT_SECRET}

# Oder Vault
quarkus.vault.url=https://vault.example.com
quarkus.vault.authentication.kubernetes.role=my-role

HashiCorp Vault-Integration

@ApplicationScoped
public class SecretService {

  @ConfigProperty(name = "api-key")
  String apiKey; // Wird aus Vault abgerufen

  public String getSecret(String key) {
    return ConfigProvider.getConfig().getValue(key, String.class);
  }
}

Ratenbegrenzung

Sicherheitshinweis: Verwenden Sie niemals direkt X-Forwarded-For – Clients können dies fälschen. Verwenden Sie die tatsächliche Remote-Adresse aus dem Servlet-Request oder eine authentifizierte Identität (API-Key, JWT-Subjekt), sofern verfügbar.

@ApplicationScoped
public class RateLimitFilter implements ContainerRequestFilter {
  private final Map<String, RateLimiter> limiters = new ConcurrentHashMap<>();

  @Inject
  HttpServletRequest servletRequest;

  @Override
  public void filter(ContainerRequestContext requestContext) {
    String clientId = getClientIdentifier();
    RateLimiter limiter = limiters.computeIfAbsent(clientId,
        k -> RateLimiter.create(100.0)); // 100 Anfragen pro Sekunde

    if (!limiter.tryAcquire()) {
      requestContext.abortWith(
          Response.status(429)
              .entity(Map.of("error", "Zu viele Anfragen"))
              .build()
      );
    }
  }

  private String getClientIdentifier() {
    // Verwenden Sie die vom Container bereitgestellte Remote-Adresse (nicht X-Forwarded-For).
    // Wenn hinter einem vertrauenswürdigen Proxy, konfigurieren Sie quarkus.http.proxy.proxy-address-forwarding=true
    // sodass getRemoteAddr() die echte Client-IP zurückgibt.
    return servletRequest.getRemoteAddr();
  }
}

Sicherheits-Header

@Provider
public class SecurityHeadersFilter implements ContainerResponseFilter {

  @Override
  public void filter(ContainerRequestContext request, ContainerResponseContext response) {
    MultivaluedMap<String, Object> headers = response.getHeaders();

    // Clickjacking verhindern
    headers.putSingle("X-Frame-Options", "DENY");

    // XSS-Schutz
    headers.putSingle("X-Content-Type-Options", "nosniff");
    headers.putSingle("X-XSS-Protection", "1; mode=block");

    // HSTS
    headers.putSingle("Strict-Transport-Security", "max-age=31536000; includeSubDomains");

    // CSP – vermeiden Sie 'unsafe-inline' für script-src, da dies den XSS-Schutz aufhebt;
    // verwenden Sie stattdessen Nonces oder Hashes. 'unsafe-inline' für style-src ist akzeptabel,
    // wenn CSS-Frameworks dies erfordern, aber bevorzugen Sie Nonces, wo möglich.
    headers.putSingle("Content-Security-Policy",
        "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'");
  }
}

Audit-Logging

@ApplicationScoped
public class AuditService {
  private static final Logger LOG = Logger.getLogger(AuditService.class);

  @Inject
  SecurityIdentity securityIdentity;

  public void logAccess(String resource, String action) {
    String user = securityIdentity.isAnonymous()
        ? "anonymous"
        : securityIdentity.getPrincipal().getName();

    LOG.infof("AUDIT: user=%s action=%s resource=%s timestamp=%s",
        user, action, resource, Instant.now());
  }
}

// Verwendung in einer Ressource
@Path("/api/sensitive")
public class SensitiveResource {
  @Inject
  AuditService auditService;

  @GET
  @RolesAllowed("ADMIN")
  public Response getData() {
    auditService.logAccess("sensitive-data", "READ");
    return Response.ok(data).build();
  }
}

Dependency-Sicherheitsscan

# Maven
mvn org.owasp:dependency-check-maven:check

# Gradle
./gradlew dependencyCheckAnalyze

# Quarkus-Erweiterungen prüfen
quarkus extension list --installable

Best Practices

  • Verwenden Sie in der Produktion immer HTTPS
  • Aktivieren Sie JWT oder OIDC für zustandslose Authentifizierung
  • Verwenden Sie @RolesAllowed für deklarative Autorisierung
  • Validieren Sie alle Eingaben mit Bean Validation
  • Hashen Sie Passwörter mit BCrypt (niemals im Klartext)
  • Speichern Sie Secrets in Vault oder Umgebungsvariablen
  • Verwenden Sie parametrisierte Abfragen, um SQL-Injection zu verhindern
  • Fügen Sie allen Antworten Sicherheits-Header hinzu
  • Implementieren Sie Ratenbegrenzung für öffentliche Endpunkte
  • Protokollieren Sie sensible Vorgänge mit Audit-Trail
  • Halten Sie Abhängigkeiten aktuell und scannen Sie auf CVEs
  • Verwenden Sie SecurityIdentity für programmatische Prüfungen
  • Legen Sie geeignete CORS-Richtlinien fest
  • Testen Sie Authentifizierungs- und Autorisierungspfade

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

Verwandte Skills