como validar um token jwt c# ou vb.net? code example

Example 1: JASON WEB TOKENS EM VBNET COM WINDOWS FORMS

{
  "iss": "JwtServer",
  "sub": "hrmanager",
  "email": "[email protected]",
  "jti": "e971bd9c-7655-41d5-9c49-fabc054dc466",
  "iat": 1503922683,
  "http://schemas.microsoft.com/ws/2008/06/identity/claims/role": [
    "Employee",
    "HR-Worker",
    "HR-Manager"
  ],
  "Department": [
    "HR",
    "HR"
  ],
  "nbf": 1503922683,
  "exp": 1503924483
}

Example 2: conceito jwt em vbnet com exemplos

const crypto = require('crypto');

const header = JSON.stringify({
    'alg': 'HS256',
    'typ': 'JWT'
});

const payload = JSON.stringify({
    'email': '[email protected]',
    'password': 'ya0gsqhy4wzvuvb4'
});

const base64Header = Buffer.from(header).toString('base64').replace(/=/g, '');
const base64Payload = Buffer.from(payload).toString('base64').replace(/=/g, '');
const secret = 'my-custom-secret';

const data = base64Header + '.' + base64Payload;

const signature = crypto
    .createHmac('sha256', secret)
    .update(data)
    .digest('base64');

const signatureUrl = signature
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g, '')

console.log(signatureUrl);

Example 3: TOKEN JWT EXEMPLOS EM VBNET

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using JWT;
using Newtonsoft.Json.Linq;

namespace TimeworksAPI2
{
class Program
{
    const string AUTHSERVICE = "https://workingURL/";
    const string twpAIPURL = "https://workingURL/";

    static void Main(string[] args)
    {
        int PartnerID = 222;
        string SiteID = "XXXXX";
        string StartDate = "2017-04-11";
        string EndDate = "2017-04-11";
        string Category = "vacation";
        string key = "XXXXXXXXXXX";
        Dictionary<string, decimal> Results = GetAccrualData(
          StartDate,EndDate,Category, SiteID, key, PartnerID);

    }
    static public Dictionary<string, decimal> GetAccrualData(string StartDate, string EndDate, string Category, string SiteID, int PartnerID, string key)
    {

        var apptoken = "";
        var token = new
        {
            iss = PartnerID,
            product = "twppartner",
            sub = "partner",
            siteInfo = new
            {
                type = "id",
                id = SiteID
            },
            exp = (Int32)DateTime.UtcNow.Add(new TimeSpan(0, 4, 30)).Subtract(new DateTime(1970, 1, 1)).TotalSeconds
        };
        var jwt = JsonWebToken.Encode(token, key, JwtHashAlgorithm.HS256);
        WebRequest request = WebRequest.Create(AUTHSERVICE);
        request.ContentType = "application/json";
        request.Method = "POST";
        request.Headers.Set("Authorization", string.Format("Bearer {0}", jwt));
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        if (response.StatusCode == HttpStatusCode.Created)
                             'QUALQUER COISA
     
     
'_________________________EM VB NET____________________________
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Net
Imports System.IO
Imports JWT
Imports Newtonsoft.Json.Linq

Namespace TimeworksAPI2
    Class Program
        Const AUTHSERVICE As String = "https://workingURL/"
        Const twpAIPURL As String = "https://workingURL/"

        Private Shared Sub Main(ByVal args As String())
            Dim PartnerID As Integer = 222
            Dim SiteID As String = "XXXXX"
            Dim StartDate As String = "2017-04-11"
            Dim EndDate As String = "2017-04-11"
            Dim Category As String = "vacation"
            Dim key As String = "XXXXXXXXXXX"
            Dim Results As Dictionary(Of String, Decimal) = GetAccrualData(StartDate, EndDate, Category, SiteID, key, PartnerID)
        End Sub

        Shared Public Function GetAccrualData(ByVal StartDate As String, ByVal EndDate As String, ByVal Category As String, ByVal SiteID As String, ByVal PartnerID As Integer, ByVal key As String) As Dictionary(Of String, Decimal)
            Dim apptoken = ""
            Dim token = New With {Key
                .iss = PartnerID, Key
                .product = "twppartner", Key
                .[sub] = "partner", Key
                .siteInfo = New With {Key
                    .type = "id", Key
                    .id = SiteID
                }, Key
                .exp = CInt(DateTime.UtcNow.Add(New TimeSpan(0, 4, 30)).Subtract(New DateTime(1970, 1, 1)).TotalSeconds)
            }
            Dim jwt = JsonWebToken.Encode(token, key, JwtHashAlgorithm.HS256)
            Dim request As WebRequest = WebRequest.Create(AUTHSERVICE)
            request.ContentType = "application/json"
            request.Method = "POST"
            request.Headers.[Set]("Authorization", String.Format("Bearer {0}", jwt))
            Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
            If response.StatusCode = HttpStatusCode.Created Then 
          
                                          'qualquer coisa 
           End If                             
        End Function
    End Class
End Namespace

Example 4: JWT EM VBNET

Dim privateKeyStream As Stream = New FileStream("D:\docusign.pem", FileMode.Open)
'Dim privateKeyStream As Stream = New MemoryStream(Encoding.UTF8.GetBytes(PK))
Using SR = New StreamReader(privateKeyStream)
    If Not SR Is Nothing And SR.Peek() > 0 Then
        Dim privateKeyBytes() As Byte = ReadAsBytes(privateKeyStream)
        'Dim privateKeyBytes() As Byte = StreamToByteArray(privateKeyStream)
        'Dim privateKeyBytes() As Byte = Convert.FromBase64String(PrivateKey)
        'Dim privateKeyBytes() As Byte = Encoding.UTF8.GetBytes(PrivateKey)

        Dim privateKeyS As String = Encoding.UTF8.GetString(privateKeyBytes)

        Dim handler As JwtSecurityTokenHandler = New JwtSecurityTokenHandler()
        handler.SetDefaultTimesOnTokenCreation = False

        Dim descriptor As SecurityTokenDescriptor = New SecurityTokenDescriptor()
        descriptor.Expires = DateTime.UtcNow.AddHours(1)
        descriptor.IssuedAt = DateTime.UtcNow

        Dim scopes As List(Of String) = New List(Of String)
        scopes.Add(OAuth.Scope_SIGNATURE)

        descriptor.Subject = New ClaimsIdentity()
        descriptor.Subject.AddClaim(New Claim("scope", String.Join(" ", scopes)))
        descriptor.Subject.AddClaim(New Claim("aud", "account-d.docusign.com"))
        descriptor.Subject.AddClaim(New Claim("iss", "INTEGRATION_ID"))
        descriptor.Subject.AddClaim(New Claim("sub", "ACCOUNT_ID"))

        Dim RSA = CreateRSAKeyFromPem(privateKeyS)
        Dim rsaKey As RsaSecurityKey = New RsaSecurityKey(RSA)
        descriptor.SigningCredentials = New SigningCredentials(rsaKey, SecurityAlgorithms.RsaSha256Signature)


        Dim Token = handler.CreateToken(descriptor)
        Dim jwtToken As String = handler.WriteToken(Token)

        Dim baseUri As String = String.Format("https://{0}/", basePath)
        Dim RestClient As RestClient = New RestClient(baseUri)
        RestClient.Timeout = 10000

        Dim contentType As String = "application/x-www-form-urlencoded"

        Dim formParams As New Dictionary(Of String, String)
        formParams.Add("grant_type", OAuth.Grant_Type_JWT)
        formParams.Add("assertion", jwtToken)

        Dim queryParams As New Dictionary(Of String, String)

        Dim headerParams As New Dictionary(Of String, String)
        headerParams.Add("Content-Type", "application/x-www-form-urlencoded")
        headerParams.Add("Cache-Control", "no-store")
        headerParams.Add("Pragma", "no-cache")

        Dim fileParams As New Dictionary(Of String, FileParameter)
        Dim pathParams As New Dictionary(Of String, String)

        Dim postBody As Object = Nothing

        Dim request As RestRequest = PrepareRequest(basePath, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, contentType)

        Dim response As IRestResponse = RestClient.Execute(request)

        If (response.StatusCode >= HttpStatusCode.OK And response.StatusCode < HttpStatusCode.BadRequest) Then
            Dim tokenInfo As OAuth.OAuthToken = JsonConvert.DeserializeObject(Of OAuth.OAuthToken)(response.Content)
            Return tokenInfo.access_token
        Else
            Throw New ApiException(response.StatusCode, "Error while requesting server, received a non successful HTTP code " & response.ResponseStatus & " with response Body: " + response.Content, response.Content)
        End If
    Else
        Throw New ApiException(400, "Private key stream not supplied or is invalid!")
    End If
End Using