Creating a JSON web token
To secure your REST API or a service endpoint, you have to write a handler in Go that generates a JSON web token, or JWT.
In this recipe, we will be using https://github.com/dgrijalva/jwt-go to generate JWT , although you can implement any library from a number of third-party libraries available in Go, such as https://github.com/square/go-jose and https://github.com/tarent/loginsrv.
How to do it…
- Install the
github.com/dgrijalva/jwt-go,github.com/gorilla/muxandgithub.com/gorilla/handlerspackages using thego getcommand, as follows:
$ go get github.com/dgrijalva/jwt-go $ go get github.com/gorilla/handlers $ go get github.com/gorilla/mux
- Create
create-jwt.go, where we will define thegetTokenhandler that generatesJWT, as follows:
package main import ( "encoding/json" "log" "net/http" "os" "time" jwt "github.com/dgrijalva/jwt-go" "github.com/gorilla/handlers" "github.com/gorilla/mux" ) const ( CONN_HOST = "localhost" CONN_PORT = "8080" CLAIM_ISSUER...