Golang : How to pass data between controllers with JSON Web Token
For this tutorial, we will explore how to pass data between controllers using JWT(JSON Web Token).
One of the problems of using session to pass data between controllers(functions) is that the session data is stored on the server and it can get complicated when the session data needs to be passed on to another server. In short, session works well for a single server instance, but not so well when scaling the number of servers to handle more requests.
One of the ways to solve this issue is to use JWT(JSON Web Token) to pass data between controllers. The beauty of JWT method of passing data is that the servers do not need to remember each of the sessions created. Just need to pack and unpack the tokens to get the embedded data inside the token.
The simple program below demonstrates how to pack and unpack JWT using Golang.
Here you go!
package main
import (
"fmt"
"log"
"net/http"
"os"
"time"
jwt "github.com/dgrijalva/jwt-go"
)
// jwtTokenSecret - for encrypting/decrypting JWT tokens. Change it to yours.
var jwtTokenSecret = "abc123456def"
func createToken(data string) (string, error) {
claims := jwt.MapClaims{}
claims["data"] = data //embed whatever data - such as username or error message inside the token string
claims["expired"] = time.Now().Add(time.Hour * 1).Unix() //Token expires after 1 hour
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(jwtTokenSecret))
}
func currentURL(r *http.Request) string {
hostname, err := os.Hostname()
if err != nil {
panic(err)
}
return hostname + r.URL.Path
}
func controllerOne(w http.ResponseWriter, r *http.Request) {
data := "this is my message to controller Two"
// create a new JSON Web Token and redirect to dashboard
tokenString, err := createToken(data)
if err != nil {
log.Println(err)
w.Write([]byte(err.Error()))
}
//url := currentURL(r) + "?token=" + tokenString -- use this for production
url := "http://localhost:8080/two" + "?token=" + tokenString // only for this tutorial...for simplicity sake
html := "<a href='" + url + "'>click here!</a>"
w.Write([]byte(html))
}
func controllerTwo(w http.ResponseWriter, r *http.Request) {
// extract token from controllerOne
keys := r.URL.Query()
tokenString := keys.Get("token")
if tokenString != "" {
log.Println("Token received from controllerOne : ", tokenString)
// decrypt tokenString
// taken from https://godoc.org/github.com/dgrijalva/jwt-go#ex-Parse--Hmac
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return []byte(jwtTokenSecret), nil
})
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
// convert to string from interface{}
data := fmt.Sprintf("%s", claims["data"])
log.Println("data : ", data)
w.Write([]byte("Data : " + data))
} else {
fmt.Println(err)
}
} else {
w.Write([]byte("unable to process token"))
}
}
func main() {
fmt.Println("Server started, point your browser to localhost:8080/one to start")
http.HandleFunc("/one", controllerOne)
http.HandleFunc("/two", controllerTwo)
http.ListenAndServe(":8080", nil)
}
References:
https://socketloop.com/tutorials/golang-how-to-login-and-logout-with-jwt-example
See also : Golang : How to login and logout with JWT example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+8.8k Golang : Capture text return from exec function example
+24.1k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+8.9k Golang : How to check if a string with spaces in between is numeric?
+10.7k Golang : Generate random elements without repetition or duplicate
+7.9k Golang : Randomize letters from a string example
+7.5k Golang : Lock executable to a specific machine with unique hash of the machine
+8.5k Golang : Random integer with rand.Seed() within a given range
+12.7k Swift : Convert (cast) Int to String ?
+13.9k Elastic Search : Mapping date format and sort by date
+23.6k Golang : Upload to S3 with official aws-sdk-go package
+8.5k Android Studio : Image button and button example