« MBS Xojo Plugins, ver… | Home | Xojo Stammtisch in Wi… »

JWT RS256 authentication in Xojo


Recently a client asked about JWT signatures. So we created an example project to create and verify JWT RS256 signatures in Xojo. This includes new EncodeBase64URLMBS and DecodeBase64URLMBS functions in MBS Xojo Encryption Plugin. We use SignData function in OpenSSLMBS class to sign the data and later use VerifyData function to verify the signature.

Create Signature

This example code takes values from fields on the window and creates the signature to show it in another field:

Sub Create() // take values from fields and make sure encoding is right and line endings Dim Header As String = Self.Header.Text.ConvertEncoding(encodings.UTF8) Dim Payload As String = Self.Payload.Text.ConvertEncoding(encodings.UTF8) Dim PrivateKey As String = ReplaceLineEndings(Self.PrivateKey.Text, EndOfLine.UNIX).ConvertEncoding(encodings.UTF8) Dim Password As String = Self.Password.Text.ConvertEncoding(encodings.UTF8) // now prepare string to sign Dim EncodedString As String = EncodeBase64URLMBS(header) + "." + EncodeBase64URLMBS(Payload) // sign it with RSA key and SHA 256 hash Dim Signature As String = OpenSSLMBS.SignData(EncodedString, PrivateKey, Password, OpenSSLMBS.kAlgorithmSHA256) // encode signature Dim SignatureEncoded As String = EncodeBase64URLMBS(Signature) // and build JWT RS 256 signature Dim result As String = EncodedString + "." + SignatureEncoded output.Text = result End Sub

Verify Signature

And the code from the verification button to check the signature:

Sub Verify() // take values from fields and make sure encoding is right and line endings Dim PrivateKey As String = ReplaceLineEndings(Self.PrivateKey.Text, EndOfLine.UNIX).ConvertEncoding(encodings.UTF8) Dim Password As String = Self.Password.Text.ConvertEncoding(encodings.UTF8) // check if we have a dot in the input. Dim t As String = output.Text.ConvertEncoding(encodings.UTF8) Dim p As Integer = InStr(t, ".") If p = 0 Then MsgBox "invalid text?" Return End If // split JWT into three parts: Dim Header As String = NthField(t, ".", 1) Dim Payload As String = NthField(t, ".", 2) Dim Signature As String = NthField(t, ".", 3) // define the signed portion Dim EncodedString As String = Header + "." + Payload // decode all three parts Signature = DecodeBase64URLMBS(Signature) Header = DecodeBase64URLMBS(Header) Payload = DecodeBase64URLMBS(Payload) // verify signature If OpenSSLMBS.VerifyData(EncodedString, signature, PrivateKey, Password, OpenSSLMBS.kAlgorithmSHA256) Then // show the valid data: MsgBox header MsgBox Payload Else MsgBox "Verification failed." End If End Sub

New functions coming soon for 20.3pr9. Please do not hesitate to contact us with your questions.

14 07 20 - 11:30