Skip to content

Instantly share code, notes, and snippets.

@drawcode
Created March 27, 2021 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drawcode/d845d4fedaed4bc316911290bb840400 to your computer and use it in GitHub Desktop.
Save drawcode/d845d4fedaed4bc316911290bb840400 to your computer and use it in GitHub Desktop.
csharp.auth.jwt.cs
using System;
using System.IO;
using System.Security.Cryptography;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
namespace Auth.Util {
class SignToken {
static void Main(string[] args) {
try {
// reading the content of a private key PEM file, PKCS8 encoded
string privateKeyPem = File.ReadAllText("...");
// keeping only the payload of the key
privateKeyPem = privateKeyPem.Replace("-----BEGIN PRIVATE KEY-----", "");
privateKeyPem = privateKeyPem.Replace("-----END PRIVATE KEY-----", "");
byte[] privateKeyRaw = Convert.FromBase64String(privateKeyPem);
// creating the RSA key
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.ImportPkcs8PrivateKey(new ReadOnlySpan<byte>(privateKeyRaw), out _);
RsaSecurityKey rsaSecurityKey = new RsaSecurityKey(provider);
// Generating the token
var now = DateTime.UtcNow;
var claims = new[] {
new Claim(JwtRegisteredClaimNames.Sub, "YOUR_CLIENTID"),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var handler = new JwtSecurityTokenHandler();
var token = new JwtSecurityToken
(
"YOUR_CLIENTID",
"https://AAAS_PLATFORM/idp/YOUR_TENANT/authn/token",
claims,
now.AddMilliseconds(-30),
now.AddMinutes(60),
new SigningCredentials(rsaSecurityKey, SecurityAlgorithms.RsaSha256)
);
// handler.WriteToken(token) returns the token ready to send to AaaS !
Console.WriteLine( handler.WriteToken(token) );
}
catch (Exception e) {
Console.WriteLine(e.ToString());
Console.WriteLine(
new System.Diagnostics.StackTrace().ToString()
);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment