jwt

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2020 License: BSD-3-Clause Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ED25519          = jose.ED25519
	RSA15            = jose.RSA1_5
	RSAOAEP          = jose.RSA_OAEP
	RSAOAEP256       = jose.RSA_OAEP_256
	A128KW           = jose.A128KW
	A192KW           = jose.A192KW
	A256KW           = jose.A256KW
	DIRECT           = jose.DIRECT
	ECDHES           = jose.ECDH_ES
	ECDHESA128KW     = jose.ECDH_ES_A128KW
	ECDHESA192KW     = jose.ECDH_ES_A192KW
	ECDHESA256KW     = jose.ECDH_ES_A256KW
	A128GCMKW        = jose.A128GCMKW
	A192GCMKW        = jose.A192GCMKW
	A256GCMKW        = jose.A256GCMKW
	PBES2HS256A128KW = jose.PBES2_HS256_A128KW
	PBES2HS384A192KW = jose.PBES2_HS384_A192KW
	PBES2HS512A256KW = jose.PBES2_HS512_A256KW
)

Key management algorithms.

View Source
const (
	EdDSA = jose.EdDSA
	HS256 = jose.HS256
	HS384 = jose.HS384
	HS512 = jose.HS512
	RS256 = jose.RS256
	RS384 = jose.RS384
	RS512 = jose.RS512
	ES256 = jose.ES256
	ES384 = jose.ES384
	ES512 = jose.ES512
	PS256 = jose.PS256
	PS384 = jose.PS384
	PS512 = jose.PS512
)

Signature algorithms.

View Source
const (
	A128CBCHS256 = jose.A128CBC_HS256
	A192CBCHS384 = jose.A192CBC_HS384
	A256CBCHS512 = jose.A256CBC_HS512
	A128GCM      = jose.A128GCM
	A192GCM      = jose.A192GCM
	A256GCM      = jose.A256GCM
)

Content encryption algorithms.

View Source
const (
	DefaultSignFilename = "jwt_sign.key"
	DefaultEncFilename  = "jwt_enc.key"
)

Default key filenames for `RSA`.

View Source
const (
	// ClaimsContextKey is the context key which the jwt claims are stored from the `Verify` method.
	ClaimsContextKey = "iris.jwt.claims"
)

Variables

View Source
var (
	// ErrMissing when token cannot be extracted from the request.
	ErrMissing = errors.New("token is missing")
	// ErrExpired indicates that token is used after expiry time indicated in exp claim.
	ErrExpired = errors.New("token is expired (exp)")
	// ErrNotValidYet indicates that token is used before time indicated in nbf claim.
	ErrNotValidYet = errors.New("token not valid yet (nbf)")
	// ErrIssuedInTheFuture indicates that the iat field is in the future.
	ErrIssuedInTheFuture = errors.New("token issued in the future (iat)")
)
View Source
var (
	// ErrNotPEM is an error type of the `ParseXXX` function(s) fired
	// when the data are not PEM-encoded.
	ErrNotPEM = errors.New("key must be PEM encoded")
	// ErrInvalidKey is an error type of the `ParseXXX` function(s) fired
	// when the contents are not type of rsa private key.
	ErrInvalidKey = errors.New("key is not of type *rsa.PrivateKey")
)
View Source
var (
	// NewNumericDate constructs NumericDate from time.Time value.
	NewNumericDate = jwt.NewNumericDate
)

Functions

func FromHeader

func FromHeader(ctx *context.Context) string

FromHeader is a token extractor. It reads the token from the Authorization request header of form: Authorization: "Bearer {token}".

func FromQuery

func FromQuery(ctx *context.Context) string

FromQuery is a token extractor. It reads the token from the "token" url query parameter.

func Get

func Get(ctx *context.Context) (interface{}, error)

Get returns and validates (if not already) the claims stored on request context's values storage.

Should be used instead of the `ReadClaims` method when a custom verification middleware was registered (see the `Verify` method for an example).

Usage: j := jwt.New(...) [...]

app.Use(func(ctx iris.Context) {
	var claims CustomClaims_or_jwt.Claims
	if err := j.VerifyToken(ctx, &claims); err != nil {
		ctx.StopWithStatus(iris.StatusUnauthorized)
		return
	}

	ctx.Values().Set(jwt.ClaimsContextKey, claims)
	ctx.Next()
})

[...]

app.Post("/restricted", func(ctx iris.Context){
	v, err := jwt.Get(ctx)
 [handle error...]
 claims,ok := v.(CustomClaims_or_jwt.Claims)
 if !ok {
	  [do you support more than one type of claims? Handle here]
	}
 [use claims...]
})

func IsValidated

func IsValidated(ctx *context.Context) bool

IsValidated reports whether a token is already validated through `VerifyToken`. It returns true when the claims are compatible validators: a `Claims` value or a value that implements the `Validate() error` method.

func LoadRSA

func LoadRSA(fname string, bits int) (key *rsa.PrivateKey, err error)

LoadRSA tries to read RSA Private Key from "fname" system file, if does not exist then it generates a new random one based on "bits" (e.g. 2048, 4096) and exports it to a new "fname" file.

func ParseRSAPrivateKey

func ParseRSAPrivateKey(key, password []byte) (*rsa.PrivateKey, error)

ParseRSAPrivateKey encodes a PEM-encoded PKCS1 or PKCS8 private key protected with a password.

func ReadClaims

func ReadClaims(ctx *context.Context, claimsPtr interface{}) error

ReadClaims binds the "claimsPtr" (destination) to the verified (and decrypted) claims. The `Verify` method should be called first (registered as middleware).

Types

type Audience

type Audience = jwt.Audience

Audience represents the recipients that the token is intended for.

type Claims

type Claims = jwt.Claims

Claims represents public claim values (as specified in RFC 7519).

func Expiry

func Expiry(maxAge time.Duration, claims Claims) Claims

Expiry returns a new standard Claims with the `Expiry` and `IssuedAt` fields of the "claims" filled based on the given "maxAge" duration.

See the `JWT.Expiry` method too.

type ContentEncryption

type ContentEncryption = jose.ContentEncryption

ContentEncryption represents a content encryption algorithm.

type JWT

type JWT struct {
	// MaxAge is the expiration duration of the generated tokens.
	MaxAge time.Duration

	// Extractors are used to extract a raw token string value
	// from the request.
	// Builtin extractors:
	// * FromHeader
	// * FromQuery
	// * FromJSON
	// Defaults to a slice of `FromHeader` and `FromQuery`.
	Extractors []TokenExtractor

	// Signer is used to sign the token.
	// It is set on `New` and `Default` package-level functions.
	Signer jose.Signer
	// VerificationKey is used to verify the token (public key).
	VerificationKey interface{}

	// Encrypter is used to, optionally, encrypt the token.
	// It is set on `WithEncryption` method.
	Encrypter jose.Encrypter
	// DecriptionKey is used to decrypt the token (private key)
	DecriptionKey interface{}
}

JWT holds the necessary information the middleware need to sign and verify tokens.

The `RSA(privateFile, publicFile, password)` package-level helper function can be used to decode the SignKey and VerifyKey.

func HMAC

func HMAC(maxAge time.Duration, keys ...string) *JWT

HMAC returns a new `JWT` instance. It tries to read hmac256 secret keys from system environment variables: * JWT_SECRET for signing and verification key and * JWT_SECRET_ENC for encryption and decryption key and defaults them to the given "keys" respectfully.

It panics on errors. Use the `New` package-level function instead for more options.

func New

func New(maxAge time.Duration, alg SignatureAlgorithm, key interface{}) (*JWT, error)

New returns a new JWT instance. It accepts a maximum time duration for token expiration and the algorithm among with its key for signing and verification.

See `WithEncryption` method to add token encryption too. Use `Token` method to generate a new token string and `VerifyToken` method to decrypt, verify and bind claims of an incoming request token. Token, by default, is extracted by "Authorization: Bearer {token}" request header and url query parameter of "token". Token extractors can be modified through the `Extractors` field.

For example, if you want to sign and verify using RSA-256 key:

  1. Generate key file, e.g: $ openssl genrsa -des3 -out private.pem 2048
  2. Read file contents with io.ReadFile("./private.pem")
  3. Pass the []byte result to the `ParseRSAPrivateKey(contents, password)` package-level helper
  4. Use the result *rsa.PrivateKey as "key" input parameter of this `New` function.

See aliases.go file for available algorithms.

func RSA

func RSA(maxAge time.Duration, filenames ...string) *JWT

RSA returns a new `JWT` instance. It tries to parse RSA256 keys from "filenames[0]" (defaults to "jwt_sign.key") and "filenames[1]" (defaults to "jwt_enc.key") files or generates and exports new random keys.

It panics on errors. Use the `New` package-level function instead for more options.

func (*JWT) Expiry

func (j *JWT) Expiry(claims Claims) Claims

Expiry method same as `Expiry` package-level function, it returns a Claims with the expiration fields of the "claims" filled based on the JWT's `MaxAge` field. Only use it when this standard "claims" is embedded on a custom claims structure. Usage:

type UserClaims struct {
	jwt.Claims
	Username string
}

[...] standardClaims := j.Expiry(jwt.Claims{...})

customClaims := UserClaims{
	Claims:   standardClaims,
	Username: "kataras",
}

j.WriteToken(ctx, customClaims)

func (*JWT) Token

func (j *JWT) Token(claims interface{}) (string, error)

Token generates and returns a new token string. See `VerifyToken` too.

func (*JWT) Verify

func (j *JWT) Verify(ctx *context.Context)

Verify is a middleware. It verifies and optionally decrypts an incoming request token. It does write a 401 unauthorized status code if verification or decryption failed. It calls the `ctx.Next` on verified requests.

See `VerifyToken` instead to verify, decrypt, validate and acquire the claims at once.

A call of `ReadClaims` is required to validate and acquire the jwt claims on the next request.

func (*JWT) VerifyToken

func (j *JWT) VerifyToken(ctx *context.Context, claimsPtr interface{}) error

VerifyToken verifies (and decrypts) the request token, it also validates and binds the parsed token's claims to the "claimsPtr" (destination). It does return a nil error on success.

func (*JWT) WithEncryption

func (j *JWT) WithEncryption(contentEncryption ContentEncryption, alg KeyAlgorithm, key interface{}) error

WithEncryption method enables encryption and decryption of the token. It sets an appropriate encrypter(`Encrypter` and the `DecriptionKey` fields) based on the key type.

func (*JWT) WriteToken

func (j *JWT) WriteToken(ctx *context.Context, claims interface{}) error

WriteToken is a helper which just generates(calls the `Token` method) and writes a new token to the client in plain text format.

Use the `Token` method to get a new generated token raw string value.

type KeyAlgorithm

type KeyAlgorithm = jose.KeyAlgorithm

KeyAlgorithm represents a key management algorithm.

type NumericDate

type NumericDate = jwt.NumericDate

NumericDate represents date and time as the number of seconds since the epoch, including leap seconds. Non-integer values can be represented in the serialized format, but we round to the nearest second.

type SignatureAlgorithm

type SignatureAlgorithm = jose.SignatureAlgorithm

SignatureAlgorithm represents a signature (or MAC) algorithm.

type TokenExtractor

type TokenExtractor func(*context.Context) string

TokenExtractor is a function that takes a context as input and returns a token. An empty string should be returned if no token found without additional information.

func FromJSON

func FromJSON(jsonKey string) TokenExtractor

FromJSON is a token extractor. Reads a json request body and extracts the json based on the given field. The request content-type should contain the: application/json header value, otherwise this method will not try to read and consume the body.

Jump to

Keyboard shortcuts

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