SET THE TOKEN

Create claims. Think of this as a schema for the data you’ll pass in a token.

typeMyCustomClaimsstruct{// This will hold a users username after authenticating.// Ignore `json:"username"` it's required by JSON Usernamestring`json:"username"`// This will hold claims that are recommended having (Expiration, issuer)jwt.StandardClaims}

Create the handler that will set a token in the client’s cookie.

http.HandleFunc("/setToken", setToken)

In production you’d do password authentication against a database before setting the token.

funcsetToken(reshttp.ResponseWriter,req*http.Request){// Expires the token and cookie in 24 hoursexpireToken:=time.Now().Add(time.Hour*24).Unix()expireCookie:=time.Now().Add(time.Hour*24)// We'll manually assign the claims but in production you'd insert values from a database claims:=MyCustomClaims{"myusername",jwt.StandardClaims{ExpiresAt:expireToken,Issuer:"example.com",},}// Create the token using your claimstoken:=jwt.NewWithClaims(jwt.SigningMethodHS256,claims)// Signs the token with a secret. signedToken,_:=token.SignedString([]byte("secret"))// This cookie will store the token on the client sidecookie:=http.Cookie{Name:"Auth",Value:signedToken,Expires:expireCookie,HttpOnly:true}http.SetCookie(res,&cookie)// Redirect the user to his profilehttp.Redirect(res,req,"/profile",301)}

CREATE VALIDATION MIDDLEWARE

// Middleware to protect private pages funcvalidate(protectedPagehttp.HandlerFunc)http.HandlerFunc{returnhttp.HandlerFunc(func(reshttp.ResponseWriter,req*http.Request){//Validate the token and if it passes call the protected handler below.protectedPage(res,req)})}

First let’s make sure a cookie is present

// Middleware to protect private pages funcvalidate(protectedPagehttp.HandlerFunc)http.HandlerFunc{returnhttp.HandlerFunc(func(reshttp.ResponseWriter,req*http.Request){// If no Auth cookie is set then return a 404 not foundcookie,err:=req.Cookie("Auth")iferr!=nil{http.NotFound(res,req)return}//Validate the token and if it passes call the protected handler below.protectedPage(res,req)})}

Extract the token from the cookie

// Middleware to protect private pages funcvalidate(protectedPagehttp.HandlerFunc)http.HandlerFunc{returnhttp.HandlerFunc(func(reshttp.ResponseWriter,req*http.Request){// If no Auth cookie is set then return a 404 not foundcookie,err:=req.Cookie("Auth")iferr!=nil{http.NotFound(res,req)return}// Cookies concatenate the key/value. Remove the Auth= part splitCookie:=strings.Split(cookie.String(),"Auth=")//Validate the token and if it passes call the protected handler below.protectedPage(res,req)})}

Validate the token

Btw you should be referencing the offical go-jwt docs for more in-depth into the functions.

// Middleware to protect private pages funcvalidate(protectedPagehttp.HandlerFunc)http.HandlerFunc{returnhttp.HandlerFunc(func(reshttp.ResponseWriter,req*http.Request){// If no Auth cookie is set then return a 404 not foundcookie,err:=req.Cookie("Auth")iferr!=nil{http.NotFound(res,req)return}// The token is concatenated with its key Auth=token// We remove the Auth= part by splitting the cookie in two splitCookie:=strings.Split(cookie.String(),"Auth=")// Parse, validate and return a token. token,err:=jwt.ParseWithClaims(splitCookie[1],&MyCustomClaims{},func(token*jwt.Token)(interface{},error){// Prevents a known exploit if_,ok:=token.Method.(*jwt.SigningMethodHMAC);!ok{returnnil,fmt.Errorf("Unexpected signing method %v",token.Header["alg"])}return[]byte("secret"),nil})protectedPage(res,req)})}

// Middleware to protect private pages funcvalidate(protectedPagehttp.HandlerFunc)http.HandlerFunc{returnhttp.HandlerFunc(func(reshttp.ResponseWriter,req*http.Request){// If no Auth cookie is set then return a 404 not foundcookie,err:=req.Cookie("Auth")iferr!=nil{http.NotFound(res,req)return}// The token is concatenated with its key Auth=token// We remove the Auth= part by splitting the cookie in two splitCookie:=strings.Split(cookie.String(),"Auth=")// Parse, validate and return a token. token,err:=jwt.ParseWithClaims(splitCookie[1],&MyCustomClaims{},func(token*jwt.Token)(interface{},error){// Prevents a known exploit if_,ok:=token.Method.(*jwt.SigningMethodHMAC);!ok{returnnil,fmt.Errorf("Unexpected signing method %v",token.Header["alg"])}return[]byte("secret"),nil})// Validate the token and save the token's claims to a contextifclaims,ok:=token.Claims.(*MyCustomClaims);ok&&token.Valid{context.Set(req,"Claims",claims)}else{http.NotFound(res,req)return}// If everything is valid then call the original protected handlerprotectedPage(res,req)})}