Skip to content

Instantly share code, notes, and snippets.

@aalvesjr
Last active May 22, 2017 14:29
Show Gist options
  • Save aalvesjr/36de019dba1759c96129719fdb8d34a0 to your computer and use it in GitHub Desktop.
Save aalvesjr/36de019dba1759c96129719fdb8d34a0 to your computer and use it in GitHub Desktop.
Using Authorizate middleware to check JWT token and enqueue the next handler
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/gorilla/mux"
)
const secret = "secret"
type DefaultClaims struct {
UserID uint `json:"user_id"`
RoleType string `json:"role_type"`
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/", Authorizate(DefaultHandler, secret)).Methods("POST")
http.ListenAndServe(":8090", router)
}
func DefaultHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
d, ok := r.Context().Value("defaultClaims").(DefaultClaims)
if !ok {
fmt.Println("doesn't has the key user_id")
}
fmt.Printf("UserID: %d, role: %s\n", d.UserID, d.RoleType)
json.NewEncoder(w).Encode(map[string]string{
"message": "OK",
})
}
func Authorizate(next http.HandlerFunc, secret string) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := strings.Split(r.Header.Get("Authorization"), " ")
token := authHeader[len(authHeader)-1]
// validateToken must return a 'token.DefaultClaims' and bool
if validateToken(token, secret) {
ctx := r.Context()
d := DefaultClaims{
UserID: 123,
RoleType: "SUPPORT",
}
ctx = context.WithValue(ctx, "defaultClaims", d)
next.ServeHTTP(w, r.WithContext(ctx))
} else {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
json.NewEncoder(w).Encode(map[string]string{
"message": "Forbidden",
})
}
})
}
func validateToken(token, secret string) bool {
// check if is a valid the [user|service] token using secret
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment