Skip to content

Instantly share code, notes, and snippets.

@packrat386
Created July 15, 2017 18:17
Show Gist options
  • Save packrat386/f65bcd442e2fd87db624afae3465989a to your computer and use it in GitHub Desktop.
Save packrat386/f65bcd442e2fd87db624afae3465989a to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
"net/http"
"strings"
"time"
"github.com/dgrijalva/jwt-go"
)
const mySigningKey = `super_secret`
var users = map[string]string{
"aidan": "coyle",
"foo": "bar",
"test": "test",
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/login", login)
mux.HandleFunc("/", root)
log.Fatal(http.ListenAndServe(":8080", mux))
}
func login(w http.ResponseWriter, r *http.Request) {
username := r.URL.Query().Get("username")
password := r.URL.Query().Get("password")
log.Println("Password: ", password)
log.Println("Found: ", users[username])
if password != users[username] {
w.WriteHeader(401)
return
}
claims := &jwt.StandardClaims{
ExpiresAt: time.Now().Add(10 * time.Minute).Unix(),
Issuer: "doble",
Subject: username,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
ss, err := token.SignedString([]byte(mySigningKey))
if err != nil {
panic(err)
}
w.Write([]byte(ss))
}
func root(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
if auth == "" {
w.WriteHeader(401)
return
}
splits := strings.Split(auth, "Bearer ")
if len(splits) > 2 {
w.WriteHeader(401)
return
}
tokenString := splits[1]
token, err := jwt.ParseWithClaims(tokenString, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(mySigningKey), nil
})
if !token.Valid || err != nil {
w.WriteHeader(401)
return
}
claims, ok := token.Claims.(*jwt.StandardClaims)
if !ok {
log.Fatal("lolwut")
}
w.Write([]byte(fmt.Sprintf("Logged in: %s", claims.Subject)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment