JOSE is a comprehensive set of JWT, JWS, and JWE libraries.
go get github.com/SermoDigital/jose
openssl genrsa -out sample_key.priv 2048
openssl rsa -in sample_key.priv -pubout > sample_key.pub
package main
import (
"fmt"
"time"
"github.com/SermoDigital/jose/jws"
)
func main() {
// expires in 10 seconds
expires := time.Now().Add(time.Duration(10) * time.Second)
claims := jws.Claims{}
claims.SetExpiration(expires)
claims.SetIssuedAt(time.Now())
fmt.Println(claims)
}
After generating up your private and public key.
package main
import (
"fmt"
"io/ioutil"
"time"
"github.com/SermoDigital/jose/crypto"
"github.com/SermoDigital/jose/jws"
)
func main() {
bytes, _ := ioutil.ReadFile("./sample_key.priv")
claims := jws.Claims{}
claims.SetExpiration(time.Now().Add(time.Duration(10) * time.Second))
rsaPrivate, _ := crypto.ParseRSAPrivateKeyFromPEM(bytes)
jwt := jws.NewJWT(claims, crypto.SigningMethodRS256)
b, _ := jwt.Serialize(rsaPrivate)
fmt.Printf("%s", b)
}
package main
import (
"io/ioutil"
"log"
"github.com/SermoDigital/jose/crypto"
"github.com/SermoDigital/jose/jws"
)
func main() {
bytes, _ := ioutil.ReadFile("./sample_key.pub")
rsaPublic, _ := crypto.ParseRSAPublicKeyFromPEM(bytes)
accessToken := "YOUR ACCESS TOKEN FROM COOKIE, FORM, HEADERS..."
jwt, err := jws.ParseJWT([]byte(accessToken))
if err != nil {
log.Fatal(err)
}
// Validate token
if err = jwt.Validate(rsaPublic, crypto.SigningMethodRS256); err != nil {
log.Fatal(err)
}
}
You must choose a Format to parse an access token
package main
import (
"fmt"
"net/http"
"github.com/SermoDigital/jose/jws"
)
func ParseTokenHandler(rw http.ResponseWriter, r *http.Request) {
j, err := jws.ParseFromHeader(r, jws.General)
// Validate token here...
// j.Validate(rsaPublic, crypto.SigningMethodRS256)
}
func main() {
http.HandleFunc("/", ParseTokenHandler)
http.ListenAndServe(":3000", nil)
}
JWSFormKey is the form "key" which should be used inside ParseFromRequest if the request is a multipart.Form.
j, err := jws.ParseFromRequest(r, jws.General)
j, err := jws.ParseFromForm(r, jws.General)
Based in that I developed a middleware:
How can I unmarshal the payload into your payloadJWT type?