Hi,
I am having issues finding a sample of C# code to connect to my external app using JWT. Since uid/password for OAuth2 will be discontinued as of February, I am getting started now on replacing that with JWT authentication. The cert has been created and uploaded from the connecting server, so that should be set up properly. Now I need to convert my code to use JWT for authentication instead of the current uid/password method, but am unable to find a reliable sample of code. Can anyone out there help?
#Authentication.clientId #JWT Bearer Token Exhcange #OAuth 2.0
byte[] privateKeyRaw // contain the key in base 64
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.ImportPkcs8PrivateKey(new ReadOnlySpan<byte>(privateKeyRaw), out _);
RsaSecurityKey rsaSecurityKey = new RsaSecurityKey(provider);
var now = DateTime.UtcNow;
var claims = new[] {
new Claim(JwtRegisteredClaimNames.Iss, cfg.AppSettings.Settings["ClientId"].Value),
new Claim(JwtRegisteredClaimNames.Sub, cfg.AppSettings.Settings["Username"].Value),
new Claim(JwtRegisteredClaimNames.Exp, ((DateTimeOffset.Now.ToUnixTimeMilliseconds() / 1000) + 300).ToString()),
};
var handler = new JwtSecurityTokenHandler();
var token = new JwtSecurityToken
(
cfg.AppSettings.Settings["ClientId"].Value,
cfg.AppSettings.Settings["LoginUrl"].Value,
claims,
now.AddMilliseconds(-30),
now.AddMinutes(60),
new SigningCredentials(rsaSecurityKey, SecurityAlgorithms.RsaSha256)
);
jwt_token = handler.WriteToken(token);
// To do
// Connect to the api {{url}}/services/oauth2/token
// send the jwt in the body parameter
var content = new FormUrlEncodedContent(
[
new KeyValuePair<string, string>("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"),
new KeyValuePair<string, string>("assertion", jwt_token)
]);
HttpClient _httpClient = new();
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(cfg.AppSettings.Settings["LoginUrl"].Value + "/services/oauth2/token"),
Content = content
};
var responseMessage = await _httpClient.SendAsync(request).ConfigureAwait(false);
var response = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);