不器小窝 不器小窝
首页
随笔
  • GoLang
  • 前端

    • Vue
    • VuePress
  • 开发工具
  • 系统工具
读吧
  • ToDb (opens new window)
  • goKit (opens new window)
  • 友情链接
  • 免费信息
  • 时间线
  • 关于
GitHub (opens new window)

不器

知行合一
首页
随笔
  • GoLang
  • 前端

    • Vue
    • VuePress
  • 开发工具
  • 系统工具
读吧
  • ToDb (opens new window)
  • goKit (opens new window)
  • 友情链接
  • 免费信息
  • 时间线
  • 关于
GitHub (opens new window)
  • GoLang

    • GoLang 安装
    • Go经验
    • 错误集合
    • 基础库

    • 第三方库

    • Fyne

    • Wails

    • GoFrame

      • Hello GoFrame
      • GoFrame 路由
      • GoFrame问题集合
      • GoFrame使用jwt
        • 下载和导入
          • 下载和安装
          • 导入
        • 创建中间件文件
          • 新建一个jwt.go文件
          • 新建userMiddleware.go
          • 路由配置
        • 使用
          • 登陆
          • 获取用户id
        • 验证
          • 如何使用Token
  • Dart

  • Markdown

  • 语言
  • GoLang
  • GoFrame
不器
2022-12-26
目录

GoFrame使用jwt

公司要进行前后端分离,事情这玩意永远都是嘴上说的容易的狠,撸代码的人就鸡飞狗跳的。原本就是使用的GoFrame这个框架,所以直接使用它的生态吧,使用起来更容易。

# 下载和导入

# 下载和安装

go get github.com/gogf/gf-jwt/v2
1

# 导入

import "github.com/gogf/gf-jwt/v2"
1

# 创建中间件文件

# 新建一个jwt.go文件

点击查看详细代码
package middleware

import (
	"context"
	"errors"
	jwt "github.com/gogf/gf-jwt/v2"
	"github.com/gogf/gf/v2/frame/g"
	"juliang-gf/internal/consts"
	"juliang-gf/internal/controller/params"
	"juliang-gf/internal/logic"
	"juliang-gf/internal/model/entity"
	"time"
)

var authService *jwt.GfJWTMiddleware

func Auth() *jwt.GfJWTMiddleware {
	return authService
}

func init() {
	auth := jwt.New(&jwt.GfJWTMiddleware{
		Realm:           "juliang",                                          // 用于展示中间件的名称
		Key:             []byte("secret key"),                               // token过期时间密钥
		Timeout:         time.Minute * 60,                                   // token过期时间
		MaxRefresh:      time.Minute * 60,                                   // token过期时间
		IdentityKey:     "id",                                               // 身份验证的key值
		TokenLookup:     "header: Authorization, query: token, cookie: jwt", // token检索模式,用于提取token-> Authorization
		TokenHeadName:   "Bearer",                                           // token在请求头时的名称,默认值为Bearer;// 客户端在header中传入Authorization 对一个值是Bearer + 空格 + token
		TimeFunc:        time.Now,                                           // 测试或服务器在其他时区可设置该属性
		Authenticator:   Authenticator,                                      // 根据登录信息对用户进行身份验证的回调函数
		Unauthorized:    Unauthorized,                                       // 处理不进行授权的逻辑
		PayloadFunc:     PayloadFunc,                                        // 登录期间的回调的函数
		IdentityHandler: IdentityHandler,                                    // 解析并设置用户身份信息
	})
	authService = auth
}

// PayloadFunc is a callback function that will be called during login.
// Using this function it is possible to add additional payload data to the webtoken.
// The data is then made available during requests via c.Get("JWT_PAYLOAD").
// Note that the payload is not encrypted.
// The attributes mentioned on jwt.io can't be used as keys for the map.
// Optional, by default no additional data will be set.
func PayloadFunc(data interface{}) jwt.MapClaims {
	claims := jwt.MapClaims{}
	params := data.(map[string]interface{})
	if len(params) > 0 {
		for k, v := range params {
			claims[k] = v
		}
	}
	return claims
}

// IdentityHandler get the identity from JWT and set the identity for every request
// Using this function, by r.GetParam("id") get identity
func IdentityHandler(ctx context.Context) interface{} {
	claims := jwt.ExtractClaims(ctx)
	return claims[authService.IdentityKey]
}

// Unauthorized is used to define customized Unauthorized callback function.
func Unauthorized(ctx context.Context, code int, message string) {
	r := g.RequestFromCtx(ctx)
	r.Response.WriteJson(g.Map{
		"code":    code,
		"message": message,
	})
	r.ExitAll()
}

// Authenticator is used to validate login parameters.
// It must return user data as user identifier, it will be stored in Claim Array.
// if your identityKey is 'id', your user data must have 'id'
// Check error (e) to determine the appropriate error message.
// 此方法用于验证账户密码是否正确,基于自己的代码嵌套即可
func Authenticator(ctx context.Context) (interface{}, error) {
	var (
		r  = g.RequestFromCtx(ctx)
		in params.LoginInUPReq
	)
	if err := r.Parse(&in); err != nil {
		return "", err
	}

	ret := logic.UPLogin(ctx, in.UserName, in.Password)
	if ret.Code == consts.CODE_OK {
		info, isOk := (ret.Data).(*entity.Users)
		if !isOk {
			return nil, errors.New("类型转换异常")
		}
		infoMap := map[string]interface{}{
			"id": info.Id,
		}

		return infoMap, nil
	}

	return nil, jwt.ErrFailedAuthentication
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102

# 新建userMiddleware.go

点击查看详细代码
import "github.com/gogf/gf/v2/net/ghttp"

type middlewareService struct{}

var middleware = middlewareService{}

func Middleware() *middlewareService {
	return &middleware
}

func (s *middlewareService) CORS(r *ghttp.Request) {
	r.Response.CORSDefault()
	r.Middleware.Next()
}

func (s *middlewareService) Auth(r *ghttp.Request) {
	Auth().MiddlewareFunc()(r)
	r.Middleware.Next()
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 路由配置

group.Middleware(middleware.Middleware().Auth)
1

# 使用

# 登陆

token, expire := middleware.Auth().LoginHandler(r.Context())
1

# 获取用户id

middleware.Auth().GetIdentity(r.Context())
1

# 验证

# 如何使用Token

Bearer来自jwt.go文件中init方法中的GfJWTMiddleware结构体中的TokenHeadName数据

请求的Headers中携带Authorization参数,参数值为Bearer+空格+Token

#GoFrame#jwt
更新时间: 2023/2/10 09:50:10
GoFrame问题集合
Dart基础

← GoFrame问题集合 Dart基础→

最近更新
01
Vue-pure-Admin基础
03-16
02
WebStorm工具使用手册
03-15
03
Windows
03-12
更多文章>
Theme by Vdoing | Copyright © 2022-2023 不器 | 小窝
sitemap icon by Icons8
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式