-
Notifications
You must be signed in to change notification settings - Fork 882
Enhance Bearer Authentication Support with Azure IMDS #2523
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
emasab
wants to merge
2
commits into
master
Choose a base branch
from
dev_sr_oautbearer_azure_imds
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<ProjectTypeGuids>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> | ||
<AssemblyName>OAuthOIDC</AssemblyName> | ||
<TargetFramework>net8.0</TargetFramework> | ||
<OutputType>Exe</OutputType> | ||
<LangVersion>7.1</LangVersion> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<!-- nuget package reference: <PackageReference Include="Confluent.SchemaRegistry.Serdes.Json" Version="2.11.1" /> --> | ||
<ProjectReference Include="../../src/Confluent.SchemaRegistry.Serdes.Json/Confluent.SchemaRegistry.Serdes.Json.csproj" /> | ||
</ItemGroup> | ||
|
||
</Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,190 @@ | ||
// Copyright 2022 Confluent Inc. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
// | ||
// Refer to LICENSE for more information. | ||
|
||
using System; | ||
using System.Collections.Generic; | ||
using System.Text; | ||
using System.Text.RegularExpressions; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using Confluent.Kafka; | ||
using Confluent.Kafka.Admin; | ||
using Confluent.Kafka.SyncOverAsync; | ||
using Newtonsoft.Json; | ||
using Confluent.SchemaRegistry; | ||
using Confluent.SchemaRegistry.Serdes; | ||
|
||
/// <summary> | ||
/// An example demonstrating how to produce a message to | ||
/// a topic, and then reading it back again using a consumer. | ||
/// The authentication uses the OpenID Connect method of the OAUTHBEARER SASL mechanism. | ||
/// The token is acquired from the Azure Instance Metadata Service (IMDS) | ||
/// using metadata based secret-less authentication. | ||
/// </summary> | ||
namespace Confluent.Kafka.Examples.OAuthOIDCAzureIMDS | ||
{ | ||
|
||
class User | ||
{ | ||
[JsonRequired] // use Newtonsoft.Json annotations | ||
[JsonProperty("name")] | ||
public string Name { get; set; } | ||
|
||
[JsonRequired] | ||
[JsonProperty("favorite_color")] | ||
public string FavoriteColor { get; set; } | ||
|
||
[JsonProperty("favorite_number")] | ||
public long FavoriteNumber { get; set; } | ||
} | ||
|
||
public class Program | ||
{ | ||
private const string azureIMDSQueryParams = "api-version=&resource=&client_id="; | ||
private const string kafkaLogicalCluster = "your-logical-cluster"; | ||
private const string identityPoolId = "your-identity-pool-id"; | ||
|
||
public static async Task Main(string[] args) | ||
{ | ||
if (args.Length != 3) | ||
{ | ||
Console.WriteLine("Usage: .. brokerList schemaRegistryUrl"); | ||
return; | ||
} | ||
var bootstrapServers = args[1]; | ||
var schemaRegistryUrl = args[2]; | ||
var topicName = Guid.NewGuid().ToString(); | ||
var groupId = Guid.NewGuid().ToString(); | ||
|
||
var commonConfig = new ClientConfig | ||
{ | ||
BootstrapServers = bootstrapServers, | ||
SecurityProtocol = SecurityProtocol.SaslPlaintext, | ||
SaslMechanism = SaslMechanism.OAuthBearer, | ||
SaslOauthbearerMethod = SaslOauthbearerMethod.Oidc, | ||
SaslOauthbearerMetadataAuthenticationType = SaslOauthbearerMetadataAuthenticationType.AzureIMDS, | ||
SaslOauthbearerConfig = $"query={azureIMDSQueryParams}", | ||
SaslOauthbearerExtensions = $"logicalCluster={kafkaLogicalCluster},identityPoolId={identityPoolId}" | ||
}; | ||
|
||
var consumerConfig = new ConsumerConfig | ||
{ | ||
BootstrapServers = bootstrapServers, | ||
SecurityProtocol = SecurityProtocol.SaslPlaintext, | ||
SaslMechanism = SaslMechanism.OAuthBearer, | ||
SaslOauthbearerMethod = SaslOauthbearerMethod.Oidc, | ||
GroupId = groupId, | ||
AutoOffsetReset = AutoOffsetReset.Earliest, | ||
EnableAutoOffsetStore = false | ||
}; | ||
|
||
var schemaRegistryConfig = new SchemaRegistryConfig | ||
{ | ||
Url = schemaRegistryUrl, | ||
BearerAuthCredentialsSource = BearerAuthCredentialsSource.OAuthBearerAzureIMDS, | ||
BearerAuthTokenEndpointQuery = azureIMDSQueryParams, | ||
BearerAuthLogicalCluster = kafkaLogicalCluster, | ||
BearerAuthIdentityPoolId = identityPoolId | ||
}; | ||
|
||
try | ||
{ | ||
createTopic(commonConfig, topicName); | ||
} | ||
catch (CreateTopicsException e) | ||
{ | ||
Console.WriteLine($"An error occurred creating topic {e.Results[0].Topic}: {e.Results[0].Error.Reason}"); | ||
Environment.Exit(1); | ||
} | ||
|
||
using (var schemaRegistry = new CachedSchemaRegistryClient(schemaRegistryConfig)) | ||
using (var producer = new ProducerBuilder<Null, User>(commonConfig) | ||
.SetValueSerializer(new JsonSerializer<User>(schemaRegistry)) | ||
.Build()) | ||
using (var consumer = new ConsumerBuilder<Ignore, User>(consumerConfig) | ||
.SetValueDeserializer(new JsonDeserializer<User>(schemaRegistry).AsSyncOverAsync()).Build()) | ||
{ | ||
consumer.Subscribe(topicName); | ||
|
||
var cancelled = false; | ||
CancellationTokenSource cts = new CancellationTokenSource(); | ||
|
||
Console.CancelKeyPress += (_, e) => | ||
{ | ||
e.Cancel = true; // prevent the process from terminating. | ||
cancelled = true; | ||
cts.Cancel(); | ||
}; | ||
|
||
try | ||
{ | ||
while (!cancelled) | ||
{ | ||
var msg = new User | ||
{ | ||
Name = "user-" + Guid.NewGuid().ToString(), | ||
FavoriteColor = "blue", | ||
FavoriteNumber = 7 | ||
}; | ||
|
||
try | ||
{ | ||
var deliveryReport = await producer.ProduceAsync(topicName, new Message<Null, User> { Value = msg }); | ||
Console.WriteLine($"Produced message to {deliveryReport.TopicPartitionOffset}, {msg}"); | ||
} | ||
catch (ProduceException<Null, User> e) | ||
{ | ||
Console.WriteLine($"failed to deliver message: {e.Message} [{e.Error.Code}]"); | ||
} | ||
|
||
try | ||
{ | ||
var consumeResult = consumer.Consume(cts.Token); | ||
Console.WriteLine($"Received message at {consumeResult.TopicPartitionOffset}: {consumeResult.Message.Value}"); | ||
try | ||
{ | ||
consumer.StoreOffset(consumeResult); | ||
} | ||
catch (KafkaException e) | ||
{ | ||
Console.WriteLine($"Store Offset error: {e.Error.Reason}"); | ||
} | ||
} | ||
catch (ConsumeException e) | ||
{ | ||
Console.WriteLine($"Consume error: {e.Error.Reason}"); | ||
} | ||
} | ||
} | ||
catch (OperationCanceledException) | ||
{ | ||
Console.WriteLine("Closing consumer."); | ||
consumer.Close(); | ||
} | ||
} | ||
} | ||
|
||
private static void createTopic(ClientConfig config, String topicName) | ||
{ | ||
using (var adminClient = new AdminClientBuilder(config).Build()) | ||
{ | ||
adminClient.CreateTopicsAsync(new TopicSpecification[] { | ||
new TopicSpecification { Name = topicName, ReplicationFactor = 3, NumPartitions = 1 } }).Wait(); ; | ||
} | ||
} | ||
} | ||
|
||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.