Skip to content

Instantly share code, notes, and snippets.

@elango
Forked from squiidz/jwt-example.go
Created January 11, 2016 04:53
Show Gist options
  • Save elango/ccca3dae839fad6f0e70 to your computer and use it in GitHub Desktop.
Save elango/ccca3dae839fad6f0e70 to your computer and use it in GitHub Desktop.
JWT in Golang
package main
import (
"fmt"
"net/http"
"time"
"github.com/go-zoo/bone"
"github.com/go-zoo/claw"
mw "github.com/go-zoo/claw/middleware"
jwt "github.com/dgrijalva/jwt-go"
)
var (
privateKey []byte
)
func init() {
privateKey = []byte("secret")
}
func main() {
muxx := bone.New()
clw := claw.New(mw.Logger)
muxx.GetFunc("/login/:user", loginHandler)
muxx.GetFunc("/private", privateHandler)
http.ListenAndServe(":8080", clw.Merge(muxx))
}
func loginHandler(rw http.ResponseWriter, req *http.Request) {
username := bone.GetValue(req, "user")
if username != "" {
token := jwt.New(jwt.GetSigningMethod("HS256"))
token.Claims["ID"] = username
token.Claims["EXP"] = time.Now().Add(time.Minute * 5).Unix()
tokenString, err := token.SignedString(privateKey)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(rw, "Internal Error %s \n", err)
return
}
rw.Header().Add("Authorization", fmt.Sprintf("Bearer %s", tokenString))
fmt.Fprintf(rw, "Token : %s \n", tokenString)
return
}
fmt.Fprintf(rw, "[x] You need to provide a valid username !\n")
return
}
func privateHandler(rw http.ResponseWriter, req *http.Request) {
token, err := jwt.ParseFromRequest(req, func(t *jwt.Token) (interface{}, error) {
return privateKey, nil
})
if err == nil && token.Valid {
fmt.Fprintf(rw, "[+] You [%s] have access to the private section !!\n", token.Claims["ID"].(string))
return
}
fmt.Fprintf(rw, "[x] Access Denied !!\n")
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment