Securing a RESTful service using a JSON web token
Once we have a REST API endpoint and a JWT token generator handler in hand, we can easily secure our endpoints with the JWT, which we will be covering in this recipe.
How to do it…
- Install the
github.com/auth0/go-jwt-middleware
,github.com/dgrijalva/jwt-go
,github.com/gorilla/mux
, andgithub.com/gorilla/handlers
packages using thego get
command, as follows:
$ go get github.com/auth0/go-jwt-middleware $ go get github.com/dgrijalva/jwt-go $ go get github.com/gorilla/handlers $ go get github.com/gorilla/mux
- Create
http-rest-api-secured.go
, where we will define the JWT middleware to check for JWTs on HTTP requests, and wrap the/employees
route with it, as follows:
package main import ( "encoding/json" "log" "net/http" "os" "time" jwtmiddleware "github.com/auth0/go-jwt-middleware" jwt "github.com/dgrijalva/jwt-go" "github.com/gorilla/handlers" "github.com/gorilla/mux" ) const ( CONN_HOST = "localhost" CONN_PORT = "8080" ...