Skip to content

Instantly share code, notes, and snippets.

@f0ster
Last active Apr 26, 2017
Embed
What would you like to do?
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