jwt

package module
v0.0.0-...-3a42789 Latest Latest
Warning

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

Go to latest
Published: May 21, 2020 License: MIT Imports: 7 Imported by: 3

README

A JSON Web Token Package for Go

CircleCI status GoDoc Go Report Card

Table of Contents

Documentation

You can find the package documentation at https://godoc.org/github.com/jrpalma/jwt

Overview

JWT is a simple Go package for JSON Web Tokens. The package provides a very simple and functional API. JWT does not attempt to implement the Javascript Object Signing and Encryption (JOSE) standard. The goal of the package is to provide a very small package with no depencies that can be used to generate, sign, and verify JWT. JWT provides the following features:

  • Simple declarative API
  • No external depencies
  • Token integrity and verification through HMAC SHA256

Installing

You can install jwt under your GOPATH if your version of Go does not support modules. Run the following command to install jwt under your GOPATH:

go get github.com/jrpalma/jwt

JWT also supports Go modules. All you have to do is initialize your project and import jwt into your project. If your project has not been initialized, all you have to do is run the following command under your project:

# You will have to specify <project path>
# if you are outside your GOPATH
go mod init <project path>

Concepts

JWT are composed of tree elements: Header, Payload (Claims), and a signature. The API allows the adition of elements to the JWT's Header and Claims. Once a JWT contains the desired header values and claims, the token can be signed. A JWT can also be verified to ensure its header and claims have not been modified. All this is done by using a combination of a secrete or symmetric key and HMAC.

Tokens

A new token can be created by calling the function NewJWT(). This functions returns a new JWT prefilled with a couple of Header values and a Claim. The token has the type and alg header values filled with jwt and HS256 respectively. This makes the JWT type jwt and the HMAC algorithm to be of type HMAC SHA256. Also, the Claim "Issued At" is set to the current time. The JWT object returned by NewJWT can be signed by calling its Sign method which requires a secret string as its input. The following code creates a jwt token with the issued at claim set to the current time, signs the token, and return the base64 encoded JWT in the form of "HEADER.PAYLOAD (CLAIMS).SIGNATURE". It then verifies it.

token := NewJWT()
base64JWT, signErr := token.Sign("secrete")
if signErr != nil {
	return signerr
}

verifyErr := token.Verify(base64JWT, "secret")
if verifyErr != nil {
	test.Errorf("Failed to verify token: %v", verifyErr)
}

Header

A JWT header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA. Although the JWT RFC supports RSA for JWT, this package only support HMAC SHA256. This package allows for other header values to be added or removed from the header section so that JWT's header can be easily extended. The following code creates a JWT token and adds the header value eventType to the header.

token := NewJWT()
token.Header.Set("eventType", "newUser")

Claims

According to the JWT's website:

The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims.

Registered claims: These are a set of predefined claims which are not mandatory but recommended, to provide a set of useful, interoperable claims. Some of them are: iss (issuer), exp (expiration time), sub (subject), aud (audience), and others.

Public claims: These can be defined at will by those using JWTs. But to avoid collisions they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision resistant namespace.

Private claims: These are the custom claims created to share information between parties that agree on using them and are neither registered or public claims.

The following code creates a JWT token, adds some claims, signs it, and verifies it.

token := NewJWT()
token.Claims.Set("user", "jose")
token.Claims.Set("id", "12345666666")

base64JWT, signErr := token.Sign("secret")
if signErr != nil {
	return signerr
}

verifyErr := token.Verify(base64JWT, "secret")
if verifyErr != nil {
	test.Errorf("Failed to verify token: %v", verifyErr)
}

Contributing

  1. Fork it
  2. Clone it git clone https://github.com/user_name/arg && cd arg)
  3. Create your feature branch (git checkout -b my-new-feature)
  4. Make changes and add them (git add .)
  5. Commit your changes (git commit -m 'Add some feature')
  6. Push to the branch (git push origin my-new-feature)
  7. Create new pull request

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Claims

type Claims struct {
	// contains filtered or unexported fields
}

Claims represents a JWT claims section.

func NewClaims

func NewClaims() *Claims

NewClaims creates a new JWT Claims object.

func (*Claims) Del

func (claims *Claims) Del(name string)

Del Deletes value in the Claims.

func (*Claims) Get

func (claims *Claims) Get(name string) (interface{}, bool)

Get gets the value in the Header given by name.

func (*Claims) GetAudience

func (claims *Claims) GetAudience() (string, error)

GetAudience gets the audience for the Claims.

func (*Claims) GetBool

func (claims *Claims) GetBool(name string) (bool, error)

GetBool Gets the bool value in the Claims given by name.

func (*Claims) GetBytes

func (claims *Claims) GetBytes(name string) ([]byte, error)

GetBytes Gets a byte slice value in the Claims given by name.

func (*Claims) GetExpiration

func (claims *Claims) GetExpiration() (time.Time, error)

GetExpiration gets the expiration timestamp for the Claims.

func (*Claims) GetFloat64

func (claims *Claims) GetFloat64(name string) (float64, error)

GetFloat64 Gets a float64 value in the Claims given by name.

func (*Claims) GetIssuedAt

func (claims *Claims) GetIssuedAt() (time.Time, error)

GetIssuedAt gets the issued at timestamp for the Claims.

func (*Claims) GetIssuer

func (claims *Claims) GetIssuer() (string, error)

GetIssuer gets the issuer for the Claims.

func (*Claims) GetJTI

func (claims *Claims) GetJTI() (string, error)

GetJTI gets the JWT ID for the Claims.

func (*Claims) GetNotBefore

func (claims *Claims) GetNotBefore() (time.Time, error)

GetNotBefore gets the not before timestamp for the Claims.

func (*Claims) GetPrincipal

func (claims *Claims) GetPrincipal() (string, error)

GetPrincipal gets the principal for the Claims.

func (*Claims) GetString

func (claims *Claims) GetString(name string) (string, error)

GetString Gets the string value in the Claims given by name.

func (*Claims) GetTime

func (claims *Claims) GetTime(name string) (time.Time, error)

GetTime Gets a time value in the Claims given by name.

func (*Claims) GetType

func (claims *Claims) GetType() (string, error)

GetType gets the type for the claim.

func (*Claims) Has

func (claims *Claims) Has(name string) bool

Has returns true if the Claims has value with the given name.

func (*Claims) Keys

func (claims *Claims) Keys() []string

Keys gets the names of all the values in the Claims.

func (*Claims) Len

func (claims *Claims) Len() int

Len returns the number of values in the Claims.

func (*Claims) Marshal

func (claims *Claims) Marshal() ([]byte, error)

Marshal encodes the Claims values into JSON.

func (*Claims) Set

func (claims *Claims) Set(name string, value interface{})

Set sets a value in the Claims

func (*Claims) SetAudience

func (claims *Claims) SetAudience(aud string)

SetAudience sets the audience for the Claims.

func (*Claims) SetExpiration

func (claims *Claims) SetExpiration(exp time.Time)

SetExpiration sets the expiration timestamp for the Claims.

func (*Claims) SetIssuedAt

func (claims *Claims) SetIssuedAt(iat time.Time)

SetIssuedAt sets the issued at timestamp for the Claims.

func (*Claims) SetIssuer

func (claims *Claims) SetIssuer(iss string)

SetIssuer sets the issuer for the Claims.

func (*Claims) SetJTI

func (claims *Claims) SetJTI(jti string)

SetJTI sets the JWT ID for the Claims.

func (*Claims) SetNotBefore

func (claims *Claims) SetNotBefore(nbf time.Time)

SetNotBefore sets the not before timestamp for the Claims.

func (*Claims) SetPrincipal

func (claims *Claims) SetPrincipal(prn string)

SetPrincipal sets the principal for the Claims.

func (*Claims) SetType

func (claims *Claims) SetType(typ string)

SetType sets the type for the Claims.

func (*Claims) Unmarshal

func (claims *Claims) Unmarshal(bytes []byte) error

Unmarshal decodes the Claims values into a Claims object.

type Header struct {
	// contains filtered or unexported fields
}

Header represents a JWT header object.

func NewHeader

func NewHeader() *Header

NewHeader creates a new JWT Header.

func (*Header) Del

func (header *Header) Del(name string)

Del deletes a value in the Header.

func (*Header) Get

func (header *Header) Get(name string) (interface{}, bool)

Get gets the value in the Header given by name.

func (*Header) GetBool

func (header *Header) GetBool(name string) (bool, error)

GetBool Gets the bool value in the Header given by name.

func (*Header) GetBytes

func (header *Header) GetBytes(name string) ([]byte, error)

GetBytes Gets a byte slice value in the Header given by name.

func (*Header) GetFloat64

func (header *Header) GetFloat64(name string) (float64, error)

GetFloat64 Gets a float64 value in the Header given by name.

func (*Header) GetString

func (header *Header) GetString(name string) (string, error)

GetString Gets the string value in the Header given by name.

func (*Header) GetTime

func (header *Header) GetTime(name string) (time.Time, error)

GetTime Gets a time value in the Header given by name.

func (*Header) Has

func (header *Header) Has(name string) bool

Has returns true if the Header has value given by name.

func (*Header) Keys

func (header *Header) Keys() []string

Keys gets the names of all the values in the Header.

func (*Header) Len

func (header *Header) Len() int

Len returns the number of values in the Header.

func (*Header) Marshal

func (header *Header) Marshal() ([]byte, error)

Marshal encodes the Header values into JSON.

func (*Header) Set

func (header *Header) Set(name string, value interface{})

Set sets a value in the Header with the given name.

func (*Header) Unmarshal

func (header *Header) Unmarshal(bytes []byte) error

Unmarshal decodes the header values into a Header object.

type JWT

type JWT struct {
	Header *Header
	Claims *Claims
}

JWT Represents a JSON Web Token. A JWT contain a Header and Claims.

func NewJWT

func NewJWT() *JWT

NewJWT Creates a new JWT. The token contains the typ and alg header. The only supported algorithm is HS256 or HMAC SHA256.

func (*JWT) Sign

func (jwt *JWT) Sign(secret string) (string, error)

Sign Signs and and returns a compacted base 64 encode JWT in the form of "header.payload.signature". The secret parameter is the symmetric key used to create the signature.

func (*JWT) Verify

func (jwt *JWT) Verify(compact string, secret string) error

Verify Deserializes a compacted JWT and verifies the token using symmetric key secret.

Jump to

Keyboard shortcuts

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