jwt

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 15, 2015 License: MIT Imports: 9 Imported by: 0

README

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 gopkg.in/zhevron/jwt.v1

Note: This package requires Go 1.3 or higher.

Examples

JSON Web Token (HMAC, HS256)
import (
  "fmt"

  "gopkg.in/zhevron/jwt.v1"
)

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"

  "gopkg.in/zhevron/jwt.v1"
)

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"

  "gopkg.in/zhevron/jwt.v1"
)

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.

Documentation

Overview

Package jwt provides an implementation JSON Web Tokens.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidAlgorithm is returned when the algorithm is not set.
	ErrInvalidAlgorithm = errors.New("jwt: invalid algorithm")

	// ErrInvalidAudience is returned when the audience cannot be verified.
	ErrInvalidAudience = errors.New("jwt: invalid audience")

	// ErrInvalidIssuer is returned when the issuer cannot be verified.
	ErrInvalidIssuer = errors.New("jwt: invalid issuer")

	// ErrInvalidSubject is returned when the subject cannot be verified.
	ErrInvalidSubject = errors.New("jwt: invalid subject")

	// ErrInvalidToken is returned when the token structure is invalid.
	ErrInvalidToken = errors.New("jwt: invalid token")

	// ErrReservedClaim is returned when the user data contains a reserved claim.
	ErrReservedClaim = errors.New("jwt: reserved claim used")

	// ErrTokenExpired is returned when the token has expired.
	ErrTokenExpired = errors.New("jwt: token expired")

	// ErrTokenNotValidYet is returned when the token is not valid yet.
	ErrTokenNotValidYet = errors.New("jwt: token not valid yet")

	// ErrUnsupportedAlgorithm is returned when the algorithm isn't implemented.
	ErrUnsupportedAlgorithm = errors.New("jwt: unsupported algorithm")

	// ErrUnsupportedTokenType is returned when an unsupported token type is used.
	ErrUnsupportedTokenType = errors.New("jwt: unsupported token type")

	// ErrNoneAlgorithmWithSecret is returned when the "none" algorithm is used with a secret.
	ErrNoneAlgorithmWithSecret = errors.New("jwt: none algorithm with secret")

	// ErrNoKeyProvided is returned when the key lookup callback is set, but no key is in the token.
	ErrNoKeyProvided = errors.New("jwt: no key provided")

	// ErrNonExistantKey is returned when the provided key ID does not exist.
	ErrNonExistantKey = errors.New("jwt: non-existant key")
)

Functions

func KeyLookupCallback

func KeyLookupCallback(callback func(string) (Algorithm, interface{}))

KeyLookupCallback sets the callback function to look up the algorithm and secret to use for a given "kid" header (located in the token header).

The function is expected to return the algorithm and secret, but the secret can be omitted (by setting it to "" or nil). The callback will then use the provided algorithm with the secret provided to the DecodeToken function.

If the callback returns "" for the Algorithm, the subsequent token validation will fail with ErrNonExistantKey.

Types

type Algorithm

type Algorithm string

Algorithm is used to define the encryption algorithm used for the token.

const (
	// None represents an unsecured JWT.
	None Algorithm = "none"

	// HS256 represents the HMAC SHA-256 algorithm.
	HS256 Algorithm = "HS256"

	// HS384 represents the HMAC SHA-384 algorithm.
	HS384 Algorithm = "HS384"

	// HS512 represents the HMAC SHA-512 algorithm.
	HS512 Algorithm = "HS512"

	// RS256 represents the RSA SHA-256 algorithm.
	RS256 Algorithm = "RS256"

	// RS384 represents the RSA SHA-384 algorithm.
	RS384 Algorithm = "RS384"

	// RS512 represents the RSA SHA-512 algorithm.
	RS512 Algorithm = "RS512"

	// ES256 represents the ECDSA SHA-256 algorithm.
	ES256 Algorithm = "ES256"

	// ES384 represents the ECDSA SHA-384 algorithm.
	ES384 Algorithm = "ES384"

	// ES512 represents the ECDSA SHA-512 algorithm.
	ES512 Algorithm = "ES512"
)

type Signer

type Signer func(string, interface{}) (string, error)

Signer is used by the signing packages to sign tokens. You can use this type to implement your own signing and verification.

type Token

type Token struct {
	Type      Type
	Algorithm Algorithm
	KeyID     string
	Issuer    string
	Subject   string
	Audience  string
	IssuedAt  time.Time
	Expires   time.Time
	NotBefore time.Time
	Claims    map[string]interface{}
}

Token contains the data structure of a JWT.

Example (Decode)
str := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJNeUlzc3VlciIsInNjb3BlcyI6WyJteV9zY29wZSJdfQ._rCzwTmDAHuUq8XNsBjLMfxHJM8Jj_H3l8-ZoPKL4TQ"

secret := []byte("secret")
token, err := DecodeToken(str, HS256, secret)
if err != nil {
	panic(err)
}

if err := token.Verify("MyIssuer", "", ""); err != nil {
	panic(err)
}

for k, v := range token.Claims {
	fmt.Printf("%s = %v", k, v)
}
Output:

Example (Kid)
str := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ik15S2V5In0.eyJpc3MiOiJNeUlzc3VlciIsInNjb3BlcyI6WyJteV9zY29wZSJdfQ.blumu_NqfxUpTLAM48lAusGjJx5Mfyv_bRiRDWfPM9A"

KeyLookupCallback(func(kid string) (Algorithm, interface{}) {
	if kid == "MyKey" {
		return HS256, nil
	}

	return "", nil
})

secret := []byte("secret")
token, err := DecodeToken(str, None, secret)
if err != nil {
	panic(err)
}

if err := token.Verify("MyIssuer", "", ""); err != nil {
	panic(err)
}

for k, v := range token.Claims {
	fmt.Printf("%s = %v", k, v)
}
Output:

Example (Sign)
token := NewToken()

token.Issuer = "MyIssuer"
token.Claims["scopes"] = []string{
	"my_scope",
}

secret := []byte("secret")
str, err := token.Sign(secret)
if err != nil {
	panic(err)
}

fmt.Printf("Your token is: %s", str)
Output:

func DecodeToken

func DecodeToken(token string, algorithm Algorithm, secret interface{}) (*Token, error)

DecodeToken attempts to decode a JWT into a Token structure using the given secret for verification. This function will only return an error if decoding fails or the signature is invalid.

The secret parameter type is variable. All algorithms support string and []byte types, but some also have other custom types.

Note: The "alg" field of the token header is completely ignored in order to ensure that a token is what the server expects.

func NewToken

func NewToken() *Token

NewToken creates a new Token struct using the default HS256 algorithm. IssuedAt is also initialized to the current UTC time.

func (Token) Expired

func (t Token) Expired() bool

Expired checks if the token has expired.

func (Token) Sign

func (t Token) Sign(secret interface{}) (string, error)

Sign signs the token with the provided secret and returns the base64 encoded string value of the token.

The secret parameter type is variable. All algorithms support string and []byte types, but some also have other custom types. Refer to the documentation in each encryption package for the options.

func (Token) Valid

func (t Token) Valid() bool

Valid checks if the token is valid yet.

func (Token) Verify

func (t Token) Verify(issuer, subject, audience string) error

Verify attempts to verify the token using the provided issuer, subject and audience. If either provided value is left empty, the value is skipped. Validity and expiration will also be checked.

type Type

type Type string

Type is used to define the type of token.

const (
	// JWT represents the JSON Web Token type.
	JWT Type = "JWT"
)

type Verifier

type Verifier func(string, string, interface{}) error

Verifier is used by the signing packages to verify signatures. You can use this type to implement your own signing and verification.

Directories

Path Synopsis
Package ecdsa provides ECDSA signing methods for JWT.
Package ecdsa provides ECDSA signing methods for JWT.
Package hmac provides HMAC signing methods for JWT.
Package hmac provides HMAC signing methods for JWT.
Package rsa provides RSA signing methods for JWT.
Package rsa provides RSA signing methods for JWT.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL