Skip to content

Negroni compatible middleware for handling JSON Web Token Auth.

License

Notifications You must be signed in to change notification settings

denkyl08/negroniJWT

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 

Repository files navigation

negroniJWT

JSON Web Token Auth middleware for Negroni.

GoDoc can be found 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 gorilla's context so it's safe for concurrent use.

Initialization


import(
    "github.com/codegangsta/negroni"
    "github.com/denkyl08/negroniJWT"
)

func main() {
    
    // false means request without a valid token always fails
    // true means that you must check _, ok := negroniJWT.Get(request)
    negroniJWT.Init(false)
    
    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) {
    token, ok := negroniJWT.Get(r); if !ok {
        http.Error(w, "Error: auth failure", 401)
        return
    }
    ...
}

About

Negroni compatible middleware for handling JSON Web Token Auth.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages