SASL Authentication | Laravel Kafka              

 [ K Laravel Kafka ](/) [Docs](/docs) [Blog](https://laravelkafka.com/blog) [GitHub](https://github.com/mateusjunges/laravel-kafka) 

     Search ⌘K       [    Login with GitHub Login ](https://laravelkafka.com/oauth/github/redirect) 

    Docs for version         

   selected

 v3.0     

 v2.13     

 v2.12     

 v2.11     

 v2.10     

 v2.9     

 v2.8     

 v1.13   

- - [ Introduction ](/docs/v3.0/introduction)
    - [ Requirements ](/docs/v3.0/requirements)
    - [ Installation and Setup ](/docs/v3.0/installation-and-setup)
    - [ Questions and issues ](/docs/v3.0/questions-and-issues)
    - [ Changelog ](/docs/v3.0/changelog)
    - [ Upgrade guide ](/docs/v3.0/upgrade-guide)
    - [ Example docker-compose file ](/docs/v3.0/example-docker-compose)
- Producing messages
    ------------------

    - [ Producing messages ](/docs/v3.0/producing-messages/producing-messages)
    - [ Configuring your kafka producer ](/docs/v3.0/producing-messages/configuring-producers)
    - [ Configuring message payload ](/docs/v3.0/producing-messages/configuring-message-payload)
    - [ Custom serializers ](/docs/v3.0/producing-messages/custom-serializers)
    - [ Publishing to kafka ](/docs/v3.0/producing-messages/publishing-to-kafka)
- Consuming messages
    ------------------

    - [ Creating a kafka consumer ](/docs/v3.0/consuming-messages/creating-consumer)
    - [ Subscribing to kafka topics ](/docs/v3.0/consuming-messages/subscribing-to-kafka-topics)
    - [ Using regex to subscribe to kafka topics ](/docs/v3.0/consuming-messages/using-regex-to-subscribe-to-kafka-topics)
    - [ Assigning consumers to a topic partition ](/docs/v3.0/consuming-messages/assigning-partitions)
    - [ Consuming messages from specific offsets ](/docs/v3.0/consuming-messages/consuming-from-specific-offsets)
    - [ Consumer groups ](/docs/v3.0/consuming-messages/consumer-groups)
    - [ Partition Discovery and Dynamic Assignment ](/docs/v3.0/consuming-messages/partition-discovery)
    - [ Message handlers ](/docs/v3.0/consuming-messages/message-handlers)
    - [ Configuring consumer options ](/docs/v3.0/consuming-messages/configuring-consumer-options)
    - [ Handling failed messages ](/docs/v3.0/consuming-messages/handling-failed-messages)
    - [ Custom deserializers ](/docs/v3.0/consuming-messages/custom-deserializers)
    - [ Consuming messages ](/docs/v3.0/consuming-messages/consuming-messages)
    - [ Pausing partitions ](/docs/v3.0/consuming-messages/pausing-partitions)
    - [ Consumer classes ](/docs/v3.0/consuming-messages/class-structure)
    - [ Using consumers with Laravel Telescope ](/docs/v3.0/consuming-messages/laravel-telescope)
- Advanced usage
    --------------

    - [ Connections ](/docs/v3.0/advanced-usage/connections)
    - [ Replacing the default serializer/deserializer ](/docs/v3.0/advanced-usage/replacing-default-serializer)
    - [ Graceful shutdown ](/docs/v3.0/advanced-usage/graceful-shutdown)
    - [ Running consumers in production ](/docs/v3.0/advanced-usage/running-consumers-in-production)
    - [ SASL Authentication ](/docs/v3.0/advanced-usage/sasl-authentication)
    - [ Custom Committers ](/docs/v3.0/advanced-usage/custom-committers)
    - [ Manual Commit ](/docs/v3.0/advanced-usage/manual-commit)
    - [ Middlewares ](/docs/v3.0/advanced-usage/middlewares)
    - [ Stop consumer when there are no messages left ](/docs/v3.0/advanced-usage/stop-consumer-after-last-message)
    - [ Stop consumer on demand ](/docs/v3.0/advanced-usage/stopping-a-consumer)
    - [ Writing custom loggers ](/docs/v3.0/advanced-usage/custom-loggers)
    - [ Before and after callbacks ](/docs/v3.0/advanced-usage/before-callbacks)
    - [ Setting global configurations ](/docs/v3.0/advanced-usage/setting-global-configuration)
    - [ Sending multiple messages with the same producer ](/docs/v3.0/advanced-usage/sending-multiple-messages-with-the-same-producer)
    - [ Events ](/docs/v3.0/advanced-usage/events)
    - [ Consumer lag ](/docs/v3.0/advanced-usage/consumer-lag)
- Testing
    -------

    - [ Kafka fake ](/docs/v3.0/testing/fake)
    - [ Assert Published ](/docs/v3.0/testing/assert-published)
    - [ Assert published On ](/docs/v3.0/testing/assert-published-on)
    - [ Assert not published ](/docs/v3.0/testing/assert-not-published)
    - [ Assert nothing published ](/docs/v3.0/testing/assert-nothing-published)
    - [ Assert published times ](/docs/v3.0/testing/assert-published-times)
    - [ Assert published on times ](/docs/v3.0/testing/assert-published-on-times)
    - [ Mocking your kafka consumer ](/docs/v3.0/testing/mocking-your-kafka-consumer)

  SASL Authentication 
=====================

  Sponsorship 

Support Laravel Kafka by sponsoring me!

Laravel Kafka is free and Open Source software, built to empower developers like you. Your support helps maintain and enhance the project. If you find it valuable, please consider sponsoring me on GitHub. Every contribution makes a difference and keeps the development going strong! Thank you!

 [   Become a Sponsor ](https://github.com/sponsors/mateusjunges) Want to hide this message? Sponsor at any tier of $10/month or more! 

SASL allows your producers and your consumers to authenticate to your Kafka cluster, which verifies their identity. It's also a secure way to enable your clients to endorse an identity.

SASL is configured per connection, in your `config/kafka.php` file. It is used by the producer and by every consumer of the connection when a username is set. The security protocol then becomes `SASL_SSL` when it is `SSL` or `SASL_SSL`, and `SASL_PLAINTEXT` otherwise, so setting credentials never removes the encryption of a connection:

         ```
'connections' => [
    'default' => [
        'brokers' => env('KAFKA_BROKERS'),
        'security_protocol' => 'SASL_SSL',
        'sasl' => [
            'mechanism' => 'SCRAM-SHA-512',
            'username' => env('KAFKA_USERNAME'),
            'password' => env('KAFKA_PASSWORD'),
        ],
    ],
],
```

To use different credentials for a single consumer, you can use the `withSasl` method of the consumer builder. The mechanism and the security protocol accept the `Junges\Kafka\Config\SaslMechanism` and `Junges\Kafka\Config\SecurityProtocol` enums, or their string values. The security protocol is optional: by default, `SASL_SSL` is used when the connection is encrypted, using `SSL` or `SASL_SSL`, and `SASL_PLAINTEXT` otherwise, so a consumer never connects with less encryption than its connection:

         ```
use Junges\Kafka\Config\SaslMechanism;
use Junges\Kafka\Config\SecurityProtocol;

$consumer = \Junges\Kafka\Facades\Kafka::consumer(['orders'])
    ->withSasl(
        username: 'username',
        password: 'password',
        mechanism: SaslMechanism::SCRAM_SHA_512,
        securityProtocol: SecurityProtocol::SASL_SSL,
    );
```

The available mechanisms are `PLAIN`, `SCRAM_SHA_256`, `SCRAM_SHA_512`, `GSSAPI` and `OAUTHBEARER`.

### [](#content-oauthbearer-authentication "Permalink")OAUTHBEARER Authentication

If your Kafka cluster requires OAuth 2.0 (OAUTHBEARER) authentication, which is common with Confluent Cloud, AWS MSK with IAM, or enterprise deployments, you can use the `onOAuthBearerTokenRefresh` method. This registers a callback that librdkafka invokes whenever it needs a fresh token.

The callback is usually registered on the connection, in the `boot` method of a service provider, so it is used by the producer and by every consumer of the connection. Set the `sasl.mechanisms` option to `OAUTHBEARER` in the connection options:

         ```
use Junges\Kafka\Facades\Kafka;

Kafka::connection()->onOAuthBearerTokenRefresh(function ($client, string $oauthConfig): void {
    $client->oauthbearerSetToken(fetchTokenFromIdP(), getTokenExpiryMs(), 'my-client-id');
});
```

You can also register it for a single consumer:

         ```
use Junges\Kafka\Facades\Kafka;

$consumer = Kafka::consumer(['my.topic'])
    ->withOptions([
        'security.protocol' => 'SASL_SSL',
        'sasl.mechanisms'   => 'OAUTHBEARER',
    ])
    ->onOAuthBearerTokenRefresh(function ($consumer, string $oauthConfig): void {
        $token      = fetchTokenFromIdP();
        $expiresMs  = getTokenExpiryMs($token);
        $principal   = 'my-client-id';
        $extensions = [
            'logicalCluster' => 'lkc-xxxxx',
            'identityPoolId' => 'pool-xxxxx',
        ];

        $consumer->oauthbearerSetToken($token, $expiresMs, $principal, $extensions);
    })
    ->withHandler(new MyMessageHandler())
    ->build()
    ->consume();
```

The callback receives two arguments: the `RdKafka\KafkaConsumer` (or `RdKafka\Producer`) instance and the `oauthbearer_config` string from your librdkafka configuration. Inside the callback, call `$consumer->oauthbearerSetToken()` to provide the token, or `$consumer->oauthbearerSetTokenFailure($reason)` if the token could not be obtained.

This method is available on both connections and the consumer builder.

### [](#content-tls-authentication "Permalink")TLS Authentication

For using TLS authentication with Laravel Kafka you can configure your connection using the following options:

         ```
'connections' => [
    'default' => [
        'brokers' => env('KAFKA_BROKERS'),
        'security_protocol' => 'SSL',
        'options' => [
            'ssl.ca.location' => '/some/location/kafka.crt',
            'ssl.certificate.location' => '/some/location/client.crt',
            'ssl.key.location' => '/some/location/client.key',
            'ssl.endpoint.identification.algorithm' => 'none',
        ],
    ],
],
```

Previous

 [    Running consumers in production ](https://laravelkafka.com/docs/v3.0/advanced-usage/running-consumers-in-production) 

Next

 [ Custom Committers    ](https://laravelkafka.com/docs/v3.0/advanced-usage/custom-committers) 

 Sponsors

 [ version="1.0" encoding="UTF-8"?       EasyCal ](https://easycal.app/) 

 [       Search  ⌘ K   ](https://typesense.org/)
