Skip to content

gostack/jwt

 
 

Repository files navigation

jwt - JSON Web Token library

Coverage Status Build Status GoDoc Gitter

jwt is a simple library for handling JSON Web Tokens in Go.
The library is developed based on draft-ietf-oauth-json-web-token-32.

Installation

You can install the library using the standard go get command:

go get github.com/gostack/jwt

Note: This package requires Go 1.3 or higher.

Examples

JSON Web Token (HMAC, HS256)

import (
  "fmt"

  "github.com/gostack/jwt"
)

func main() {
  key := "secret"

  token := jwt.NewToken()
  token.Claims["username"] = "my_username"

  tokenstring, err := token.Sign(key)
  if err != nil {
    panic(err)
  }

  token, err = jwt.DecodeToken(tokenstring, jwt.HS256, key)
  if err != nil {
    panic(err)
  }

  fmt.Printf("Your username is: %s\n", token.Claims["username"])
}

JSON Web Token (RSA, RS256)

import (
  "fmt"

  "github.com/gostack/jwt"
)

func main() {
  privateKey = `-----BEGIN RSA PRIVATE KEY-----
myprivatekeyhere
-----END RSA PRIVATE KEY-----`
  publicKey = `-----BEGIN PUBLIC KEY-----
mypublickeyhere  
-----END PUBLIC KEY-----`

  token := jwt.NewToken()
  token.Algorithm = jwt.RS256
  token.Claims["username"] = "my_username"

  tokenstring, err := token.Sign(privateKey)
  if err != nil {
    panic(err)
  }

  token, err = jwt.DecodeToken(tokenstring, jwt.RS256, publicKey)
  if err != nil {
    panic(err)
  }

  fmt.Printf("Your username is: %s\n", token.Claims["username"])
}

JSON Web Token (ECDSA, ES256)

import (
  "fmt"

  "github.com/gostack/jwt"
)

func main() {
  privateKey = `-----BEGIN EC PRIVATE KEY-----
myprivatekeyhere
-----END EC PRIVATE KEY-----`
  publicKey = `-----BEGIN PUBLIC KEY-----
mypublickeyhere  
-----END PUBLIC KEY-----`

  token := jwt.NewToken()
  token.Algorithm = jwt.ES256
  token.Claims["username"] = "my_username"

  tokenstring, err := token.Sign(privateKey)
  if err != nil {
    panic(err)
  }

  token, err = jwt.DecodeToken(tokenstring, jwt.ES256, publicKey)
  if err != nil {
    panic(err)
  }

  fmt.Printf("Your username is: %s\n", token.Claims["username"])
}

License

jwt is licensed under the MIT license.

Packages

No packages published

Languages

  • Go 98.4%
  • Shell 1.6%