Documentation ¶
Index ¶
- Constants
- Variables
- func FromHeader(ctx *context.Context) string
- func FromQuery(ctx *context.Context) string
- func Get(ctx *context.Context) (interface{}, error)
- func IsValidated(ctx *context.Context) bool
- func LoadRSA(fname string, bits int) (key *rsa.PrivateKey, err error)
- func ParseRSAPrivateKey(key, password []byte) (*rsa.PrivateKey, error)
- func ReadClaims(ctx *context.Context, claimsPtr interface{}) error
- type Audience
- type Claims
- type ContentEncryption
- type JWT
- func (j *JWT) Expiry(claims Claims) Claims
- func (j *JWT) Token(claims interface{}) (string, error)
- func (j *JWT) Verify(ctx *context.Context)
- func (j *JWT) VerifyToken(ctx *context.Context, claimsPtr interface{}) error
- func (j *JWT) WithEncryption(contentEncryption ContentEncryption, alg KeyAlgorithm, key interface{}) error
- func (j *JWT) WriteToken(ctx *context.Context, claims interface{}) error
- type KeyAlgorithm
- type NumericDate
- type SignatureAlgorithm
- type TokenExtractor
Constants ¶
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.
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.
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.
const ( DefaultSignFilename = "jwt_sign.key" DefaultEncFilename = "jwt_enc.key" )
Default key filenames for `RSA`.
const (
// ClaimsContextKey is the context key which the jwt claims are stored from the `Verify` method.
ClaimsContextKey = "iris.jwt.claims"
)
Variables ¶
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)") )
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") )
var ( // NewNumericDate constructs NumericDate from time.Time value. NewNumericDate = jwt.NewNumericDate )
Functions ¶
func FromHeader ¶
FromHeader is a token extractor. It reads the token from the Authorization request header of form: Authorization: "Bearer {token}".
func FromQuery ¶
FromQuery is a token extractor. It reads the token from the "token" url query parameter.
func Get ¶
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 ¶
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 ¶
ReadClaims binds the "claimsPtr" (destination) to the verified (and decrypted) claims. The `Verify` method should be called first (registered as middleware).
Types ¶
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 ¶
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:
- Generate key file, e.g: $ openssl genrsa -des3 -out private.pem 2048
- Read file contents with io.ReadFile("./private.pem")
- Pass the []byte result to the `ParseRSAPrivateKey(contents, password)` package-level helper
- Use the result *rsa.PrivateKey as "key" input parameter of this `New` function.
See aliases.go file for available algorithms.
func RSA ¶
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 ¶
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) Verify ¶
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 ¶
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.
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 ¶
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.