Akagi201
9/29/2016 - 2:35 PM

JOSE - JWT Usage Examples

JOSE - JWT Usage Examples

JOSE - JWT Usage Examples

JOSE is a comprehensive set of JWT, JWS, and JWE libraries.

Installation

go get github.com/SermoDigital/jose

Building rsa keys

Private key

openssl genrsa -out sample_key.priv 2048

Public key

openssl rsa -in sample_key.priv -pubout > sample_key.pub

Usage Examples

Using Claims

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)
}

Generating token

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)
}

Validating token

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)
    }
}

Parsing token

You must choose a Format to parse an access token

From Header

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)
}

From Request

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)

From Form

j, err := jws.ParseFromForm(r, jws.General)