go-mockid/mockid/api/sign.go

58 lines
1.1 KiB
Go
Raw Normal View History

2020-08-04 07:09:43 +00:00
package api
import (
"encoding/json"
"net/http"
"git.rootprojects.org/root/keypairs"
2020-08-04 07:09:43 +00:00
)
// 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 := keypairs.SignClaims(privkey, header, opts.Claims)
2020-08-04 07:09:43 +00:00
if nil != err {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var b []byte
if jwt {
s := keypairs.JWSToJWT(jws)
2020-08-04 07:09:43 +00:00
w.Write(append([]byte(s), '\n'))
return
}
b, _ = json.Marshal(jws)
w.Write(append(b, '\n'))
}