jwt

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2021 License: GPL-3.0 Imports: 10 Imported by: 0

README

jwt Go Reference

JWT Helper

Usage

go get -u github.com/ClavinJune/jwt@latest

Example

package main

import (
	"crypto/rand"
	"crypto/rsa"
	"fmt"
	"time"

	"github.com/ClavinJune/jwt"
)

func main() {
	key, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		panic(err)
	}

	j := jwt.JWT{
		Header: jwt.Header{
			Alg: jwt.HeaderAlgRS256,
			Typ: jwt.HeaderTypJWT,
		},
		Claims: jwt.Claims{
			RegisteredClaims: jwt.RegisteredClaims{
				Iss: "issuer",
				Sub: "subject",
				Aud: []string{"aud1", "aud2"},
				Exp: time.Now().Add(time.Hour),
				Iat: time.Now(),
			},
			ExtraClaims: map[string]interface{}{
				"user": "ehe",
			},
		},
	}

	token, err := j.Sign(key)
	if err != nil {
		panic(err)
	}

	fmt.Println(token)

	if err := jwt.Verify(&key.PublicKey, token) ; err != nil {
		panic(err)
	}

	fmt.Println("token verified")
}

Documentation

Index

Constants

View Source
const (
	HeaderAlgRS256 HeaderAlg = "RS256"

	HeaderTypJWT HeaderTyp = "JWT"
)

Variables

View Source
var (
	ErrEncodingFailed  = errors.New("jwt: failed to encode jwt")
	ErrDecodingFailed  = errors.New("jwt: failed to decode base64")
	ErrSigningFailed   = errors.New("jwt: failed to sign jwt")
	ErrVerifyingFailed = errors.New("jwt: failed to verify token")
)

Functions

func Verify

func Verify(key *rsa.PublicKey, token string) error

Types

type Claims

type Claims struct {
	RegisteredClaims
	ExtraClaims map[string]interface{}
}

Claims stores RegisteredClaims and ExtraClaims

func ClaimsFrom

func ClaimsFrom(token string) (*Claims, error)

ClaimsFrom construct Claims from encoded token

func (Claims) Encode

func (c Claims) Encode() (string, error)

Encode returns Header in encoded string form

type Header struct {
	Alg HeaderAlg `json:"alg,omitempty"`
	Typ HeaderTyp `json:"typ,omitempty"`
}

Header stores header component of JWT

func HeaderFrom

func HeaderFrom(token string) (*Header, error)

HeaderFrom construct Header from encoded token

func (*Header) Encode

func (h *Header) Encode() (string, error)

Encode returns Header in encoded string form

type HeaderAlg

type HeaderAlg string

HeaderAlg stores algorithm of the jwt

type HeaderTyp

type HeaderTyp string

HeaderTyp stores type of the jwt, which is JWT

type JWT

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

func From

func From(key *rsa.PublicKey, token string) (*JWT, error)

func (*JWT) Sign

func (j *JWT) Sign(key *rsa.PrivateKey) (string, error)

type RegisteredClaims

type RegisteredClaims struct {
	Iss string
	Sub string
	Aud []string
	Exp time.Time
	Iat time.Time
}

RegisteredClaims stores standard claims of JWT

Jump to

Keyboard shortcuts

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