Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. What is this JWT Code Doing?

What is this JWT Code Doing?

Scheduled Pinned Locked Moved C#
jsontutorialquestioncsharpdata-structures
6 Posts 4 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T Offline
    T Offline
    TheOnlyRealTodd
    wrote on last edited by
    #1

    I'm following a tutorial for Web API Jwt Tokens but am confused on what exactly this below code is doing. When I read tutorials, I like to take the time to understand the content rather than just sorta copy/paste blow through them. If anyone is familiar with this type of code, please give me a little walkthrough. I'll go ahead and narrate how I feel this is working below to start it off:

    public string Protect(AuthenticationTicket data)
    public class CustomJwtFormat : ISecureDataFormat
    {

        private readonly string \_issuer = string.Empty;
    
        public CustomJwtFormat(string issuer)
        {
            \_issuer = issuer;
        }
    
        public string Protect(AuthenticationTicket data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
    
            string audienceId = ConfigurationManager.AppSettings\["as:AudienceId"\];
    
            string symmetricKeyAsBase64 = ConfigurationManager.AppSettings\["as:AudienceSecret"\];
    
            var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);
    
            var signingKey = new HmacSigningCredentials(keyByteArray);
    
            var issued = data.Properties.IssuedUtc;
            
            var expires = data.Properties.ExpiresUtc;
    
            var token = new JwtSecurityToken(\_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);
    
            var handler = new JwtSecurityTokenHandler();
    
            var jwt = handler.WriteToken(token);
    
            return jwt;
        }
    

    The code appears to: 1. Accept user claims as an argument called "data" (?) 2. After ensuring the data isn't null, it pulls an "AudienceId" and "AudienceSecret" from AppSettings in web.config and assigns to two variables. 3. It decodes the AudienceSecret from Base64Url into a byte array? <----This is where I'm confused. The secret is just a URL??? 4. It now takes the decoded URL and then passes it into a hash function, creating a keyed-hash message authentication code "signing credentials" (also confused a bit here) 5. Assigns issued and expiry date to the claims/data. 6. It then creates a token with the above data 7.News up a "token handler" and then creates yet another jwt token variable and finally appare

    L Richard DeemingR 2 Replies Last reply
    0
    • T TheOnlyRealTodd

      I'm following a tutorial for Web API Jwt Tokens but am confused on what exactly this below code is doing. When I read tutorials, I like to take the time to understand the content rather than just sorta copy/paste blow through them. If anyone is familiar with this type of code, please give me a little walkthrough. I'll go ahead and narrate how I feel this is working below to start it off:

      public string Protect(AuthenticationTicket data)
      public class CustomJwtFormat : ISecureDataFormat
      {

          private readonly string \_issuer = string.Empty;
      
          public CustomJwtFormat(string issuer)
          {
              \_issuer = issuer;
          }
      
          public string Protect(AuthenticationTicket data)
          {
              if (data == null)
              {
                  throw new ArgumentNullException("data");
              }
      
              string audienceId = ConfigurationManager.AppSettings\["as:AudienceId"\];
      
              string symmetricKeyAsBase64 = ConfigurationManager.AppSettings\["as:AudienceSecret"\];
      
              var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);
      
              var signingKey = new HmacSigningCredentials(keyByteArray);
      
              var issued = data.Properties.IssuedUtc;
              
              var expires = data.Properties.ExpiresUtc;
      
              var token = new JwtSecurityToken(\_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);
      
              var handler = new JwtSecurityTokenHandler();
      
              var jwt = handler.WriteToken(token);
      
              return jwt;
          }
      

      The code appears to: 1. Accept user claims as an argument called "data" (?) 2. After ensuring the data isn't null, it pulls an "AudienceId" and "AudienceSecret" from AppSettings in web.config and assigns to two variables. 3. It decodes the AudienceSecret from Base64Url into a byte array? <----This is where I'm confused. The secret is just a URL??? 4. It now takes the decoded URL and then passes it into a hash function, creating a keyed-hash message authentication code "signing credentials" (also confused a bit here) 5. Assigns issued and expiry date to the claims/data. 6. It then creates a token with the above data 7.News up a "token handler" and then creates yet another jwt token variable and finally appare

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      The trouble is the developer was too lazy to use proper variable typing, so all those var keywords just make it more difficult to understand. One of the worst decisions in C# was that keyword IMHO.

      T 1 Reply Last reply
      0
      • L Lost User

        The trouble is the developer was too lazy to use proper variable typing, so all those var keywords just make it more difficult to understand. One of the worst decisions in C# was that keyword IMHO.

        T Offline
        T Offline
        TheOnlyRealTodd
        wrote on last edited by
        #3

        I agree with you. It's pretty clear to me that, just like in many other areas/trades, there are many "features" included in modern programming languages which are to be blunt, for lazy people. Or at least abused by them. The thing that always baffles my mind is people do everything they can to try and type less, yet I've never met one programmer whose problem is that they spend too much time typing. In fact, I wished I spent more time typing and less time dealing with bs!

        OriginalGriffO 1 Reply Last reply
        0
        • T TheOnlyRealTodd

          I agree with you. It's pretty clear to me that, just like in many other areas/trades, there are many "features" included in modern programming languages which are to be blunt, for lazy people. Or at least abused by them. The thing that always baffles my mind is people do everything they can to try and type less, yet I've never met one programmer whose problem is that they spend too much time typing. In fact, I wished I spent more time typing and less time dealing with bs!

          OriginalGriffO Offline
          OriginalGriffO Offline
          OriginalGriff
          wrote on last edited by
          #4

          Go over to QA, and look at the amount of effort some students will put into avoiding learning how to write code: they will invest hours in trying to get you to write a five line console app... :sigh: These are the people that want var to be usable outside Linq queries.

          Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...

          "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
          "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

          L 1 Reply Last reply
          0
          • T TheOnlyRealTodd

            I'm following a tutorial for Web API Jwt Tokens but am confused on what exactly this below code is doing. When I read tutorials, I like to take the time to understand the content rather than just sorta copy/paste blow through them. If anyone is familiar with this type of code, please give me a little walkthrough. I'll go ahead and narrate how I feel this is working below to start it off:

            public string Protect(AuthenticationTicket data)
            public class CustomJwtFormat : ISecureDataFormat
            {

                private readonly string \_issuer = string.Empty;
            
                public CustomJwtFormat(string issuer)
                {
                    \_issuer = issuer;
                }
            
                public string Protect(AuthenticationTicket data)
                {
                    if (data == null)
                    {
                        throw new ArgumentNullException("data");
                    }
            
                    string audienceId = ConfigurationManager.AppSettings\["as:AudienceId"\];
            
                    string symmetricKeyAsBase64 = ConfigurationManager.AppSettings\["as:AudienceSecret"\];
            
                    var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);
            
                    var signingKey = new HmacSigningCredentials(keyByteArray);
            
                    var issued = data.Properties.IssuedUtc;
                    
                    var expires = data.Properties.ExpiresUtc;
            
                    var token = new JwtSecurityToken(\_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);
            
                    var handler = new JwtSecurityTokenHandler();
            
                    var jwt = handler.WriteToken(token);
            
                    return jwt;
                }
            

            The code appears to: 1. Accept user claims as an argument called "data" (?) 2. After ensuring the data isn't null, it pulls an "AudienceId" and "AudienceSecret" from AppSettings in web.config and assigns to two variables. 3. It decodes the AudienceSecret from Base64Url into a byte array? <----This is where I'm confused. The secret is just a URL??? 4. It now takes the decoded URL and then passes it into a hash function, creating a keyed-hash message authentication code "signing credentials" (also confused a bit here) 5. Assigns issued and expiry date to the claims/data. 6. It then creates a token with the above data 7.News up a "token handler" and then creates yet another jwt token variable and finally appare

            Richard DeemingR Offline
            Richard DeemingR Offline
            Richard Deeming
            wrote on last edited by
            #5

            TheOnlyRealTodd wrote:

            3. It decodes the AudienceSecret from Base64Url into a byte array? <----This is where I'm confused. The secret is just a URL???

            The secret is a Base64[^]-encoded byte array. The TextEncodings.Base64Url.Decode method uses Convert.FromBase64String[^]. It replaces some characters that can't be used in a URL, and pads the string to the correct length. It's not clear why you'd need to do that, since you're not passing the string in a URL.

            public class Base64UrlTextEncoder : ITextEncoder
            {
            public string Encode(byte[] data)
            {
            if (data == null) throw new ArgumentNullException("data");
            return Convert.ToBase64String(data).TrimEnd('=').Replace('+', '-').Replace('/', '_');
            }

            public byte\[\] Decode(string text)
            {
                if (text == null) throw new ArgumentNullException("text");
                return Convert.FromBase64String(Pad(text.Replace('-', '+').Replace('\_', '/')));
            }
            
            private static string Pad(string text)
            {
                int count = 3 - (text.Length + 3) % 4;
                if (count == 0) return text;
                return text + new string('=', count);
            }
            

            }


            "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

            "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

            1 Reply Last reply
            0
            • OriginalGriffO OriginalGriff

              Go over to QA, and look at the amount of effort some students will put into avoiding learning how to write code: they will invest hours in trying to get you to write a five line console app... :sigh: These are the people that want var to be usable outside Linq queries.

              Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #6

              But doesn't everyone want to be a "project manager" ... and skip all that "techie" stuff?

              1 Reply Last reply
              0
              Reply
              • Reply as topic
              Log in to reply
              • Oldest to Newest
              • Newest to Oldest
              • Most Votes


              • Login

              • Don't have an account? Register

              • Login or register to search.
              • First post
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • World
              • Users
              • Groups