Example for using JWT with SermoDigital/jose/jws

530 views
Skip to first unread message

macmilla...@gmail.com

unread,
Jun 20, 2016, 10:14:10 PM6/20/16
to golang-nuts
I get this error 'Error serializing the key. json: error calling MarshalJSON for type jws.Claims: unexpected end of JSON input'
I believe that I need to find the function that sign the token. The docs don't have any usage exampl - https://godoc.org/github.com/SermoDigital/jose/jws

 Any working example would be appreciated. 

Thank you

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "os"
)

import "github.com/SermoDigital/jose/jws"

const (
    privKeyPath = "keys/app.rsa"     // openssl genrsa -out keys/app.rsa 1024
    pubKeyPath  = "keys/app.rsa.pub" // openssl rsa -in keys/app.rsa -pubout > keys/app.rsa.pub
)

var signKey []byte

func init() {
    var err error
    signKey, err = ioutil.ReadFile(privKeyPath)
    if err != nil {
        log.Fatal("Error reading private key")
        os.Exit(1)
    }

}

func main() {
    token := createJWT()
    fmt.Println("Created token", token)
}

func createJWT() string {
    claims := jws.Claims{}
    // claims.Set("AccessToken", "level1")
    signMethod := jws.GetSigningMethod("HS512")
    token := jws.NewJWT(claims, signMethod)
    byteToken, err := token.Serialize(signKey)
    if err != nil {
        log.Fatal("Error signing the key. ", err)
        os.Exit(1)
    }

    return string(byteToken)
}

Scott

unread,
Jun 20, 2016, 11:56:45 PM6/20/16
to golang-nuts, macmilla...@gmail.com
You're loading in an RSA key but signing with HS512, try changing:


signMethod := jws.GetSigningMethod("HS512")

to

signMethod := jws.GetSigningMethod("RS256")

macmilla...@gmail.com

unread,
Jun 21, 2016, 12:06:42 AM6/21/16
to golang-nuts, macmilla...@gmail.com
Thanks Scott. Even after changing it to RS256 I get the same error.

macmilla...@gmail.com

unread,
Jun 22, 2016, 1:24:57 AM6/22/16
to golang-nuts, macmilla...@gmail.com
It's working now. I had to uncomment this line: claims.Set("AccessToken", "level1")

Thanks!


On Monday, June 20, 2016 at 7:14:10 PM UTC-7, macmilla...@gmail.com wrote:
Reply all
Reply to author
Forward
0 new messages