Skip to content

Instantly share code, notes, and snippets.

@bschapendonk
Last active October 22, 2023 08:01
Show Gist options
  • Select an option

  • Save bschapendonk/80f2339e0ac6837670d7c6843455d4e2 to your computer and use it in GitHub Desktop.

Select an option

Save bschapendonk/80f2339e0ac6837670d7c6843455d4e2 to your computer and use it in GitHub Desktop.

Revisions

  1. bschapendonk renamed this gist Jan 17, 2017. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion Program.cs → CreateValidateJWT.cs
    Original file line number Diff line number Diff line change
    @@ -3,7 +3,7 @@
    using System.Security.Claims;
    using System.Security.Cryptography;

    namespace ConsoleApplication1
    namespace CreateValidateJWT
    {
    class Program
    {
  2. bschapendonk created this gist Oct 7, 2016.
    47 changes: 47 additions & 0 deletions Program.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    using System;
    using System.IdentityModel.Tokens;
    using System.Security.Claims;
    using System.Security.Cryptography;

    namespace ConsoleApplication1
    {
    class Program
    {
    static void Main(string[] args)
    {
    var handler = new JwtSecurityTokenHandler();

    //create symmetrickey
    var buffer = new byte[64];
    using (var random = new RNGCryptoServiceProvider())
    {
    random.GetBytes(buffer);
    }
    var secretString = Convert.ToBase64String(buffer);

    //create jwt
    var token = handler.CreateToken(
    issuer: "issuer",
    audience: "audience",
    expires: DateTime.UtcNow.AddSeconds(10),
    subject: new ClaimsIdentity(new[] {
    new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
    new Claim(ClaimTypes.Name, "User")
    }),
    signingCredentials: new SigningCredentials(new InMemorySymmetricSecurityKey(buffer), SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha512Digest));


    //validate jwt
    var tokenString = handler.WriteToken(token);
    SecurityToken validatedToken;
    var param = new TokenValidationParameters
    {
    ClockSkew = TimeSpan.FromMinutes(1),
    ValidIssuer = "issuer",
    ValidAudience = "audience",
    IssuerSigningKey = new InMemorySymmetricSecurityKey(buffer),
    };
    var claims = handler.ValidateToken(tokenString, param, out validatedToken);
    }
    }
    }