paseto

package module
v0.0.0-...-71af663 Latest Latest
Warning

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

Go to latest
Published: May 8, 2023 License: Apache-2.0 Imports: 10 Imported by: 3

README

PASETO (This is a community driven project)

Paseto is everything you love about JOSE (JWT, JWE, JWS) without any of the many design deficits that plague the JOSE standards.

This is the PASETO middleware for Hertz framework.

Usage

Install

go get github.com/hertz-contrib/paseto

Import

import "github.com/hertz-contrib/paseto"

Example

package main

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/app/client"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"github.com/cloudwego/hertz/pkg/protocol"
	"github.com/hertz-contrib/paseto"
)

func performRequest() {
	time.Sleep(time.Second)
	c, _ := client.NewClient()
	req, resp := protocol.AcquireRequest(), protocol.AcquireResponse()
	req.SetRequestURI("http://127.0.0.1:8080/paseto")

	req.SetMethod("GET")
	_ = c.Do(context.Background(), req, resp)
	fmt.Printf("get token: %s\n", resp.Body())

	req.SetMethod("POST")
	req.SetHeader("Authorization", string(resp.Body()))
	_ = c.Do(context.Background(), req, resp)
	fmt.Printf("Authorization response :%s", resp.Body())
}

func main() {
	h := server.New(server.WithHostPorts(":8080"))
	h.GET("/paseto", func(c context.Context, ctx *app.RequestContext) {
		now := time.Now()
		genTokenFunc := paseto.DefaultGenTokenFunc()
		token, err := genTokenFunc(&paseto.StandardClaims{
			Issuer:    "cwg-issuer",
			ExpiredAt: now.Add(time.Hour),
			NotBefore: now,
			IssuedAt:  now,
		}, nil, nil)
		if err != nil {
			hlog.Error("generate token failed")
		}
		ctx.String(http.StatusOK, token)
	})

	h.POST("/paseto", paseto.New(), func(c context.Context, ctx *app.RequestContext) {
		ctx.String(http.StatusOK, "token is valid")
	})

	go performRequest()

	h.Spin()
}

Options

Option Default Description
Next nil Next defines a function to skip this middleware when returned true.
ErrorFunc output log and response 401 ErrorFunc defines a function which is executed when an error occurs.
SuccessHandler save the claims to app.RequestContext SuccessHandler defines a function which is executed when the token is valid.
KeyLookup "header:Authorization" KeyLookup is a string in the form of ":" that is used to create an Extractor that extracts the token from the request.
TokenPrefix "" TokenPrefix is a string that holds the prefix for the token lookup.
ParseFunc parse V4 Public Token ParseFunc parse and verify token.

Version comparison

Version Local Public
v1 Encrypted with AES-256-CBC and signed with HMAC-SHA-256 Signed with RSA-SHA-256
v2 Encrypted with XSalsa20Poly1305 and signed with HMAC-SHA-384 Signed with EdDSA (Ed25519)
v3 Encrypted with XChaCha20Poly1305 and signed with HMAC-SHA-384 Signed with EdDSA (Ed25519)
v4 Encrypted with XChaCha20Poly1305 and signed with HMAC-SHA-512-256 Signed with EdDSA (Ed448)

Documentation

Index

Constants

View Source
const (
	DefaultContextKey   = "paseto"
	DefaultSymmetricKey = "707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f"
	DefaultPublicKey    = "1eb9dbbbbc047c03fd70604e0071f0987e16b28b757225c11f00415d0e20b1a2"
	DefaultPrivateKey   = "" /* 128-byte string literal not displayed */
	DefaultImplicit     = "paseto-implicit"
)

Variables

View Source
var DefaultOptions = Options{
	Next: nil,
	ErrorHandler: func(ctx context.Context, c *app.RequestContext) {
		hlog.Error("PASTO: ", c.Errors.Last())
		c.String(consts.StatusUnauthorized, "authorization failed")
		c.Abort()
	},
	SuccessHandler: func(ctx context.Context, c *app.RequestContext, token *paseto.Token) {
		c.Set(DefaultContextKey, *token)
	},
	KeyLookup: "header:Authorization",
	ParseFunc: DefaultParseFunc(),
}

DefaultOptions is the default options.

Functions

func New

func New(opts ...Option) app.HandlerFunc

New returns a paseto middleware.

Types

type Extractor

type Extractor func(c *app.RequestContext) (string, error)

Extractor defines the function to get token from app.Request Context

func NewExtractor

func NewExtractor(keyLookup string) (Extractor, error)

NewExtractor creates an Extractor based on keyLookup.

func TokenFromCookie

func TokenFromCookie(key string) Extractor

TokenFromCookie returns a function that extracts token from the request header.

func TokenFromForm

func TokenFromForm(key string) Extractor

TokenFromForm returns a function that extracts a token from a multipart-form.

func TokenFromHeader

func TokenFromHeader(key string) Extractor

TokenFromHeader returns a function that extracts token from the request header.

func TokenFromParams

func TokenFromParams(param string) Extractor

TokenFromParams returns a function that extracts token from the url param string.

func TokenFromQuery

func TokenFromQuery(key string) Extractor

TokenFromQuery returns a function that extracts token from the query string.

type GenTokenFunc

type GenTokenFunc func(stdClaims *StandardClaims, customClaims utils.H, footer []byte) (token string, err error)

GenTokenFunc defines the function which generates token.

func DefaultGenTokenFunc

func DefaultGenTokenFunc() GenTokenFunc

DefaultGenTokenFunc returns default GenTokenFunc which creates v4 public paseto.

func NewV2EncryptFunc

func NewV2EncryptFunc(symmetricKey string) (GenTokenFunc, error)

NewV2EncryptFunc returns a GenTokenFunc which generates v2 local paseto.

func NewV2SignFunc

func NewV2SignFunc(asymmetricKey string) (GenTokenFunc, error)

NewV2SignFunc returns a GenTokenFunc which generates v2 public paseto.

func NewV3EncryptFunc

func NewV3EncryptFunc(symmetricKey string, implicit []byte) (GenTokenFunc, error)

NewV3EncryptFunc returns a GenTokenFunc which generates v3 local paseto.

func NewV3SignFunc

func NewV3SignFunc(asymmetricKey string, implicit []byte) (GenTokenFunc, error)

NewV3SignFunc returns a GenTokenFunc which generates v3 public paseto.

func NewV4EncryptFunc

func NewV4EncryptFunc(symmetricKey string, implicit []byte) (GenTokenFunc, error)

NewV4EncryptFunc returns a GenTokenFunc which generates v4 local paseto.

func NewV4SignFunc

func NewV4SignFunc(asymmetricKey string, implicit []byte) (GenTokenFunc, error)

NewV4SignFunc returns a GenTokenFunc which generates v4 public paseto.

type NextHandler

type NextHandler func(ctx context.Context, c *app.RequestContext) bool

type Option

type Option struct {
	F func(o *Options)
}

Option is the only struct that can be used to set Options.

func WithErrorFunc

func WithErrorFunc(f app.HandlerFunc) Option

WithErrorFunc sets ErrorFunc.

func WithKeyLookUp

func WithKeyLookUp(lookup string) Option

WithKeyLookUp sets a string in the form of "<source>:<key>" that is used to create an Extractor that extracts the token from the request.

func WithNext

func WithNext(f NextHandler) Option

WithNext sets a function to judge whether to skip this middleware.

func WithParseFunc

func WithParseFunc(f ParseFunc) Option

WithParseFunc sets the ParseFunc.

func WithSuccessHandler

func WithSuccessHandler(f SuccessHandler) Option

WithSuccessHandler sets the logic to handle the Parsed token.

func WithTokenPrefix

func WithTokenPrefix(tokenPrefix string) Option

WithTokenPrefix sets the tokenPrefix.

type Options

type Options struct {
	// Next defines a function to skip middleware.
	// Optional.Default: nil
	Next NextHandler

	// ErrorHandler defines a function which is executed when an error occurs.
	// It may be used to define a custom PASETO error.
	// Optional. Default: OutPut log and response 401.
	ErrorHandler app.HandlerFunc

	// SuccessHandler handle the Parsed token.
	// Optional.Default: Save the claims to app.RequestContext.
	SuccessHandler SuccessHandler

	// KeyLookup is a string in the form of "<source>:<key>" that is used
	// to create an Extractor that extracts the token from the request.
	// Optional. Default: "header:Authorization"
	// Possible values:
	// - "header:<name>"
	// - "query:<name>"
	// - "param:<name>"
	// - "form:<name>"
	// - "cookie:<name>"
	KeyLookup string

	// TokenPrefix is a string that holds the prefix for the token lookup.
	// Optional. Default value ""
	// Recommended value: "Bearer "
	TokenPrefix string

	// ParseFunc parse and verify token.
	ParseFunc ParseFunc
}

Options defines the config for middleware.

func NewOptions

func NewOptions(opts ...Option) *Options

func (*Options) Apply

func (o *Options) Apply(opts []Option)

type ParseFunc

type ParseFunc func(token string) (*paseto.Token, error)

ParseFunc parse and verify paseto and validate against any parser rules. Error if parsing, verification, or any rule fails.

func DefaultParseFunc

func DefaultParseFunc() ParseFunc

DefaultParseFunc returns a default ParseFunc(V4 Public).

func NewV2LocalParseFunc

func NewV2LocalParseFunc(symmetricKey string, options ...ParseOption) (ParseFunc, error)

NewV2LocalParseFunc will return a function which parse and valid v2 local paseto.

func NewV2PublicParseFunc

func NewV2PublicParseFunc(asymmetricPubKey string, options ...ParseOption) (ParseFunc, error)

NewV2PublicParseFunc will return a function which parse and valid v2 public paseto.

func NewV3LocalParseFunc

func NewV3LocalParseFunc(symmetricPubKey string, implicit []byte, options ...ParseOption) (ParseFunc, error)

NewV3LocalParseFunc will return a function which parse and valid v3 local paseto.

func NewV3PublicParseFunc

func NewV3PublicParseFunc(asymmetricPubKey string, implicit []byte, options ...ParseOption) (ParseFunc, error)

NewV3PublicParseFunc will return a function which parse and valid v3 public paseto.

func NewV4LocalParseFunc

func NewV4LocalParseFunc(symmetricPubKey string, implicit []byte, options ...ParseOption) (ParseFunc, error)

NewV4LocalParseFunc will return a function which parse and valid v4 local paseto.

func NewV4PublicParseFunc

func NewV4PublicParseFunc(asymmetricPubKey string, implicit []byte, options ...ParseOption) (ParseFunc, error)

NewV4PublicParseFunc will return a function which parse and valid v4 public paseto.

type ParseOption

type ParseOption func(ps *paseto.Parser)

ParseOption is the only struct that can be used to add rule to ParseFunc.

func WithAudience

func WithAudience(audience string) ParseOption

WithAudience requires that the given audience matches the "aud" field of the token.

func WithIdentifier

func WithIdentifier(identifier string) ParseOption

WithIdentifier requires that the given identifier matches the "jti" field of the token.

func WithIssuer

func WithIssuer(issuer string) ParseOption

WithIssuer requires that the given issuer matches the "iss" field of the token.

func WithNotBefore

func WithNotBefore() ParseOption

WithNotBefore requires that the token is allowed to be used according to the time when this rule is checked and the "nbf" field of a token. Beware that this rule does not validate the token's "iat" or "exp" fields, or even require their presence.

func WithSubject

func WithSubject(subject string) ParseOption

WithSubject requires that the given subject matches the "sub" field of the token.

func WithValidAt

func WithValidAt(time time.Time) ParseOption

WithValidAt requires that the token has not expired according to the given time and the "exp" field, and that the given time is both after the token's issued at time "iat", and the token's not before time "nbf".

type StandardClaims

type StandardClaims struct {
	Issuer    string
	Subject   string
	Audience  string
	Jti       string
	ID        string
	ExpiredAt time.Time
	NotBefore time.Time
	IssuedAt  time.Time
}

type SuccessHandler

type SuccessHandler func(ctx context.Context, c *app.RequestContext, token *paseto.Token)

Jump to

Keyboard shortcuts

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