jwt

package module
v0.0.0-...-ec228b0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 7 Imported by: 147

README

jwt

JSON Web Token verification for Iris v14, built on golang-jwt/jwt v4.

Iris has its own JWT middleware, kataras/iris/middleware/jwt. It signs as well as verifies, decodes claims into your own struct, supports encrypted payloads and a blocklist, and is maintained with the framework. Prefer it for new code. This module remains for applications that already use it.

Install

go get github.com/iris-contrib/middleware/jwt@main
import "github.com/iris-contrib/middleware/jwt"

Example

package main

import (
	"time"

	"github.com/kataras/iris/v14"

	"github.com/iris-contrib/middleware/jwt"
)

// In production load the secret from the environment or from a file.
var mySecret = []byte("My Secret")

func main() {
	app := iris.New()

	j := jwt.New(jwt.Config{
		ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
			return mySecret, nil
		},
		// Refuse a token signed with any other algorithm.
		SigningMethod: jwt.SigningMethodHS256,
		// Refuse a token that has expired or has no "exp" claim.
		Expiration: true,
	})

	// Issues a token.
	app.Get("/token", func(ctx iris.Context) {
		token := jwt.NewTokenWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
			"foo": "bar",
			"exp": time.Now().Add(15 * time.Minute).Unix(),
		})

		tokenString, err := token.SignedString(mySecret)
		if err != nil {
			ctx.StopWithError(iris.StatusInternalServerError, iris.PrivateError(err))
			return
		}

		ctx.WriteString(tokenString)
	})

	// j.Serve answers 401 unless the request carries a valid token in the
	// "Authorization: Bearer <token>" header.
	app.Get("/protected", j.Serve, func(ctx iris.Context) {
		// The token that j.Serve verified.
		token := j.Get(ctx)

		claims := token.Claims.(jwt.MapClaims)
		ctx.Writef("foo=%s", claims["foo"])
	})

	// To protect a group of routes: app.Router("/users", j.Serve)

	app.Listen(":8080")
}
TOKEN=$(curl -s http://localhost:8080/token)
curl -H "Authorization: Bearer $TOKEN" http://localhost:8080/protected

j.CheckJWT(ctx) runs the same check from inside a handler and returns the error instead of answering.

Config

Field Default Description
ValidationKeyGetter none, required Returns the key that verifies the signature: a shared secret or a public key.
SigningMethod none When set, a token signed with another algorithm is refused. Set it. Without it the algorithm named in the token is trusted.
Expiration false When true, a token without an exp claim is refused. An exp in the past is always refused.
Extractor FromAuthHeader Where the token is read from.
ContextKey "jwt" The Context key the verified *jwt.Token is stored under. Middleware.Get(ctx) reads it.
ErrorHandler OnError Called with the error of a refused request.
CredentialsOptional false When true, a request without a token passes and Get(ctx) returns nil. A token that is present must still be valid.
EnableAuthOnOptions false When false, OPTIONS requests pass unchecked, for CORS preflight.

OnError answers 401 Unauthorized with the error's text and stores the error on the Context, where ctx.GetErr() returns it.

Token extractors

Extractor Reads the token from
FromAuthHeader The Authorization: Bearer <token> request header.
FromParameter(name) The URL query parameter name.
FromFirst(extractors...) The first of the given extractors that finds one.

A token in a URL is written to access logs, kept in the browser history and sent in Referer headers. Use FromParameter only where a header cannot be set, such as a download link. The framework's own middleware stopped reading the URL by default in v14 for this reason.

package main

import (
	"github.com/kataras/iris/v14"

	"github.com/iris-contrib/middleware/jwt"
)

func main() {
	app := iris.New()

	j := jwt.New(jwt.Config{
		ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
			return []byte("My Secret"), nil
		},
		SigningMethod: jwt.SigningMethodHS256,
		// The header first, then the "token" URL query parameter.
		Extractor: jwt.FromFirst(jwt.FromAuthHeader, jwt.FromParameter("token")),
	})

	app.Get("/download", j.Serve, func(ctx iris.Context) {
		ctx.WriteString("the file")
	})

	app.Listen(":8080")
}

A TokenExtractor is a func(iris.Context) (string, error). Return an empty string and no error when the request has no token.

Names re-exported from golang-jwt

Token, MapClaims, Claims, NewToken, NewTokenWithClaims and the signing methods SigningMethodHS256, HS384, HS512, ES256, ES384 and ES512. For anything else import github.com/golang-jwt/jwt/v4 directly.

Documentation

Index

Constants

View Source
const (
	// DefaultContextKey jwt
	DefaultContextKey = "jwt"
)

Variables

View Source
var (
	NewToken           = jwt.New
	NewTokenWithClaims = jwt.NewWithClaims
)

Shortcuts to create a new Token.

View Source
var (
	SigningMethodHS256 = jwt.SigningMethodHS256
	SigningMethodHS384 = jwt.SigningMethodHS384
	SigningMethodHS512 = jwt.SigningMethodHS512
)

HS256 and company.

View Source
var (
	SigningMethodES256 = jwt.SigningMethodES256
	SigningMethodES384 = jwt.SigningMethodES384
	SigningMethodES512 = jwt.SigningMethodES512
)

ECDSA - EC256 and company.

View Source
var (
	// ErrTokenMissing is the error value that it's returned when
	// a token is not found based on the token extractor.
	ErrTokenMissing = errors.New("required authorization token not found")

	// ErrTokenInvalid is the error value that it's returned when
	// a token is not valid.
	ErrTokenInvalid = errors.New("token is invalid")

	// ErrTokenExpired is the error value that it's returned when
	// a token value is found and it's valid but it's expired.
	ErrTokenExpired = errors.New("token is expired")
)

Functions

func FromAuthHeader

func FromAuthHeader(ctx iris.Context) (string, error)

FromAuthHeader is a "TokenExtractor" that takes a give context and extracts the JWT token from the Authorization header.

func OnError

func OnError(ctx iris.Context, err error)

OnError is the default error handler. It stops the request with 401 (Unauthorized) and the error's text, and stores the error on the Context (see Context.GetErr). Set `Config.ErrorHandler` to change the behavior.

Types

type Claims

type Claims = jwt.Claims

Claims must just have a Valid method that determines if the token is invalid for any supported reason.

A type alias for jwt.Claims.

type Config

type Config struct {
	// The function that will return the Key to validate the JWT.
	// It can be either a shared secret or a public key.
	// Default value: nil
	ValidationKeyGetter jwt.Keyfunc
	// The name of the property in the request where the user (&token) information
	// from the JWT will be stored.
	// Default value: "jwt"
	ContextKey string
	// The function that will be called when there's an error validating the token
	// Default value: OnError
	ErrorHandler errorHandler
	// A boolean indicating if the credentials are required or not
	// Default value: false
	CredentialsOptional bool
	// A function that extracts the token from the request
	// Default: FromAuthHeader (i.e., from Authorization header as bearer token)
	Extractor TokenExtractor
	// When set, all requests with the OPTIONS method will use authentication
	// if you enable this option you should register your route with app.Options(...) also
	// Default: false
	EnableAuthOnOptions bool
	// When set, the middelware verifies that tokens are signed with the specific signing algorithm
	// If the signing method is not constant the ValidationKeyGetter callback can be used to implement additional checks
	// Important to avoid security issues described here: https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
	// Default: nil
	SigningMethod jwt.SigningMethod
	// When set, the expiration time of token will be check every time
	// if the token was expired, expiration error will be returned
	// Default: false
	Expiration bool
}

Config is a struct for specifying configuration options for the jwt middleware.

type MapClaims

type MapClaims = jwt.MapClaims

MapClaims type that uses the map[string]interface{} for JSON decoding This is the default claims type if you don't supply one

A type alias for jwt.MapClaims.

type Middleware

type Middleware struct {
	Config Config
}

Middleware the middleware for JSON Web tokens authentication method

func New

func New(cfg ...Config) *Middleware

New constructs a new Middleware instance with supplied options.

func (*Middleware) CheckJWT

func (m *Middleware) CheckJWT(ctx iris.Context) error

CheckJWT the main functionality, checks for token

func (*Middleware) Get

func (m *Middleware) Get(ctx iris.Context) *jwt.Token

Get returns the user (&token) information for this client/request

func (*Middleware) Serve

func (m *Middleware) Serve(ctx iris.Context)

Serve the middleware's action

type Token

type Token = jwt.Token

Token for JWT. Different fields will be used depending on whether you're creating or parsing/verifying a token.

A type alias for jwt.Token.

type TokenExtractor

type TokenExtractor func(iris.Context) (string, error)

TokenExtractor is a function that takes a context as input and returns either a token or an error. An error should only be returned if an attempt to specify a token was found, but the information was somehow incorrectly formed. In the case where a token is simply not present, this should not be treated as an error. An empty string should be returned in that case.

func FromFirst

func FromFirst(extractors ...TokenExtractor) TokenExtractor

FromFirst returns a function that runs multiple token extractors and takes the first token it finds

func FromParameter

func FromParameter(param string) TokenExtractor

FromParameter returns a function that extracts the token from the specified query string parameter

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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