|
| 1 | +// Copyright 2022 Confluent Inc. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | +// |
| 15 | +// Refer to LICENSE for more information. |
| 16 | + |
| 17 | +using System; |
| 18 | +using System.Collections.Generic; |
| 19 | +using System.Text; |
| 20 | +using System.Text.RegularExpressions; |
| 21 | +using System.Threading; |
| 22 | +using System.Threading.Tasks; |
| 23 | +using Confluent.Kafka; |
| 24 | +using Confluent.Kafka.Admin; |
| 25 | +using Confluent.Kafka.SyncOverAsync; |
| 26 | +using Newtonsoft.Json; |
| 27 | +using Confluent.SchemaRegistry; |
| 28 | +using Confluent.SchemaRegistry.Serdes; |
| 29 | + |
| 30 | +/// <summary> |
| 31 | +/// An example demonstrating how to produce a message to |
| 32 | +/// a topic, and then reading it back again using a consumer. |
| 33 | +/// The authentication uses the OpenID Connect method of the OAUTHBEARER SASL mechanism. |
| 34 | +/// The token is acquired from the Azure Instance Metadata Service (IMDS) |
| 35 | +/// using metadata based secret-less authentication. |
| 36 | +/// </summary> |
| 37 | +namespace Confluent.Kafka.Examples.OAuthOIDCAzureIMDS |
| 38 | +{ |
| 39 | + |
| 40 | + class User |
| 41 | + { |
| 42 | + [JsonRequired] // use Newtonsoft.Json annotations |
| 43 | + [JsonProperty("name")] |
| 44 | + public string Name { get; set; } |
| 45 | + |
| 46 | + [JsonRequired] |
| 47 | + [JsonProperty("favorite_color")] |
| 48 | + public string FavoriteColor { get; set; } |
| 49 | + |
| 50 | + [JsonProperty("favorite_number")] |
| 51 | + public long FavoriteNumber { get; set; } |
| 52 | + } |
| 53 | + |
| 54 | + public class Program |
| 55 | + { |
| 56 | + private const string azureIMDSQueryParams = "api-version=&resource=&client_id="; |
| 57 | + |
| 58 | + public static async Task Main(string[] args) |
| 59 | + { |
| 60 | + if (args.Length != 3) |
| 61 | + { |
| 62 | + Console.WriteLine("Usage: .. brokerList schemaRegistryUrl"); |
| 63 | + return; |
| 64 | + } |
| 65 | + var bootstrapServers = args[1]; |
| 66 | + var schemaRegistryUrl = args[2]; |
| 67 | + var topicName = Guid.NewGuid().ToString(); |
| 68 | + var groupId = Guid.NewGuid().ToString(); |
| 69 | + |
| 70 | + var commonConfig = new ClientConfig |
| 71 | + { |
| 72 | + BootstrapServers = bootstrapServers, |
| 73 | + SecurityProtocol = SecurityProtocol.SaslPlaintext, |
| 74 | + SaslMechanism = SaslMechanism.OAuthBearer, |
| 75 | + SaslOauthbearerMethod = SaslOauthbearerMethod.Oidc, |
| 76 | + SaslOauthbearerMetadataAuthenticationType = SaslOauthbearerMetadataAuthenticationType.AzureIMDS, |
| 77 | + SaslOauthbearerConfig = $"query={azureIMDSQueryParams}", |
| 78 | + }; |
| 79 | + |
| 80 | + var consumerConfig = new ConsumerConfig |
| 81 | + { |
| 82 | + BootstrapServers = bootstrapServers, |
| 83 | + SecurityProtocol = SecurityProtocol.SaslPlaintext, |
| 84 | + SaslMechanism = SaslMechanism.OAuthBearer, |
| 85 | + SaslOauthbearerMethod = SaslOauthbearerMethod.Oidc, |
| 86 | + GroupId = groupId, |
| 87 | + AutoOffsetReset = AutoOffsetReset.Earliest, |
| 88 | + EnableAutoOffsetStore = false |
| 89 | + }; |
| 90 | + |
| 91 | + var schemaRegistryConfig = new SchemaRegistryConfig |
| 92 | + { |
| 93 | + Url = schemaRegistryUrl, |
| 94 | + BearerAuthCredentialsSource = BearerAuthCredentialsSource.OAuthBearerAzureIMDS, |
| 95 | + BearerAuthTokenEndpointQuery = azureIMDSQueryParams, |
| 96 | + }; |
| 97 | + |
| 98 | + try |
| 99 | + { |
| 100 | + createTopic(commonConfig, topicName); |
| 101 | + } |
| 102 | + catch (CreateTopicsException e) |
| 103 | + { |
| 104 | + Console.WriteLine($"An error occurred creating topic {e.Results[0].Topic}: {e.Results[0].Error.Reason}"); |
| 105 | + Environment.Exit(1); |
| 106 | + } |
| 107 | + |
| 108 | + using (var schemaRegistry = new CachedSchemaRegistryClient(schemaRegistryConfig)) |
| 109 | + using (var producer = new ProducerBuilder<Null, User>(commonConfig) |
| 110 | + .SetValueSerializer(new JsonSerializer<User>(schemaRegistry)) |
| 111 | + .Build()) |
| 112 | + using (var consumer = new ConsumerBuilder<Ignore, User>(consumerConfig) |
| 113 | + .SetValueDeserializer(new JsonDeserializer<User>(schemaRegistry).AsSyncOverAsync()).Build()) |
| 114 | + { |
| 115 | + consumer.Subscribe(topicName); |
| 116 | + |
| 117 | + var cancelled = false; |
| 118 | + CancellationTokenSource cts = new CancellationTokenSource(); |
| 119 | + |
| 120 | + Console.CancelKeyPress += (_, e) => |
| 121 | + { |
| 122 | + e.Cancel = true; // prevent the process from terminating. |
| 123 | + cancelled = true; |
| 124 | + cts.Cancel(); |
| 125 | + }; |
| 126 | + |
| 127 | + try |
| 128 | + { |
| 129 | + while (!cancelled) |
| 130 | + { |
| 131 | + var msg = new User |
| 132 | + { |
| 133 | + Name = "user-" + Guid.NewGuid().ToString(), |
| 134 | + FavoriteColor = "blue", |
| 135 | + FavoriteNumber = 7 |
| 136 | + }; |
| 137 | + |
| 138 | + try |
| 139 | + { |
| 140 | + var deliveryReport = await producer.ProduceAsync(topicName, new Message<Null, User> { Value = msg }); |
| 141 | + Console.WriteLine($"Produced message to {deliveryReport.TopicPartitionOffset}, {msg}"); |
| 142 | + } |
| 143 | + catch (ProduceException<Null, User> e) |
| 144 | + { |
| 145 | + Console.WriteLine($"failed to deliver message: {e.Message} [{e.Error.Code}]"); |
| 146 | + } |
| 147 | + |
| 148 | + try |
| 149 | + { |
| 150 | + var consumeResult = consumer.Consume(cts.Token); |
| 151 | + Console.WriteLine($"Received message at {consumeResult.TopicPartitionOffset}: {consumeResult.Message.Value}"); |
| 152 | + try |
| 153 | + { |
| 154 | + consumer.StoreOffset(consumeResult); |
| 155 | + } |
| 156 | + catch (KafkaException e) |
| 157 | + { |
| 158 | + Console.WriteLine($"Store Offset error: {e.Error.Reason}"); |
| 159 | + } |
| 160 | + } |
| 161 | + catch (ConsumeException e) |
| 162 | + { |
| 163 | + Console.WriteLine($"Consume error: {e.Error.Reason}"); |
| 164 | + } |
| 165 | + } |
| 166 | + } |
| 167 | + catch (OperationCanceledException) |
| 168 | + { |
| 169 | + Console.WriteLine("Closing consumer."); |
| 170 | + consumer.Close(); |
| 171 | + } |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + private static void createTopic(ClientConfig config, String topicName) |
| 176 | + { |
| 177 | + using (var adminClient = new AdminClientBuilder(config).Build()) |
| 178 | + { |
| 179 | + adminClient.CreateTopicsAsync(new TopicSpecification[] { |
| 180 | + new TopicSpecification { Name = topicName, ReplicationFactor = 3, NumPartitions = 1 } }).Wait(); ; |
| 181 | + } |
| 182 | + } |
| 183 | + } |
| 184 | + |
| 185 | +} |
0 commit comments