Skip to content

Latest commit

 

History

History
68 lines (52 loc) · 2.09 KB

README.md

File metadata and controls

68 lines (52 loc) · 2.09 KB

negroniJWT (Updated)

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

##About

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.

Initialization


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))
    
}

##In Login Controller

    
    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)

##Retrieve Token claims from request

func ProtectedHandler(w http.ResponseWriter, r *http.Request) {
    claims, ok := negroniJWT.Get(r); if !ok {
        http.Error(w, "Error: auth failure", 401)
        return
    }
    ...
}