jwt

package
v0.0.0-...-04c1826 Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2020 License: MIT Imports: 4 Imported by: 0

README

JWT封装

参考:

feature

  • JWT-Token的生成和解析
  • 解析错误类型分类
  • 适用于 gin 的中间件封装(见valyria/middleware/jwt.go
  • 续签

usage

基本使用

package main

import (
	"fmt"
	"github.com/strconv/valyria/jwt"
)

func main() {
	// 生成
	token, _ := jwt.GenToken(1000005)
	
	// 解析
	c, err := jwt.ParseToken(token)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(c.UID)
}

中间件

对 gin 中每个需要JWT认证的接口做鉴权

account := s.Group("/user/info")
// 在这里添加中间件
account.Use(middleware.JWTAuth()) // JWT
{
    account.GET("/get", userInfo.Get)
    account.POST("/update", userInfo.Update)
}

需要注意的是

  • 如果用 valyria ,需要在配置文件内加上JWT相关配置
      jwt:
        secret: "welcome to ariser.cn"
        timeOut: 120 # 分钟
    

TODO

  • JWT自定义参数
  • timeoutsecret 作为参数传入

Documentation

Index

Constants

View Source
const HEADER_TOKEN_KEY = "X-Token" // http请求体内的token

参考 https://www.liwenzhou.com/posts/Go/jwt_in_gin/

Variables

View Source
var (
	TokenExpired     = errors.New("token expired")
	TokenNotValidYet = errors.New("token not valid yet")
	TokenMalformed   = errors.New("token malformed")
	TokenInvalid     = errors.New("invalid token")
	Secret           = []byte(config.C.JWT.Secret)
)

Functions

func GenToken

func GenToken(uid int64) (string, error)

Types

type Claims

type Claims struct {
	UID int64 // 这里根据需要修改类型,考虑改为interface{}
	jwt.StandardClaims
}

func ParseToken

func ParseToken(tokenStr string) (*Claims, error)

Jump to

Keyboard shortcuts

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