<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Jung</title>
    <description>The latest articles on DEV Community by Jung (@shjung-dev).</description>
    <link>https://dev.to/shjung-dev</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3575358%2F4c09fb9d-193a-4b97-b9c4-faa45dcb64af.jpeg</url>
      <title>DEV Community: Jung</title>
      <link>https://dev.to/shjung-dev</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/shjung-dev"/>
    <language>en</language>
    <item>
      <title>Understanding Token Validation Function</title>
      <dc:creator>Jung</dc:creator>
      <pubDate>Sun, 14 Dec 2025 16:42:38 +0000</pubDate>
      <link>https://dev.to/shjung-dev/token-validation-57id</link>
      <guid>https://dev.to/shjung-dev/token-validation-57id</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F56bcz77dvab2f7vrsnr9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F56bcz77dvab2f7vrsnr9.png" alt=" " width="800" height="349"&gt;&lt;/a&gt;&lt;br&gt;
I came across this line of code in an authentication tutorial but didn’t fully understand what it was doing under the hood, and the tutorial didn’t explain it either. So, I researched how it actually works internally and documented my findings here in the simplest way possible.&lt;/p&gt;

&lt;p&gt;Firstly:&lt;br&gt;
func ValidateToken(tokenString string)(*Claims , error)&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Takes a JWT string called tokenString&lt;/li&gt;
&lt;li&gt;Returns a pointer to a Claims struct containing the decoded payload if valid&lt;/li&gt;
&lt;li&gt;Returns an error if the token is invalid&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;my Claims Struct is as follow:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type Claims struct {
    UserID string json:"user_id"
    jwt.StandardClaims
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Secondly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;secretKey := GetJWTKey()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Fetches the global secret key used for signing and validating JWTs&lt;/li&gt;
&lt;li&gt;This is the &lt;strong&gt;same key for all users&lt;/strong&gt; in my case since it is HS256&lt;/li&gt;
&lt;li&gt;Stored as []byte internally&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Thirdly (This is the part that I had problem understanding)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;jwt.ParseWithClaims(tokenString, &amp;amp;Claims{}, func(token *jwt.Token) (interface{}, error) {
    return secretKey, nil
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Just a couple of things to understand: [&lt;br&gt;
a. &amp;amp;Claims{} -&amp;gt; so Claims{} creates a new empty Claims struct first and we pass in the pointer to this created Claims struct. If we pass in just Claims{} (value), Go would copy the struct and fill in the token details in that copied struct instead of the original struct so the original struct remains unchanged&lt;/p&gt;

&lt;p&gt;b. interface{} here is referring to generic type which can hold []byte (HS256) or RSA keys (RS256) etc...&lt;/p&gt;


&lt;h2&gt;
  
  
  First Step:
&lt;/h2&gt;

&lt;p&gt;When jwt.ParseWithClaims function gets called firstly it does:&lt;br&gt;
  -&amp;gt; Splits the token string into &lt;strong&gt;three parts&lt;/strong&gt;&lt;br&gt;
  -&amp;gt; &lt;strong&gt;header&lt;/strong&gt; , &lt;strong&gt;payload&lt;/strong&gt; , &lt;strong&gt;signature&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Header:&lt;/strong&gt;&lt;br&gt;
-&amp;gt; Encoded in Base64&lt;br&gt;
-&amp;gt; Contains metadata about the token, usually:&lt;br&gt;
{&lt;br&gt;
  "alg": "HS256",  // algorithm used to sign the token&lt;br&gt;
  "typ": "JWT"     // type of token&lt;br&gt;
}&lt;br&gt;
alg → tells the server how to verify the signature (HMAC SHA256, RSA, etc.)&lt;br&gt;
typ → usually "JWT", indicates the type of token&lt;br&gt;
-&amp;gt; information used to verify the signature.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Payload (Claims):&lt;/strong&gt;&lt;br&gt;
-&amp;gt; Also encoded in Base64&lt;br&gt;
-&amp;gt; Contains the data about the user and token&lt;br&gt;
-&amp;gt; Payload in my case here corresponds to the Claims structure I defined above&lt;br&gt;
-&amp;gt; An example payload JSON:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   {
  "user_id": "12345",
  "exp": 1712345678,  // expiration timestamp
  "iat": 1712342000,  // issued at timestamp
  "iss": "my-app",    // issuer
  "sub": "12345"      // subject (optional)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and this payload is what gets parsed into &lt;strong&gt;&amp;amp;Claims{}&lt;/strong&gt; struct&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Signature&lt;/strong&gt;&lt;br&gt;
-&amp;gt; Calculated as:&lt;br&gt;
HMACSHA256(&lt;br&gt;
    base64UrlEncode(header) + "." + base64UrlEncode(payload),&lt;br&gt;
    secretKey&lt;br&gt;
)&lt;br&gt;
Purpose: ensures token hasn’t been tampered with&lt;br&gt;
-&amp;gt; Only valid if the server knows the secretKey&lt;/p&gt;


&lt;h2&gt;
  
  
  Second Step:
&lt;/h2&gt;

&lt;p&gt;Decodes &lt;strong&gt;header and payload&lt;/strong&gt; into a temporary jwt.Token struct:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type Token struct {
    Raw       string
    Method    SigningMethod
    Header    map[string]interface{} -&amp;gt; alg types
    Claims    Claims
    Signature string
    Valid     bool
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Third Step:
&lt;/h2&gt;

&lt;p&gt;Call the function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func(token *jwt.Token)(interface{}, error) {return secretKey,nil}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we pass in the temporary jwt.Token struct formed in Step 2 into the function&lt;br&gt;
-&amp;gt; Since this jwt.Token contains the header, we can dynamically choose which key to choose based on the method, but in my case as mentioned earlier I am using the same secretKey all the time so no dynamic selection is needed&lt;br&gt;
-&amp;gt; Return the secretKey&lt;/p&gt;


&lt;h2&gt;
  
  
  Fourth Step:
&lt;/h2&gt;

&lt;p&gt;After the key function returns secretKey, jwt.ParseWithClaims does the following internally:&lt;br&gt;
-&amp;gt; &lt;strong&gt;Recalculate&lt;/strong&gt; the expected signature:&lt;br&gt;
     a. Uses the decoded  +  + secretKey&lt;br&gt;
     b. Algorithm is determined by token.Method from the header(HS256, etc.)&lt;/p&gt;

&lt;p&gt;-&amp;gt; Compare with the signature in the token:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type Token struct {
    Raw       string
    Method    SigningMethod
    Header    map[string]interface{} -&amp;gt; alg types
    Claims    Claims
    **Signature string** &amp;lt;- Compare with this
    Valid     bool
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;a. If they match → token is valid and untampered&lt;br&gt;
b. If they don’t → token is invalid&lt;/p&gt;

&lt;p&gt;As mentioned above:&lt;br&gt;
Signature&lt;br&gt;
-&amp;gt; Calculated as:&lt;br&gt;
HMACSHA256(&lt;br&gt;
    base64UrlEncode(header) + "." + base64UrlEncode(payload),&lt;br&gt;
    secretKey&lt;br&gt;
)&lt;/p&gt;


&lt;h2&gt;
  
  
  Fifth Step:
&lt;/h2&gt;

&lt;p&gt;-&amp;gt; Fill the Claims struct (&amp;amp;Claims{}):&lt;br&gt;
     a. &lt;strong&gt;Decoded payload is written into your Claims struct pointer&lt;/strong&gt;&lt;br&gt;
     b. &lt;strong&gt;Automatically checks for&lt;/strong&gt; standard claims like (exp, iat, iss, etc.) and custom claims (user_id)&lt;/p&gt;

&lt;p&gt;-&amp;gt; token.Valid is set to true if signature matches and standard claims (e.g., expiration) are valid&lt;/p&gt;


&lt;h2&gt;
  
  
  Sixth Step:
&lt;/h2&gt;

&lt;p&gt;After jwt.ParseWithClaims returns&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if claims, ok := token.Claims.(*Claims); ok &amp;amp;&amp;amp; token.Valid {
    return claims, nil
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;-&amp;gt; We type assert the generic token.Claims to my concrete *Claims struct&lt;br&gt;
-&amp;gt; If type assertion succeeds then return the value (claims of type *Claims) and ok (type boolean true)&lt;br&gt;
-&amp;gt; Then we can safely access:&lt;br&gt;
claims.UserID&lt;br&gt;
claims.ExpiresAt&lt;br&gt;
claims.Issuer&lt;/p&gt;

&lt;p&gt;TLDR Flow:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;jwt.ParseWithClaims receives tokenString&lt;/li&gt;
&lt;li&gt;Splits token → header, payload, signature&lt;/li&gt;
&lt;li&gt;Decodes header + payload → temporary jwt.Token struct&lt;/li&gt;
&lt;li&gt;Calls key function with jwt.Token → returns secretKey&lt;/li&gt;
&lt;li&gt;Recalculates signature using secretKey&lt;/li&gt;
&lt;li&gt;Compares with token’s signature

&lt;ul&gt;
&lt;li&gt;Match → valid&lt;/li&gt;
&lt;li&gt;No match → invalid&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Fills &amp;amp;Claims{} struct with payload data&lt;/li&gt;
&lt;li&gt;Returns token with token.Valid = true&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>security</category>
      <category>backend</category>
      <category>beginners</category>
      <category>go</category>
    </item>
  </channel>
</rss>
