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
+5.5k PHP : Fix Call to undefined function curl_init() error
+11.2k Golang : How to use if, eq and print properly in html template
+9.9k Golang : Convert octal value to string to deal with leading zero problem
+20.1k Golang : Convert seconds to human readable time format example
+18.4k Golang : Get download file size
+12k Golang : convert(cast) string to integer value
+5.7k Linux : Disable and enable IPv4 forwarding
+5.8k Cash Flow : 50 days to pay your credit card debt
+5.6k Golang : Frobnicate or tweaking a string example
+4.7k Which content-type(MIME type) to use for JSON data
+11.4k Golang : Handle API query by curl with Gorilla Queries example
+17.6k Golang : [json: cannot unmarshal object into Go value of type]