50

JWT在Gin中的使用

 4 years ago
source link: https://www.tuicool.com/articles/b6Z3Mfa
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

LearnJWT in Gin for Go

介绍

JSON Web Token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该 Token 被设计为紧凑且安全的,特别适用于分布式站点的单点登录(SSO)场景。JWT 的声明一般被用来在身份提供者和服务提供者间传递被认证的用户身份信息,以便于从资源服务器获取资源,也可以增加一些额外的其它业务逻辑所必须的声明信息,该 Token 也可直接被用于认证,也可被加密。

安装

使用

1. import "github.com/dgrijalva/jwt-go"
2. import "github.com/appleboy/gin-jwt"

使用jwt-go,可操作性更好一点,参考文档: https://godoc.org/github.com/...

编写JWT工具包

1. 定义Claims结构体

2.定义方法:GenerateToken(username, password string) (string error){}, ParseToken(token string) (*Claims, error){}

3.编写middleware下的jwt
    JWT() gin.HandlerFunc{}

如何获取token

1.在models里面定义认证模型以及验证的方法
2.在apis里面编写获取用户认证信息并生成token的方法,

验证token

调用相应的api,看是否返回token成功

将中间件接入Gin

在router.go里面通过apiv1.Use(jwt.JWT()),使用中间件

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK