jwt

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jan 1, 2020 License: Apache-2.0 Imports: 8 Imported by: 0

README

elton-jwt

JWT middleware for elton.

package main

import (
	"net/http"
	"time"

	"github.com/vicanso/elton"
	jwt "github.com/vicanso/elton-jwt"
	responder "github.com/vicanso/elton-responder"
)

func main() {
	e := elton.New()
	jwtCookie := "jwt"
	e.Use(responder.NewDefault())

	ttlToken := &jwt.TTLToken{
		TTL: 24 * time.Hour,
		// 密钥用于加密数据,需保密
		Secret: []byte("my secret"),
	}

	// Passthrough为false,会校验token是否正确
	jwtNormal := jwt.NewJWT(jwt.Config{
		CookieName: jwtCookie,
		Decode:     ttlToken.Decode,
	})
	// 用于初始化创建token使用(此时可能token还没有或者已过期)
	jwtPassthrough := jwt.NewJWT(jwt.Config{
		CookieName:  jwtCookie,
		Decode:      ttlToken.Decode,
		Passthrough: true,
	})

	e.GET("/login", jwtPassthrough, func(c *elton.Context) (err error) {
		// 模拟登录成功后获取用户信息
		data, err := ttlToken.Encode(`{"account":"tree.xie"}`)
		if err != nil {
			return
		}
		// 将相关信息写入cookie
		err = c.AddCookie(&http.Cookie{
			Name:  jwtCookie,
			Value: data,
		})
		if err != nil {
			return
		}
		c.Body = map[string]string{
			"token": data,
		}
		return
	})

	e.GET("/", jwtNormal, func(c *elton.Context) (err error) {
		// 获取相应的用户信息
		userInfo := c.Get(jwt.DefaultKey).(string)
		c.Body = userInfo
		return
	})
	err := e.ListenAndServe(":3000")
	if err != nil {
		panic(err)
	}
}

Documentation

Index

Constants

View Source
const (
	// DefaultKey default key for data
	DefaultKey = "user"
)

Variables

View Source
var (
	// ErrTokenNotFound err token not found
	ErrTokenNotFound = &hes.Error{
		Message:    "Token not found",
		StatusCode: http.StatusUnauthorized,
	}
	// ErrTokenIsInvalid err token is invalid
	ErrTokenIsInvalid = &hes.Error{
		Message:    "Token is invalid",
		StatusCode: http.StatusUnauthorized,
	}
)

Functions

func NewJWT

func NewJWT(config Config) elton.Handler

NewJWT new jwt middleware

Types

type Config

type Config struct {
	Key string
	// CookieName cookie for token
	CookieName string
	Skipper    elton.Skipper
	// Passthrough passthrough when token not found
	Passthrough bool
	// Decode decode
	Decode Decode
}

Config jwt config

type Decode

type Decode func(data string) (string, error)

Decode decode function

type TTLToken

type TTLToken struct {
	TTL    time.Duration
	Secret []byte
}

TTLToken normal token

func (*TTLToken) Decode

func (t *TTLToken) Decode(tokenString string) (data string, err error)

Decode ttl token decode

func (*TTLToken) Encode

func (t *TTLToken) Encode(data string) (tokenString string, err error)

Encode ttl token encode

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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