cancel
Showing results for 
Search instead for 
Did you mean: 

Code stage for generating JWT token using Private key

Sheela
Level 6
Im trying to generate JWT token using Code stage with Private Key,  Aud, email fields. When I try to use RSACryptoServiceProvider to ImportPkcs8PrivateKey, Im getting below error System.Service.Cryptography.RSACryptoServiceProvider  does not contain ImportPkcs8PrivateKey or no extension method 'ImportPkcs8PrivateKey ' of type argument system.Service.Cryptography.RS....

I downloaded System.Service.Cryptography.csp dll from nuget and imported in the code stage.
Could you please help me to resolve this issue.

I have taken below code as reference to generate token.
using System;
using System.IO;
using System.Security.Cryptography;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;

namespace AaaSDocumentation
{
    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()
                );
            }

        }
    }
}


------------------------------
Sheela Parthasarathy
Assistant Consultant
TCS
Pacific/Apia
------------------------------
6 REPLIES 6

Hi Sheela,

Can you share the VBO that you have created?

------------------------------
Shashank Kumar
DX Integrations Partner Consultant
Blue Prism
Singapore
+6581326707
------------------------------

Hi Shashank,

Thanks for responding back.
I cannot upload the VBO. So I have attached the screenshot of my VBO configurations.
Though my code is not completed yet, I was validating on each step and I was stuck with this error.
Im using .net 4.7 and Blue Prism 6.5.1.
I downloaded lib from NuGet Gallery.


------------------------------
Sheela Parthasarathy
Assistant Consultant
TCS
Pacific/Apia
------------------------------

Hi,

The function you are trying to use is compatible with .net 5.0+ that is why you are getting the mentioned error.

RSA.ImportPkcs8PrivateKey(ReadOnlySpan<Byte>, Int32) Method (System.Security.Cryptography) | Microsoft Docs



------------------------------
Gopal Bhaire
Analyst
Accenture
------------------------------

Hi Gopal,

Thanks for replying.
Is there any other function which I can use in .net 4.7 for creating a token.

------------------------------
Sheela Parthasarathy
Assistant Consultant
TCS
Pacific/Apia
------------------------------

Hi Sheela,

You can try the GitHub - jwt-dotnet/jwt: Jwt.Net, a JWT (JSON Web Token) implementation for .NET for creating a token.



------------------------------
Gopal Bhaire
Analyst
Accenture
------------------------------

Hi Sheela,

If you are after an example that demonstrates how you can take in a private key (and optionally a public key for validation), you may check out the below article:

https://stackoverflow.com/questions/38794670/how-to-sign-a-jwt-using-rs256-with-rsa-private-key?answertab=votes#tab-top

It requires both Jose JWT for signing and hashing, and Bouncy Castle to extract the private keys from the PEMs. I have managed to get it to work in a .NET 4.7.2 environment. Providing you can add those dependent DLLs to Blue Prism, you should have little issues in generating the JWT token.

Hope this helps.

------------------------------
Bruce Liu
Senior Product Consultant, Professional Services
Blue Prism
Australia/Sydney
------------------------------