This is an updated version of negroniJWT compatible with go1.7.3+. This uses golang's native context instead of gorilla/context which was being used before in negroniJWT
JSON Web Token Auth middleware for Negroni.
GoDoc can be found here.
All credits to the original author here
This is some simple middleware for handling JSON Web Token authorization. Token encoding and decoding is done using dgrijalva's jwt-go. Claims from request are retrieved using negroniJWT.Get(r) and uses golang's native context so it's safe for concurrent use.
import(
"github.com/codegangsta/negroni"
"github.com/yadvendar/negroniJWT"
)
func main() {
// false means request without a valid token always fails
// true means that you must check _, ok := negroniJWT.Get(request)
// "jwt" is the private key filename and "jwt.pub" is the public key filename
negroniJWT.Init(false, "jwt", "jwt.pub")
n := negroni.Classic()
n.Use(negroni.HandlerFunc(negroniJWT.Middleware))
}
err = user.Authenticate()
if err != nil {
http.Error(w, err.Error(), 401)
return
}
claims := make(map[string]interface{})
claims["Username"] = user.Username
// generate JWT token with encrypted claims
token, err := negroniJWT.GenerateToken(claims, time.Now().Add(30*time.Minute))
err = utils.WriteJson(struct {
Token string
}{token}, w)
func ProtectedHandler(w http.ResponseWriter, r *http.Request) {
claims, ok := negroniJWT.Get(r); if !ok {
http.Error(w, "Error: auth failure", 401)
return
}
...
}