-
Notifications
You must be signed in to change notification settings - Fork 879
/
Copy pathProgram.cs
179 lines (156 loc) · 7.32 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
// 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 Newtonsoft.Json;
/// <summary>
/// An example showing producer
/// with a custom OAUTHBEARER token implementation.
/// </summary>
namespace Confluent.Kafka.Examples.OAuthProducer
{
/// <summary>
/// A class to store the token and related properties.
/// </summary>
class OAuthBearerToken
{
public string TokenValue { get; set; }
public long Expiration { get; set; }
public String Principal { get; set; }
public Dictionary<String, String> Extensions { get; set; }
}
public class Program
{
private const String OauthConfigRegexPattern = "^(\\s*(\\w+)\\s*=\\s*(\\w+))+\\s*$"; // 1 or more name=value pairs with optional ignored whitespace
private const String OauthConfigKeyValueRegexPattern = "(\\w+)\\s*=\\s*(\\w+)"; // Extract key=value pairs from OAuth Config
private const String PrincipalClaimNameKey = "principalClaimName";
private const String PrincipalKey = "principal";
private const String ScopeKey = "scope";
public static async Task Main(string[] args)
{
if (args.Length != 4)
{
Console.WriteLine("Usage: .. brokerList topic \"principal=<value> scope=<scope>\"");
return;
}
string bootstrapServers = args[1];
string topicName = args[2];
string oauthConf = args[3];
if (!Regex.IsMatch(oauthConf, OauthConfigRegexPattern))
{
Console.WriteLine("Invalid OAuth config passed.");
Environment.Exit(1);
}
var producerConfig = new ProducerConfig
{
BootstrapServers = bootstrapServers,
SecurityProtocol = SecurityProtocol.SaslPlaintext,
SaslMechanism = SaslMechanism.OAuthBearer,
SaslOauthbearerConfig = oauthConf,
};
// Callback to handle OAuth bearer token refresh. It creates an unsecured JWT based on the configuration defined
// in OAuth Config and sets the token on the client for use in any future authentication attempt.
// It must be invoked whenever the client requires a token (i.e. when it first starts and when the
// previously-received token is 80% of the way to its expiration time).
void OauthCallback(IClient client, string cfg)
{
try
{
var token = retrieveUnsecuredToken(cfg);
client.OAuthBearerSetToken(token.TokenValue, token.Expiration, token.Principal);
}
catch (Exception e)
{
client.OAuthBearerSetTokenFailure(e.ToString());
}
}
using (var producer = new ProducerBuilder<string, string>(producerConfig)
.SetOAuthBearerTokenRefreshHandler(OauthCallback).Build())
{
Console.WriteLine("\n-----------------------------------------------------------------------");
Console.WriteLine($"Producer {producer.Name} producing on topic {topicName}.");
Console.WriteLine("-----------------------------------------------------------------------");
Console.WriteLine("Ctrl-C to quit.\n");
var cancelled = false;
var msgCnt = 1;
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true; // prevent the process from terminating.
cancelled = true;
};
while (!cancelled)
{
var msg = String.Format("Producer example, message #{0}", msgCnt++);
try
{
var deliveryReport = await producer.ProduceAsync(topicName, new Message<string, string> { Value = msg });
Console.WriteLine($"Produced message to {deliveryReport.TopicPartitionOffset}, {msg}");
}
catch (ProduceException<string, string> e)
{
Console.WriteLine($"failed to deliver message: {e.Message} [{e.Error.Code}]");
}
Thread.Sleep(1000); // sleep one second
}
}
}
private static string ToUnpaddedBase64(string s)
=> Convert.ToBase64String(Encoding.UTF8.GetBytes(s)).TrimEnd('=');
private static OAuthBearerToken retrieveUnsecuredToken(String oauthConfig)
{
Console.WriteLine("Refreshing the token");
var parsedConfig = new Dictionary<String, String>();
foreach (Match match in Regex.Matches(oauthConfig, OauthConfigKeyValueRegexPattern))
{
parsedConfig[match.Groups[1].ToString()] = match.Groups[2].ToString();
}
if (!parsedConfig.ContainsKey(PrincipalKey) || !parsedConfig.ContainsKey(ScopeKey) || parsedConfig.Count > 2)
{
throw new Exception($"Invalid OAuth config {oauthConfig} passed.");
}
var principalClaimName = parsedConfig.ContainsKey(PrincipalClaimNameKey) ? parsedConfig[PrincipalClaimNameKey] : "sub";
var principal = parsedConfig[PrincipalKey];
var scopeValue = parsedConfig[ScopeKey];
var issuedAt = DateTimeOffset.UtcNow;
var expiresAt = issuedAt.AddSeconds(5); // setting a low value to show the token refresh in action.
var header = new
{
alg = "none",
typ = "JWT"
};
var payload = new Dictionary<String, Object>
{
{principalClaimName, principal},
{"iat", issuedAt.ToUnixTimeSeconds()},
{"exp", expiresAt.ToUnixTimeSeconds()},
{ScopeKey, scopeValue}
};
var headerJson = JsonConvert.SerializeObject(header);
var payloadJson = JsonConvert.SerializeObject(payload);
return new OAuthBearerToken
{
TokenValue = $"{ToUnpaddedBase64(headerJson)}.{ToUnpaddedBase64(payloadJson)}.",
Expiration = expiresAt.ToUnixTimeMilliseconds(),
Principal = principal,
Extensions = new Dictionary<string, string>()
};
}
}
}