go-mockid/mockid.go

101 lines
2.3 KiB
Go

package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"net/url"
"os"
"strconv"
"git.coolaj86.com/coolaj86/go-mockid/mockid"
_ "github.com/joho/godotenv/autoload"
)
func main() {
done := make(chan bool)
var port int
var host string
jwkm := map[string]string{
"crv": "P-256",
"d": "GYAwlBHc2mPsj1lp315HbYOmKNJ7esmO3JAkZVn9nJs",
"x": "ToL2HppsTESXQKvp7ED6NMgV4YnwbMeONexNry3KDNQ",
"y": "Tt6Q3rxU37KAinUV9PLMlwosNy1t3Bf2VDg5q955AGc",
}
jwk := &mockid.PrivateJWK{
PublicJWK: mockid.PublicJWK{
Crv: jwkm["crv"],
X: jwkm["x"],
Y: jwkm["y"],
},
D: jwkm["d"],
}
priv := mockid.ParseKey(jwk)
portFlag := flag.Int("port", 0, "Port on which the HTTP server should run")
urlFlag := flag.String("url", "", "Outward-facing address, such as https://example.com")
prefixFlag := flag.String("jwkspath", "", "The path to the JWKs storage directory")
flag.Parse()
if nil != portFlag && *portFlag > 0 {
port = *portFlag
} else {
portStr := os.Getenv("PORT")
port, _ = strconv.Atoi(portStr)
}
if port < 1 {
fmt.Fprintf(os.Stderr, "You must specify --port or PORT\n")
os.Exit(1)
}
if nil != urlFlag && "" != *urlFlag {
host = *urlFlag
} else {
host = "http://localhost:" + strconv.Itoa(port)
}
var jwksPrefix string
if nil != prefixFlag && "" != *prefixFlag {
jwksPrefix = *prefixFlag
} else {
jwksPrefix = "public-jwks"
}
err := os.MkdirAll(jwksPrefix, 0755)
if nil != err {
fmt.Fprintf(os.Stderr, "couldn't write %q: %s", jwksPrefix, err)
os.Exit(1)
}
mockid.Route(jwksPrefix, priv, jwk)
fs := http.FileServer(http.Dir("public"))
http.Handle("/", fs)
/*
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Printf(r.Method, r.URL.Path)
http.Error(w, "Not Found", http.StatusNotFound)
})
*/
fmt.Printf("Serving on port %d\n", port)
go func() {
log.Fatal(http.ListenAndServe(":"+strconv.Itoa(port), nil))
done <- true
}()
b, _ := json.Marshal(jwk)
fmt.Printf("Private Key:\n\t%s\n", string(b))
b, _ = json.Marshal(jwk.PublicJWK)
fmt.Printf("Public Key:\n\t%s\n", string(b))
protected, payload, token := mockid.GenToken(host, priv, url.Values{})
fmt.Printf("Protected (Header):\n\t%s\n", protected)
fmt.Printf("Payload (Claims):\n\t%s\n", payload)
fmt.Printf("Access Token:\n\t%s\n", token)
<-done
}