75 lines
1.7 KiB
Go
75 lines
1.7 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt"
|
|
"github.com/husobee/vestigo"
|
|
)
|
|
|
|
// For HMAC signing method, the key can be any []byte. It is recommended to generate
|
|
// a key using crypto/rand or something equivalent. You need the same key for signing
|
|
// and validating.
|
|
var hmacSampleSecret = []byte("a")
|
|
|
|
func main() {
|
|
if len(os.Args) == 2 && os.Args[1] == "token" {
|
|
generateToken()
|
|
os.Exit(0)
|
|
}
|
|
|
|
router := vestigo.NewRouter()
|
|
router.Get("/", Auth(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
}))
|
|
http.ListenAndServe(":8080", router)
|
|
}
|
|
|
|
func Auth(f http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
authheader, ok := r.Header["Authorization"]
|
|
if !ok {
|
|
http.Error(w, "Missing token", http.StatusBadRequest)
|
|
return
|
|
}
|
|
tokenString := strings.Split(authheader[0], " ")[1]
|
|
|
|
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
|
|
}
|
|
|
|
return hmacSampleSecret, nil
|
|
})
|
|
if err != nil {
|
|
http.Error(w, "Bad token", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
|
fmt.Println(claims["foo"], claims["nbf"])
|
|
f(w, r)
|
|
} else {
|
|
fmt.Println(err)
|
|
http.Error(w, "Forbidden", http.StatusUnauthorized)
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
func generateToken() {
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
|
"foo": "bar",
|
|
"nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),
|
|
})
|
|
tokenString, err := token.SignedString(hmacSampleSecret)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
fmt.Println(tokenString)
|
|
}
|