{"id":381,"date":"2026-05-18T09:00:00","date_gmt":"2026-05-18T03:30:00","guid":{"rendered":"https:\/\/smitabharat.com\/blog\/go-jwt-authentication\/"},"modified":"2026-10-10T21:21:30","modified_gmt":"2026-10-10T15:51:30","slug":"go-jwt-authentication","status":"publish","type":"post","link":"https:\/\/smitabharat.com\/blog\/go-jwt-authentication\/","title":{"rendered":"Go JWT Authentication for REST APIs"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Go JWT authentication lets your API remember who a user is without storing a session on the server. In this post, you will learn what a JSON Web Token is and how its three parts work. Also, you will see why the signature matters. Then we will build login, a token check middleware and a protected route for our book API.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This lesson continues straight from <a href=\"https:\/\/smitabharat.com\/blog\/go-password-hashing-bcrypt\/\">Go password hashing with bcrypt<\/a>. There, users learned to log in safely. We also use middleware from <a href=\"https:\/\/smitabharat.com\/blog\/go-middleware-examples\/\">Go middleware explained with examples<\/a> and context values from <a href=\"https:\/\/smitabharat.com\/blog\/go-context-beginners-guide\/\">Go context for beginners<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What Is Go JWT Authentication?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In short, a JSON Web Token, or JWT, is a small signed string. It carries facts about a user, such as their email and role. So after a correct login, the server creates a JWT and gives it to the client. Then the client sends it back with every request, usually in the <code>Authorization<\/code> header. Because the token itself holds the user details, the server does not need to look anything up.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, think of a wristband at a music festival. First, at the gate, staff check your ticket once and give you a band. After that, every stage only looks at the band, so nobody checks your ticket again. Similarly, the server checks the password once and then trusts the signed token.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In Go, the most popular library for this is <code>github.com\/golang-jwt\/jwt\/v5<\/code>. So that is what we use here. It is well tested and follows the JWT standard closely, and its version 5 added clearer errors.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why Go JWT Authentication Matters<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Traditionally, classic sessions store login state in server memory or a database. However, modern backends often run many servers and services. Specifically, here is where Go JWT authentication helps.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Stateless servers<\/strong>: any server can check a token, so you do not need shared session storage.<\/li>\n\n\n\n<li><strong>Microservices<\/strong>: one auth service issues tokens, and every other service verifies them.<\/li>\n\n\n\n<li><strong>Mobile apps and SPAs<\/strong>: clients simply attach the token to each API call.<\/li>\n\n\n\n<li><strong>Built-in expiry<\/strong>: every token carries its own end time.<\/li>\n\n\n\n<li><strong>Roles and permissions<\/strong>: claims such as <code>role<\/code> travel with each request.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">In short, Go JWT authentication fits APIs that serve many clients from many servers.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How Go JWT Authentication Works<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">First, the user sends an email and password to <code>\/login<\/code>. After that, the server checks the password with bcrypt and creates a signed token. Then the client stores the token and sends <code>Authorization: Bearer &lt;token&gt;<\/code> on later requests. Finally, a middleware verifies the signature and expiry before the handler runs.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><a href=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-diagram-1.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-diagram-1-1024x640.png\" alt=\"Go JWT Authentication diagram showing login, token issue, Bearer requests and middleware checks\" class=\"wp-image-370\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-diagram-1-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-diagram-1-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-diagram-1-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-diagram-1-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-diagram-1-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><figcaption class=\"wp-element-caption\">The client logs in once, receives a signed token, and then sends it as a Bearer header on every request for the middleware to verify.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Above all, the key idea is the signature. In fact, the server signs the token with a secret key that only it knows. As a result, if anyone changes even one letter of the token, the signature check fails.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The Three Parts of a JWT<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Overall, a JWT is three Base64URL strings joined by dots: header, payload and signature. For example, here is a real token we signed with HS256 for this post.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYWRtaW4iLCJpc3MiOiJib29rc3RvcmUiLCJzdWIiOiJhc2hhQGV4YW1wbGUuY29tIiwiZXhwIjoxNzg4OTI1NTAwLCJpYXQiOjE3ODg5MjQ2MDB9.xFDOrrhdQr7rCbFNo51pUhWSWaeyVzsQlg4E8zMXY5E<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Then, decoding the first two parts gives plain JSON. So the header is <code>{\"alg\":\"HS256\",\"typ\":\"JWT\"}<\/code>, and the payload is shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\"role\":\"admin\",\"iss\":\"bookstore\",\"sub\":\"asha@example.com\",\"exp\":1788925500,\"iat\":1788924600}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">However, anyone can read the payload. Therefore, never put passwords or other secrets in a JWT. In other words, the signature only proves the data was not changed; it does not hide it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Standard Claims<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Claims are the fields inside the payload. So this table lists the standard ones you will use most.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Claim<\/th><th>Name<\/th><th>Example use<\/th><\/tr><\/thead><tbody><tr><td><code>sub<\/code><\/td><td>Subject<\/td><td>The user&#8217;s email or ID<\/td><\/tr><tr><td><code>iss<\/code><\/td><td>Issuer<\/td><td>Which service created the token<\/td><\/tr><tr><td><code>exp<\/code><\/td><td>Expires at<\/td><td>Reject the token after this time<\/td><\/tr><tr><td><code>iat<\/code><\/td><td>Issued at<\/td><td>When the token was created<\/td><\/tr><tr><td><code>aud<\/code><\/td><td>Audience<\/td><td>Which service the token is for<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Go JWT Authentication vs Server Sessions<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Both approaches keep users logged in. However, they store state in different places, as the table below shows.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>JWT<\/th><th>Server session<\/th><\/tr><\/thead><tbody><tr><td>Where state lives<\/td><td>Inside the signed token<\/td><td>In server memory or a database<\/td><\/tr><tr><td>Works across many servers<\/td><td>Yes, with the same key<\/td><td>Needs shared session storage<\/td><\/tr><tr><td>Logout right away<\/td><td>Hard, token valid until expiry<\/td><td>Easy, delete the session<\/td><\/tr><tr><td>Size per request<\/td><td>Larger header<\/td><td>Small cookie ID<\/td><\/tr><tr><td>Best for<\/td><td>APIs, mobile apps, microservices<\/td><td>Classic server-rendered websites<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><a href=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-diagram-2.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-diagram-2-1024x640.png\" alt=\"Go JWT Authentication vs sessions diagram comparing where login state lives\" class=\"wp-image-371\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-diagram-2-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-diagram-2-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-diagram-2-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-diagram-2-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-diagram-2-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><figcaption class=\"wp-element-caption\">A JWT carries the user&#8217;s claims inside the signed token, while a session cookie only carries an ID that the server looks up.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">So when should you use which? Use Go JWT authentication for APIs used by apps and other services. On the other hand, sessions are simpler for a classic website where you need instant logout.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Hands-On: Protect the Book API with JWT<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Now let&#8217;s add Go JWT authentication to our API with login and a protected <code>\/me<\/code> route. First, add the library with <code>go get github.com\/golang-jwt\/jwt\/v5<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 1: Claims, Signing and Parsing<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">We define our own claims struct, then write one function to create tokens and one to check them.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var jwtKey = []byte(os.Getenv(\"JWT_SECRET\"))\n\ntype Claims struct {\n\tRole string `json:\"role\"`\n\tjwt.RegisteredClaims\n}\n\nfunc createToken(email, role string) (string, error) {\n\tnow := time.Now()\n\tclaims := Claims{\n\t\tRole: role,\n\t\tRegisteredClaims: jwt.RegisteredClaims{\n\t\t\tIssuer:    \"bookstore\",\n\t\t\tSubject:   email,\n\t\t\tIssuedAt:  jwt.NewNumericDate(now),\n\t\t\tExpiresAt: jwt.NewNumericDate(now.Add(15 * time.Minute)),\n\t\t},\n\t}\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)\n\treturn token.SignedString(jwtKey)\n}\n\nfunc parseToken(tokenStr string) (*Claims, error) {\n\tclaims := &amp;Claims{}\n\t_, err := jwt.ParseWithClaims(tokenStr, claims,\n\t\tfunc(t *jwt.Token) (any, error) { return jwtKey, nil },\n\t\tjwt.WithValidMethods([]string{\"HS256\"}),\n\t\tjwt.WithIssuer(\"bookstore\"),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn claims, nil\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here, embedding <code>jwt.RegisteredClaims<\/code> gives us <code>sub<\/code>, <code>exp<\/code> and the other standard fields for free. Also, <code>WithValidMethods<\/code> makes the parser accept only HS256. As a result, an attacker cannot switch the algorithm to trick the check. Finally, <code>ParseWithClaims<\/code> checks the signature, the expiry and the issuer in one call.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 2: The Login Handler<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Next, the login handler reuses the bcrypt <code>UserStore<\/code> from the previous lesson.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func (a *App) handleLogin(w http.ResponseWriter, r *http.Request) {\n\tvar in struct {\n\t\tEmail    string `json:\"email\"`\n\t\tPassword string `json:\"password\"`\n\t}\n\tif err := json.NewDecoder(r.Body).Decode(&amp;in); err != nil {\n\t\thttp.Error(w, \"invalid JSON\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif err := a.users.Login(in.Email, in.Password); err != nil {\n\t\thttp.Error(w, \"invalid email or password\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\ttoken, err := createToken(in.Email, a.users.Role(in.Email))\n\tif err != nil {\n\t\thttp.Error(w, \"could not create token\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tjson.NewEncoder(w).Encode(map[string]string{\"token\": token})\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Step 3: The Auth Middleware<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Then this middleware reads the Bearer token and checks it. If the token is valid, it stores the claims in the request context.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type ctxKey string\n\nconst claimsKey ctxKey = \"claims\"\n\nfunc RequireAuth(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\ttokenStr, ok := strings.CutPrefix(r.Header.Get(\"Authorization\"), \"Bearer \")\n\t\tif !ok {\n\t\t\thttp.Error(w, \"missing token\", http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\tclaims, err := parseToken(tokenStr)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"invalid token\", http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\tctx := context.WithValue(r.Context(), claimsKey, claims)\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t})\n}\n\nfunc handleMe(w http.ResponseWriter, r *http.Request) {\n\tclaims := r.Context().Value(claimsKey).(*Claims)\n\tjson.NewEncoder(w).Encode(map[string]string{\n\t\t\"email\": claims.Subject, \"role\": claims.Role,\n\t})\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">To finish the setup, register the routes with <code>mux.HandleFunc(\"POST \/login\", app.handleLogin)<\/code> and <code>mux.Handle(\"GET \/me\", RequireAuth(http.HandlerFunc(handleMe)))<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 4: Try It with curl<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, log in, call the protected route without a token and then with one.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>curl -s -X POST localhost:8080\/login \\\n  -d '{\"email\":\"asha@example.com\",\"password\":\"secret123\"}'\n{\"token\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\"}\n\ncurl -s localhost:8080\/me\nmissing token\n\ncurl -s -H \"Authorization: Bearer $TOKEN\" localhost:8080\/me\n{\"email\":\"asha@example.com\",\"role\":\"admin\"}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">When a token fails, the library returns a clear error. For example, an expired token gives <code>token has invalid claims: token is expired<\/code>. Meanwhile, a changed token gives <code>token signature is invalid: signature is invalid<\/code>. So you can give the client a helpful message with <code>errors.Is<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>_, err := parseToken(tokenStr)\nswitch {\ncase errors.Is(err, jwt.ErrTokenExpired):\n\thttp.Error(w, \"token expired, please log in again\", http.StatusUnauthorized)\ncase errors.Is(err, jwt.ErrTokenSignatureInvalid):\n\thttp.Error(w, \"invalid token\", http.StatusUnauthorized)\ncase errors.Is(err, jwt.ErrTokenMalformed):\n\thttp.Error(w, \"malformed token\", http.StatusBadRequest)\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">As a result, an app can show &#8220;please log in again&#8221; for an expired token. That is much better than a confusing generic error.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Refresh Tokens in Go JWT Authentication<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Short access tokens are safer. However, logging in again every 15 minutes would annoy every user. So most Go JWT authentication setups add a second, longer-lived token called a refresh token.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The flow is simple. First, login returns two tokens: a 15 minute access token and a 7 day refresh token. Then the app uses the access token for normal calls. When it expires, the app sends the refresh token to <code>\/refresh<\/code> and gets a new access token. Finally, on logout, the server deletes the refresh token from its database, so it can never be used again.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Because the server stores refresh tokens, it can cancel them. Meanwhile, access tokens stay stateless and fast to check. In short, you get both speed and the ability to log users out.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common Mistakes with Go JWT Authentication<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Weak or hard-coded secrets<\/strong>: anyone who guesses the key can create admin tokens. So use a long random secret from an environment variable.<\/li>\n\n\n\n<li><strong>Not restricting algorithms<\/strong>: attackers may try other algorithms. Always pass <code>WithValidMethods<\/code>.<\/li>\n\n\n\n<li><strong>Very long expiry times<\/strong>: a stolen token then works for weeks. Keep access tokens short, such as 15 minutes.<\/li>\n\n\n\n<li><strong>Secrets in the payload<\/strong>: anyone can decode the claims. Store only IDs, emails and roles.<\/li>\n\n\n\n<li>**Tokens in <code>localStorage<\/code> with no XSS protection**: injected scripts can steal them. Consider HttpOnly cookies for browser apps.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Best Practices for Go JWT Authentication<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Use HTTPS everywhere<\/strong>, because a token sent over plain HTTP can be copied.<\/li>\n\n\n\n<li><strong>Pair short access tokens with refresh tokens<\/strong>, so users stay logged in safely.<\/li>\n\n\n\n<li>**Check <code>iss<\/code> and <code>aud<\/code>**, since that stops tokens meant for another service.<\/li>\n\n\n\n<li><strong>Keep a deny list for urgent logouts<\/strong>, as JWTs otherwise stay valid until expiry.<\/li>\n\n\n\n<li><strong>Rotate signing keys from time to time<\/strong>, and use the <code>kid<\/code> header to pick the right one.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Task<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To practise Go JWT authentication, add a <code>RequireRole(\"admin\")<\/code> middleware. It should run after <code>RequireAuth<\/code> and return 403 Forbidden when the role does not match. Then protect a <code>DELETE \/books\/{id}<\/code> route with it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Hint: read the claims from the context, just like <code>handleMe<\/code> does. Then test it twice: once with an admin token and once with a normal user token.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Official Resources<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These pages cover the library and the JWT standard itself, so keep them handy.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/pkg.go.dev\/github.com\/golang-jwt\/jwt\/v5\">golang-jwt v5 package documentation<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.rfc-editor.org\/rfc\/rfc7519\">RFC 7519: JSON Web Token<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/cheatsheetseries.owasp.org\/cheatsheets\/JSON_Web_Token_for_Java_Cheat_Sheet.html\">OWASP JSON Web Token Cheat Sheet<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Quick Recap<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Go JWT authentication gives clients a signed token after one login.<\/li>\n\n\n\n<li>A JWT has a header, a payload and a signature, joined by dots.<\/li>\n\n\n\n<li>Anyone can read the payload, so never store secrets in it.<\/li>\n\n\n\n<li><code>jwt.NewWithClaims<\/code> signs tokens, and <code>ParseWithClaims<\/code> checks them.<\/li>\n\n\n\n<li>A middleware reads the Bearer token and puts the claims in the context.<\/li>\n\n\n\n<li>Keep tokens short-lived, restrict algorithms and always use HTTPS.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">At this point, our API knows who each user is. Next, we will make sure the data users send is valid before it reaches the database, with input validation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Coming soon: Go Input Validation<\/p>\n\n","protected":false},"excerpt":{"rendered":"<p>Go JWT authentication lets your API remember who a user is without storing a session on the server. In this post, you will learn&hellip;<\/p>\n","protected":false},"author":1,"featured_media":369,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_swapz_level":"","_swapz_series_part":0,"_swapz_hide_toc":false,"_swapz_hide_featured":false,"_swapz_description":"","footnotes":""},"categories":[15],"tags":[75,11,23,21],"swapz_series":[],"class_list":["post-381","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-go-lang","tag-go-jwt","tag-go-lang","tag-go-tutorial","tag-golang-basics"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Go JWT Authentication for REST APIs Explained<\/title>\n<meta name=\"description\" content=\"Learn Go JWT authentication step by step: how tokens work, sign and verify them with golang-jwt, write auth middleware and avoid mistakes.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/smitabharat.com\/blog\/go-jwt-authentication\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Go JWT Authentication for REST APIs Explained\" \/>\n<meta property=\"og:description\" content=\"Learn Go JWT authentication step by step: how tokens work, sign and verify them with golang-jwt, write auth middleware and avoid mistakes.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/smitabharat.com\/blog\/go-jwt-authentication\/\" \/>\n<meta property=\"og:site_name\" content=\"Smita Bharat - Blog\" \/>\n<meta property=\"article:published_time\" content=\"2026-05-18T03:30:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-10-10T15:51:30+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-featured.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2400\" \/>\n\t<meta property=\"og:image:height\" content=\"1260\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Smita\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Smita\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-jwt-authentication\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-jwt-authentication\\\/\"},\"author\":{\"name\":\"Smita\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"headline\":\"Go JWT Authentication for REST APIs\",\"datePublished\":\"2026-05-18T03:30:00+00:00\",\"dateModified\":\"2026-10-10T15:51:30+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-jwt-authentication\\\/\"},\"wordCount\":1469,\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-jwt-authentication\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-jwt-authentication-featured.png\",\"keywords\":[\"Go JWT\",\"Go Lang\",\"Go Tutorial\",\"Golang Basics\"],\"articleSection\":[\"Go Lang\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-jwt-authentication\\\/\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-jwt-authentication\\\/\",\"name\":\"Go JWT Authentication for REST APIs Explained\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-jwt-authentication\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-jwt-authentication\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-jwt-authentication-featured.png\",\"datePublished\":\"2026-05-18T03:30:00+00:00\",\"dateModified\":\"2026-10-10T15:51:30+00:00\",\"description\":\"Learn Go JWT authentication step by step: how tokens work, sign and verify them with golang-jwt, write auth middleware and avoid mistakes.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-jwt-authentication\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-jwt-authentication\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-jwt-authentication\\\/#primaryimage\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-jwt-authentication-featured.png\",\"contentUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-jwt-authentication-featured.png\",\"width\":2400,\"height\":1260,\"caption\":\"Go JWT Authentication featured image: cards for issuing, sending and verifying tokens\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-jwt-authentication\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Go JWT Authentication for REST APIs\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\",\"name\":\"Smita Bharat Blog\",\"description\":\"Golang &amp; Backend Development Tutorials and Interview Questions\",\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"alternateName\":\"Smita Bharat\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\",\"name\":\"Smita\",\"logo\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/smitabharat.com\\\/blog\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Go JWT Authentication for REST APIs Explained","description":"Learn Go JWT authentication step by step: how tokens work, sign and verify them with golang-jwt, write auth middleware and avoid mistakes.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/smitabharat.com\/blog\/go-jwt-authentication\/","og_locale":"en_US","og_type":"article","og_title":"Go JWT Authentication for REST APIs Explained","og_description":"Learn Go JWT authentication step by step: how tokens work, sign and verify them with golang-jwt, write auth middleware and avoid mistakes.","og_url":"https:\/\/smitabharat.com\/blog\/go-jwt-authentication\/","og_site_name":"Smita Bharat - Blog","article_published_time":"2026-05-18T03:30:00+00:00","article_modified_time":"2026-10-10T15:51:30+00:00","og_image":[{"width":2400,"height":1260,"url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-featured.png","type":"image\/png"}],"author":"Smita","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Smita","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/smitabharat.com\/blog\/go-jwt-authentication\/#article","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/go-jwt-authentication\/"},"author":{"name":"Smita","@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"headline":"Go JWT Authentication for REST APIs","datePublished":"2026-05-18T03:30:00+00:00","dateModified":"2026-10-10T15:51:30+00:00","mainEntityOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-jwt-authentication\/"},"wordCount":1469,"publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-jwt-authentication\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-featured.png","keywords":["Go JWT","Go Lang","Go Tutorial","Golang Basics"],"articleSection":["Go Lang"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/smitabharat.com\/blog\/go-jwt-authentication\/","url":"https:\/\/smitabharat.com\/blog\/go-jwt-authentication\/","name":"Go JWT Authentication for REST APIs Explained","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-jwt-authentication\/#primaryimage"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-jwt-authentication\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-featured.png","datePublished":"2026-05-18T03:30:00+00:00","dateModified":"2026-10-10T15:51:30+00:00","description":"Learn Go JWT authentication step by step: how tokens work, sign and verify them with golang-jwt, write auth middleware and avoid mistakes.","breadcrumb":{"@id":"https:\/\/smitabharat.com\/blog\/go-jwt-authentication\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/smitabharat.com\/blog\/go-jwt-authentication\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/smitabharat.com\/blog\/go-jwt-authentication\/#primaryimage","url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-featured.png","contentUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-jwt-authentication-featured.png","width":2400,"height":1260,"caption":"Go JWT Authentication featured image: cards for issuing, sending and verifying tokens"},{"@type":"BreadcrumbList","@id":"https:\/\/smitabharat.com\/blog\/go-jwt-authentication\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/smitabharat.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Go JWT Authentication for REST APIs"}]},{"@type":"WebSite","@id":"https:\/\/smitabharat.com\/blog\/#website","url":"https:\/\/smitabharat.com\/blog\/","name":"Smita Bharat Blog","description":"Golang &amp; Backend Development Tutorials and Interview Questions","publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"alternateName":"Smita Bharat","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/smitabharat.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339","name":"Smita","logo":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/image\/"},"sameAs":["https:\/\/smitabharat.com\/blog"]}]}},"_links":{"self":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/381","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/comments?post=381"}],"version-history":[{"count":1,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/381\/revisions"}],"predecessor-version":[{"id":391,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/381\/revisions\/391"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media\/369"}],"wp:attachment":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media?parent=381"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/categories?post=381"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/tags?post=381"},{"taxonomy":"swapz_series","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/swapz_series?post=381"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}