Skip to content

Instantly share code, notes, and snippets.

@f0ster
Last active April 26, 2017 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save f0ster/e7ce875dbf495739ea470bc0e0f05153 to your computer and use it in GitHub Desktop.
Save f0ster/e7ce875dbf495739ea470bc0e0f05153 to your computer and use it in GitHub Desktop.
auth0 jwt go middleware example
func getUserFromRequest(r *http.Request) *model.User {
//Authorization: bearer {token}
//auth0 user is in user
jwtContext := context.Get(r, "user")
auth0Id := ((jwtContext.(*jwt.Token)).Claims).(jwt.MapClaims)["sub"]
user := model.GetUserFromAuthId(auth0Id.(string))
return user
}
func UserAuthorizationMiddleware(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc){
user := getUserFromRequest(r)
context.Set(r, "User", user)
next(rw, r)
}
///
func main() {
r := mux.NewRouter()
jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
secret := []byte(os.Getenv("AUTH0_CLIENT_SECRET"))
if len(secret) == 0 {
log.Fatal("AUTH0_CLIENT_SECRET is not set")
}
return secret, nil
},
SigningMethod: jwt.SigningMethodHS256,
})
r.Handle("/user", negroni.New(
negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
negroni.HandlerFunc(UserAuthorizationMiddleware),
negroni.HandlerFunc(GetUserHandler),
))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment