-
-
Save elango/ccca3dae839fad6f0e70 to your computer and use it in GitHub Desktop.
JWT in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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