go-mockid/mockid/api/sign.go

58 lines
1.1 KiB
Go

package api
import (
"encoding/json"
"net/http"
"git.coolaj86.com/coolaj86/go-mockid/xkeypairs"
)
// SignJWS will create an uncompressed JWT with the given payload
func SignJWS(w http.ResponseWriter, r *http.Request) {
sign(w, r, false)
}
// SignJWT will create an compressed JWS (JWT) with the given payload
func SignJWT(w http.ResponseWriter, r *http.Request) {
sign(w, r, true)
}
func sign(w http.ResponseWriter, r *http.Request, jwt bool) {
if "POST" != r.Method {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
opts, err := getOpts(r)
if nil != err {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
privkey, err := getPrivKey(opts)
if nil != err {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
header := opts.Header
if 0 != opts.Seed {
header["_seed"] = opts.Seed
}
jws, err := xkeypairs.SignClaims(privkey, header, opts.Claims)
if nil != err {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var b []byte
if jwt {
s := xkeypairs.JWSToJWT(jws)
w.Write(append([]byte(s), '\n'))
return
}
b, _ = json.Marshal(jws)
w.Write(append(b, '\n'))
}