jwt

package
v14.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: BSD-3-Clause, BSD-3-Clause Imports: 8 Imported by: 0

README

How to use JWT authentication with Iris

A JSON Web Token carries signed claims about a user, so a server can trust a request without keeping session state. This tutorial builds JWT authentication into an Iris application: a login endpoint that issues tokens, a protected endpoint that requires one, and a refresh endpoint that exchanges an expiring token for a new pair.

Prerequisites

To follow this tutorial, you will need:

  • Go 1.27 or higher installed on your machine
  • A basic understanding of Go and Iris
  • A text editor or IDE of your choice (e.g. VS Code)

Creating a new Iris project

Start a new Iris project with go mod. Run the following commands:

$ mkdir iris-jwt
$ cd iris-jwt
$ go mod init iris-jwt
$ go get github.com/kataras/iris/v14@latest

This will create a new folder called iris-jwt with the following files:

iris-jwt
├── go.mod
└── go.sum

The go.mod file contains the module name and the dependency on Iris. The go.sum file contains the checksums of the dependencies.

Create a file called main.go in the same folder with enough code to start a server on port 8080. The JWT logic goes into this same file as the tutorial continues.

package main

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

func main() {
    // Create a new Iris application.
    app := iris.New()

    // Register a simple GET handler at the root path.
    app.Get("/", func(ctx iris.Context) {
        ctx.WriteString("Hello, world!")
    })

    // Start the server at http://localhost:8080.
    app.Listen(":8080")
}

To run the server, run the following command:

$ go run main.go

You should see something like this in your terminal:

Now listening on: http://localhost:8080
Application started. Press CTRL+C to shut down.

You can also visit http://localhost:8080 in your browser and see the message "Hello, world!".

Defining the user model and the JWT claims

Now, we will define a simple user model and a custom JWT claims struct in our main.go file. The user model will represent the data of our users, such as username and password. The JWT claims struct will contain the information that we want to store in our JWT tokens, such as user ID and expiration time.

We will also define some constants for our secret keys and token expiration durations.

package main

import (
    "time"

    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/middleware/jwt"
)

// User is a simple user model.
type User struct {
    ID       int64  `json:"id"`
    Username string `json:"username"`
    Password string `json:"password"`
}

// Claims is a custom JWT claims struct.
type Claims struct {
    jwt.Claims // embeds standard claims iat, exp and sub.
    UserID     int64  `json:"user_id"`
}

// Define some constants for our secret keys and token expiration durations.
const (
    accessSecret  = "my-access-secret"
    refreshSecret = "my-refresh-secret"
    accessExpire  = 15 * time.Minute
    refreshExpire = 24 * time.Hour
)

Creating a signer and a verifier for JWT

The middleware/jwt package gives you a signer and a verifier. The signer generates and signs tokens from your secret key and claims; the verifier checks the token a client sends and rejects anything that does not hold up.

Create two signers, one for the access token and one for the refresh token, and one verifier for the access token. Encrypting the tokens on top of signing them keeps the claims unreadable to whoever holds the token.

package main

import (
    "time"

    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/middleware/jwt"
)

// ...

// Create a signer for the access token.
accessSigner := jwt.NewSigner(jwt.HS256, accessSecret, accessExpire).
    // Use encryption for the access token.
    WithEncryption([]byte("my-access-encryption-key"), nil)

// Create a signer for the refresh token.
refreshSigner := jwt.NewSigner(jwt.HS256, refreshSecret, refreshExpire).
    // Use encryption for the refresh token.
    WithEncryption([]byte("my-refresh-encryption-key"), nil)

// Create a verifier for the access token.
accessVerifier := jwt.NewVerifier(jwt.HS256, accessSecret).
    // Use decryption for the access token.
    WithDecryption([]byte("my-access-encryption-key"), nil)
    // Use a blocklist to revoke tokens.
    // .WithDefaultBlocklist()

Creating some mock users and a login handler

To keep the example short, the users live in a map. A real application would read them from a database.

The login handler takes a username and password from the request, checks them against that map, and on a match signs an access token and a refresh token and returns both.

package main

import (
    "time"

    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/middleware/jwt"
    "github.com/kataras/iris/v14/rest/errors"
)

// ...

// Create some mock users in a map.
users := map[string]User{
    "alice": {ID: 1, Username: "alice", Password: "1234"},
    "bob":   {ID: 2, Username: "bob", Password: "5678"},
}

// Create a login handler that will generate JWT tokens for authenticated users.
loginHandler := func(ctx iris.Context) {
    // Get the username and password from the request body.
    user, ok := ctx.BindJSON[User]()
    if !ok {
        return // ctx.BindJSON wrote the 400 itself.
    }

    // Check if the username and password match with one of our mock users.
    u, found := users[user.Username]
    if !found || u.Password != user.Password {
        errors.Unauthenticated.Message(ctx, "invalid credentials")
        return
    }

    // Generate an access token with the user ID as the subject claim.
    accessClaims := Claims{
        Claims: jwt.Claims{Subject: u.Username},
        UserID: u.ID,
    }
    accessToken, err := accessSigner.Sign(accessClaims)
    if err != nil {
        errors.HandleError(ctx, err)
        return
    }

    // Generate a refresh token with the user ID as the subject claim.
    refreshClaims := Claims{
        Claims: jwt.Claims{Subject: u.Username},
        UserID: u.ID,
    }
    refreshToken, err := refreshSigner.Sign(refreshClaims)
    if err != nil {
        errors.HandleError(ctx, err)
        return
    }

    /* OR
    tokenPair, err := refreshSigner.NewTokenPair(accessClaims, refreshClaims, refreshExpire)
    // [handle err...]
    ctx.JSON(tokenPair)
    */

    // Send the tokens to the client as JSON.
    ctx.OK(iris.Map{
        "access_token":  string(accessToken),
        "refresh_token": string(refreshToken),
        "expires_in":    int64(accessExpire.Seconds()),
    }, nil)
}

Creating a protected API handler

A protected endpoint puts the access verifier in front of the handler as middleware. A request without a valid token never reaches the handler. When the token is valid, the handler reads the user ID out of the claims and answers with it.

package main

import (
    "time"

    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/middleware/jwt"
    "github.com/kataras/iris/v14/rest/errors"
)

// ...

// Create a protected API handler that will only allow authorized users to access it.
protectedHandler := func(ctx iris.Context) {
    // Get the verified token from the context.
    token := jwt.GetVerifiedToken(ctx) // important step.

    // Get the custom claims from the token.
    var claims Claims
    if err := token.Claims(&claims); err != nil { // important step.
        errors.HandleError(ctx, err)
        return
    }

    // Get the user ID from the claims.
    userID := claims.UserID

    // Send the user ID to the client as JSON.
    // This is just an example, you can do whatever you want here.
    ctx.OK(iris.Map{
        "user_id": userID,
    }, nil)
}

Creating a refresh handler

Access tokens are short-lived on purpose, so a client needs a way to get a fresh one without asking the user to log in again. The refresh handler verifies the refresh token and, if it holds up, signs a new access and refresh token for the same user.

package main

import (
    "time"

    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/middleware/jwt"
    "github.com/kataras/iris/v14/rest/errors"
)

// ...

// Create a refresh handler that will allow users to refresh their access tokens using their refresh tokens.
refreshHandler := func(ctx iris.Context) {
    // Get the verified token from the context.
    token := jwt.GetVerifiedToken(ctx)

    // Get the custom claims from the token.
    var claims Claims
    if err := token.Claims(&claims); err != nil {
        errors.HandleError(ctx, err)
        return
    }

    // Get the user ID and username from the claims.
    userID := claims.UserID
    username := claims.Subject

    // Generate a new access token with the same user ID and username as the subject claim.
    accessClaims := Claims{
        Claims: jwt.Claims{Subject: username},
        UserID: userID,
    }
    accessToken, err := accessSigner.Sign(accessClaims)
    if err != nil {
        errors.HandleError(ctx, err)
        return
    }

    // Generate a new refresh token with the same user ID and username as the subject claim.
    refreshClaims := Claims{
        Claims: jwt.Claims{Subject: username},
        UserID: userID,
    }
    refreshToken, err := refreshSigner.Sign(refreshClaims)
    if err != nil {
        errors.HandleError(ctx, err)
        return
    }

    // Send the new tokens to the client as JSON.
    ctx.OK(iris.Map{
        "access_token":  string(accessToken),
        "refresh_token": string(refreshToken),
        "expires_in":    int64(accessExpire.Seconds()),
    }, nil)
}

Registering the handlers and testing the application

Now that we have created all our handlers, we can register them with our Iris application and test our application. We will use the app.Post method to register our login, protected, and refresh handlers with different paths. We will also use the accessVerifier.Verify method to register our verifiers as middlewares for the rest of the protected handlers.

package main

import (
    "time"

    "github.com/kataras/iris/v14"
    "github.com/kataras/iris/v14/middleware/jwt"
)

// ...

func main() {
    // Create a new Iris application.
    app := iris.New()

    // Register our login handler at /login path.
    app.Post("/login", loginHandler)

    // Register a single protected handler at /protected path.
    // This handler verifies the request manually as we've seen above.
    app.Post("/protected", protectedHandler)

    // Register our refresh handler at /refresh path with refresh signer.
    app.Post("/refresh", refreshHandler)

    // You can also register the pre-defined jwt middleware for all protected routes
    // which performs verification automatically and set the custom Claims to the Context
    // for next handlers to use through: claims, ok := jwt.Get[*Claims](ctx).
    app.Use(accessVerifier.Verify(func() any {
		return new(Claims)
	}))

    // [more routes...]

    // Start the server at http://localhost:8080.
    app.Listen(":8080")
}

To test our application, we can use a tool like curl or Postman to send HTTP requests to our server. Here are some examples of how to do that:

  • To login as Alice and get the access token and the refresh token, we can send a POST request to http://localhost:8080/login with the following JSON body:
{
    "username": "alice",
    "password": "1234"
}

We should get a response like this:

{
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MzYwNjQ3MzEsImlhdCI6MTYzNjA2MzIzMSwic3ViIjoiYWxpY2UiLCJ1c2VySWQiOjF9.8f7a7b8f7a7b8f7a7b8f7a7b8f7a7b8f7a7b8f7a7b8f7a7b8f7a7b8f",
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MzYxNTAzMzEsImlhdCI6MTYzNjA2MzIzMSwic3ViIjoiYWxpY2UiLCJ1c2VySWQiOjF9.9f8a8b9f8a8b9f8a8b9f8a8b9f8a8b9f8a8b9f8a8b9f8a8b9f8a8b9f",
    "expires_in": 900
}
Authorization: Bearer <access-token>

We should get a response like this:

{
    "user_id": 1
}
Authorization: Bearer <refresh-token>

We should get a response like this:

{
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MzYwNjQ4NTMsImlhdCI6MTYzNjA2MzM1Mywic3ViIjoiYWxpY2UiLCJ1c2VySWQiOjF9.9g7a7c9g7a7c9g7a7c9g7a7c9g7a7c9g7a7c9g7a7c9g7a7c9g7a7c9g",
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MzYxNTA0NTMsImlhdCI6MTYzNjA2MzM1Mywic3ViIjoiYWxpY2UiLCJ1c2VySWQiOjF9.aG8aBbaG8aBbaG8aBbaG8aBbaG8aBbaG8aBbaG8aBbaG8aBbaG8aBbaG",
    "expires_in": 900
}

Token Extraction Defaults (v14)

As of v14, jwt.NewVerifier reads the token from the Authorization header only. The ?token= query-parameter extractor is no longer enabled by default, because tokens in URLs leak into access logs, proxy logs, browser history and Referer headers. Opt back in only when a header cannot be set (for example browser file downloads):

verifier := jwt.NewVerifier(jwt.HS256, key).WithQueryToken()

Documentation

Overview

Package jwt signs and verifies JSON Web Tokens.

It has no single Handler entry point: NewSigner(alg, key, maxAge) issues tokens and NewVerifier(alg, key, validators...) validates them, and it is the Verifier's `Verify` method that returns the Handler. The two halves are separate objects because most applications sign in one place and verify in another.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrBlocked           = jwt.ErrBlocked
	ErrDecrypt           = jwt.ErrDecrypt
	ErrExpected          = jwt.ErrExpected
	ErrExpired           = jwt.ErrExpired
	ErrInvalidKey        = jwt.ErrInvalidKey
	ErrIssuedInTheFuture = jwt.ErrIssuedInTheFuture
	ErrMissing           = jwt.ErrMissing
	ErrMissingKey        = jwt.ErrMissingKey
	ErrNotValidYet       = jwt.ErrNotValidYet
	ErrTokenAlg          = jwt.ErrTokenAlg
	ErrTokenForm         = jwt.ErrTokenForm
	ErrTokenSignature    = jwt.ErrTokenSignature
)

Error values.

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

Signature algorithms.

View Source
var (
	MustLoadHMAC         = jwt.MustLoadHMAC
	LoadHMAC             = jwt.LoadHMAC
	MustLoadRSA          = jwt.MustLoadRSA
	LoadPrivateKeyRSA    = jwt.LoadPrivateKeyRSA
	LoadPublicKeyRSA     = jwt.LoadPublicKeyRSA
	ParsePrivateKeyRSA   = jwt.ParsePrivateKeyRSA
	ParsePublicKeyRSA    = jwt.ParsePublicKeyRSA
	MustLoadECDSA        = jwt.MustLoadECDSA
	LoadPrivateKeyECDSA  = jwt.LoadPrivateKeyECDSA
	LoadPublicKeyECDSA   = jwt.LoadPublicKeyECDSA
	ParsePrivateKeyECDSA = jwt.ParsePrivateKeyECDSA
	ParsePublicKeyECDSA  = jwt.ParsePublicKeyECDSA
	MustLoadEdDSA        = jwt.MustLoadEdDSA
	LoadPrivateKeyEdDSA  = jwt.LoadPrivateKeyEdDSA
	LoadPublicKeyEdDSA   = jwt.LoadPublicKeyEdDSA
	ParsePrivateKeyEdDSA = jwt.ParsePrivateKeyEdDSA
	ParsePublicKeyEdDSA  = jwt.ParsePublicKeyEdDSA
)

Signature algorithm helpers.

View Source
var (
	GCM = jwt.GCM
	// Helper to generate random key,
	// can be used to generate hmac signature key and GCM+AES for testing.
	MustGenerateRandom = jwt.MustGenerateRandom
)

Encryption algorithms.

View Source
var (
	// Leeway adds validation for a leeway expiration time.
	// If the token was not expired then a comparison between
	// this "leeway" and the token's "exp" one is expected to pass instead (now+leeway > exp).
	// Example of use case: disallow tokens that are going to be expired in 3 seconds from now,
	// this is useful to make sure that the token is valid when the when the user fires a database call for example.
	// Usage:
	//  verifiedToken, err := verifier.Verify(..., jwt.Leeway(5*time.Second))
	Leeway = jwt.Leeway
	// MaxAge is a SignOption to set the expiration "exp", "iat" JWT standard claims.
	// Can be passed as last input argument of the `Sign` function.
	//
	// If maxAge > second then sets expiration to the token.
	// It's a helper field to set the "exp" and "iat" claim values.
	// Usage:
	//  signer.Sign(..., jwt.MaxAge(15*time.Minute))
	MaxAge = jwt.MaxAge

	// ID is a shurtcut to set jwt ID on Sign.
	ID = func(id string) jwt.SignOptionFunc {
		return func(c *Claims) {
			c.ID = id
		}
	}
)
View Source
var (
	Verify               = jwt.Verify
	VerifyEncryptedToken = jwt.VerifyEncrypted
	Sign                 = jwt.Sign
	SignEncrypted        = jwt.SignEncrypted
)

Shortcuts for Signing and Verifying.

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.

Security note: tokens placed in the URL query string tend to leak into access logs, proxy logs, browser history and Referer headers. As of v14 FromQuery is NOT one of the default extractors; opt in explicitly with Verifier.WithQueryToken only when header-based extraction is not possible.

func Get

func Get[T any](ctx *context.Context) (T, bool)

Get returns the claims decoded by a verifier, as type T. It reports false when the request carries no claims or when they are not a T; it never panics.

The stored value is what the claims constructor passed to Verify returned, usually a pointer, so T is that pointer type:

claims, ok := jwt.Get[*UserClaims](ctx)

Types

type Alg

type Alg = jwt.Alg

Alg is the signature algorithm interface alias.

type Blocklist

type Blocklist interface {
	jwt.TokenValidator

	// InvalidateToken should invalidate a verified JWT token.
	InvalidateToken(token []byte, c Claims) error
	// Del should remove a token from the storage.
	Del(key string) error
	// Has should report whether a specific token exists in the storage.
	Has(key string) (bool, error)
	// Count should return the total amount of tokens stored.
	Count() (int64, error)
}

Blocklist should hold and manage invalidated-by-server tokens. The `jwt.NewBlocklist` and `jwt.NewBlocklistContext` functions of the github.com/kataras/jwt package return a memory storage of tokens; use the `Verifier.WithDefaultBlocklist` method to attach one.

The end-developer can implement her/his own blocklist, e.g. a redis one to keep persistence of invalidated tokens on server restarts. and bind to the JWT middleware's Blocklist field.

type Claims

type Claims = jwt.Claims

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

type ClaimsContextValidator

type ClaimsContextValidator interface {
	Validate(*context.Context) error
}

ClaimsContextValidator same as ClaimsValidator but it accepts a request context which can be used for further checks before validating the incoming token's claims.

type ClaimsValidator

type ClaimsValidator interface {
	Validate() error
}

ClaimsValidator is a special interface which, if the destination claims implements it then the verifier runs its Validate method before return.

type Expected

type Expected = jwt.Expected

Expected is a TokenValidator which performs simple checks between standard claims values.

Usage:

 expecteed := jwt.Expected{
	  Issuer: "my-app",
 }
 verifiedToken, err := verifier.Verify(..., expected)

type SignOption

type SignOption = jwt.SignOption

SignOption used to set signing options at Sign function.

type Signer

type Signer struct {
	Alg Alg
	Key any

	// MaxAge to set "exp" and "iat".
	// Recommended value for access tokens: 15 minutes.
	// Defaults to 0, no limit.
	MaxAge  time.Duration
	Options []SignOption

	Encrypt func([]byte) ([]byte, error)
}

Signer holds common options to sign and generate a token. Its Sign method can be used to generate a token which can be sent to the client. Its NewTokenPair can be used to construct a token pair (access_token, refresh_token).

It does not support JWE, JWK.

func NewSigner

func NewSigner(signatureAlg Alg, signatureKey any, maxAge time.Duration) *Signer

NewSigner accepts the signature algorithm among with its (private or shared) key and the max life time duration of generated tokens and returns a JWT signer. See its Sign method.

Usage:

signer := NewSigner(HS256, secret, 15*time.Minute)
token, err := signer.Sign(userClaims{Username: "kataras"})

func (*Signer) NewTokenPair

func (s *Signer) NewTokenPair(accessClaims any, refreshClaims any, refreshMaxAge time.Duration, accessOpts ...SignOption) (TokenPair, error)

NewTokenPair accepts the access and refresh claims plus the life time duration for the refresh token and generates a new token pair which can be sent to the client. The same token pair can be json-decoded.

func (*Signer) Sign

func (s *Signer) Sign(claims any, opts ...SignOption) ([]byte, error)

Sign generates a new token based on the given "claims" which is valid up to "s.MaxAge".

func (*Signer) WithEncryption

func (s *Signer) WithEncryption(key, additionalData []byte) *Signer

WithEncryption enables AES-GCM payload-only encryption of the signed token.

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.

type TokenPair

type TokenPair = jwt.TokenPair

TokenPair is just a helper structure which holds both access and refresh tokens.

type TokenValidator

type TokenValidator = jwt.TokenValidator

TokenValidator is the token validator interface alias.

type VerifiedToken

type VerifiedToken = jwt.VerifiedToken

VerifiedToken is the type alias for the verfieid token type, the result of the VerifyToken function.

func GetVerifiedToken

func GetVerifiedToken(ctx *context.Context) *VerifiedToken

GetVerifiedToken returns the verified token structure which holds information about the decoded token and its standard claims.

type Verifier

type Verifier struct {
	Alg Alg
	Key any

	Decrypt func([]byte) ([]byte, error)

	Extractors []TokenExtractor
	Blocklist  Blocklist
	Validators []TokenValidator

	ErrorHandler func(ctx *context.Context, err error)
	// DisableContextUser disables the registration of the claims as context User.
	DisableContextUser bool
}

Verifier holds common options to verify an incoming token. Its Verify method can be used as a middleware to allow authorized clients to access an API.

It does not support JWE, JWK.

func NewVerifier

func NewVerifier(signatureAlg Alg, signatureKey any, validators ...TokenValidator) *Verifier

NewVerifier accepts the algorithm for the token's signature among with its (public) key and optionally some token validators for all verify middlewares that may initialized under this Verifier. See its Verify method.

Usage:

verifier := NewVerifier(HS256, secret)

OR

verifier := NewVerifier(HS256, secret, Expected{Issuer: "my-app"})

claimsGetter := func() any { return new(userClaims) }
middleware := verifier.Verify(claimsGetter)

OR

middleware := verifier.Verify(claimsGetter, Expected{Issuer: "my-app"})

Register the middleware, e.g.

app.Use(middleware)

Get the claims:

claims, ok := jwt.Get[*userClaims](ctx)
if !ok {
	return // the request went through no verifier.
}
ctx.Writef("hello %s", claims.Username)

Get the context user:

username, err := ctx.User().GetUsername()

func (*Verifier) RequestToken

func (v *Verifier) RequestToken(ctx *context.Context) (token string)

RequestToken extracts the token from the request.

func (*Verifier) Verify

func (v *Verifier) Verify(claimsType func() any, validators ...TokenValidator) context.Handler

Verify is the most important piece of code inside the Verifier. It accepts the "claimsType" function which should return a pointer to a custom structure which the token's decode claims valuee will be binded and validated to. Returns a common Iris handler which can be used as a middleware to protect an API from unauthorized client requests. After this, the route handlers can access the claims through the jwt.Get package-level function.

By default it extracts the token from the Authorization: Bearer $token header only. Query-parameter (?token=) extraction is opt-in through the Verifier.WithQueryToken method, or by modifying its Extractors field.

By default a 401 status code with a generic message will be sent to the client on a token verification or claims validation failure, to change that behavior modify its ErrorHandler field and retrieve the error through Context.GetErr method.

If the "claimsType" is nil then only the jwt.GetVerifiedToken is available and the handler should unmarshal the payload to extract the claims by itself.

func (*Verifier) VerifyToken

func (v *Verifier) VerifyToken(token []byte, validators ...TokenValidator) (*VerifiedToken, error)

VerifyToken simply verifies the given "token" and validates its standard claims (such as expiration). Returns a structure which holds the token's information. See the Verify method instead.

func (*Verifier) WithDecryption

func (v *Verifier) WithDecryption(key, additionalData []byte) *Verifier

WithDecryption enables AES-GCM payload-only decryption of the incoming token.

func (*Verifier) WithDefaultBlocklist

func (v *Verifier) WithDefaultBlocklist() *Verifier

WithDefaultBlocklist attaches an in-memory blocklist storage to invalidate tokens through server-side. To invalidate a token simply call the Context.Logout method.

func (*Verifier) WithQueryToken

func (v *Verifier) WithQueryToken() *Verifier

WithQueryToken adds the query-parameter (?token=) extractor to the verifier.

As of v14 the default extractors read the Authorization header only, because tokens placed in the URL query string tend to leak into access logs, proxy logs, browser history and Referer headers. Opt back in only when you must (e.g. browser downloads that cannot set an Authorization header):

verifier := jwt.NewVerifier(jwt.HS256, key).WithQueryToken()

Directories

Path Synopsis
blocklist

Jump to

Keyboard shortcuts

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