分享
  1. 首页
  2. 文章

使用JWT做RESTful API的身份验证-Go语言实现

CoderMiner · · 2272 次点击 · · 开始浏览
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

使用JWT做RESTful API的身份验证-Go语言实现

使用Golang和MongoDB构建 RESTful API已经实现了一个简单的 RESTful API应用,但是对于有些API接口需要授权之后才能访问,在这篇文章中就用 jwt 做一个基于Token的身份验证,关于 jwt 请访问 JWT有详细的说明,而且有各个语言实现的库,请根据需要使用对应的版本。

image

需要先安装 jwt-go 接口 go get github.com/dgrijalva/jwt-go

新增注册登录接口,并在登录时生成token

  • 自定义返回结果,并封装 helper/utils.go
type Response struct {
 Code int `json:"code"`
 Msg string `json:"msg"`
 Data interface{} `json:"data"`
}
func ResponseWithJson(w http.ResponseWriter, code int, payload interface{}) {
 response, _ := json.Marshal(payload)
 w.Header().Set("Content-Type", "application/json")
 w.WriteHeader(code)
 w.Write(response)
}
  • 模型 models/user.go
type User struct {
 UserName string `bson:"username" json:"username"`
 Password string `bson:"password" json:"password"`
}
type JwtToken struct {
 Token string `json:"token"`
}
  • 控制器 controllers/user.go
func Register(w http.ResponseWriter, r *http.Request) {
 var user models.User
 err := json.NewDecoder(r.Body).Decode(&user)
 if err != nil || user.UserName == "" || user.Password == "" {
 helper.ResponseWithJson(w, http.StatusBadRequest,
 helper.Response{Code: http.StatusBadRequest, Msg: "bad params"})
 return
 }
 err = models.Insert(db, collection, user)
 if err != nil {
 helper.ResponseWithJson(w, http.StatusInternalServerError,
 helper.Response{Code: http.StatusInternalServerError, Msg: "internal error"})
 }
}
func Login(w http.ResponseWriter, r *http.Request) {
 var user models.User
 err := json.NewDecoder(r.Body).Decode(&user)
 if err != nil {
 helper.ResponseWithJson(w, http.StatusBadRequest,
 helper.Response{Code: http.StatusBadRequest, Msg: "bad params"})
 }
 exist := models.IsExist(db, collection, bson.M{"username": user.UserName})
 if exist {
 token, _ := auth.GenerateToken(&user)
 helper.ResponseWithJson(w, http.StatusOK,
 helper.Response{Code: http.StatusOK, Data: models.JwtToken{Token: token}})
 } else {
 helper.ResponseWithJson(w, http.StatusNotFound,
 helper.Response{Code: http.StatusNotFound, Msg: "the user not exist"})
 }
}
  • 生成Token auth/middleware.go
func GenerateToken(user *models.User) (string, error) {
 token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
 "username": user.UserName,
 //"exp": time.Now().Add(time.Hour * 2).Unix(),// 可以添加过期时间
 })
 return token.SignedString([]byte("secret"))//对应的字符串请自行生成,最后足够使用加密后的字符串
}

http中间件

go http的中间件实现起来很简单,只需要实现一个函数签名为func(http.Handler) http.Handler的函数即可。

func middlewareHandler(next http.Handler) http.Handler{
 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
 // 执行handler之前的逻辑
 next.ServeHTTP(w, r)
 // 执行完毕handler后的逻辑
 })
}

我们使用的 mux 作为路由,本身支持在路由中添加中间件,改造一下之前的路由逻辑

routes/routes.go

type Route struct {
 Method string
 Pattern string
 Handler http.HandlerFunc
 Middleware mux.MiddlewareFunc //添加中间件
}
func NewRouter() *mux.Router {
 router := mux.NewRouter()
 for _, route := range routes {
 r := router.Methods(route.Method).
 Path(route.Pattern)
 //如果这个路由有中间件的逻辑,需要通过中间件先处理一下
 if route.Middleware != nil {
 r.Handler(route.Middleware(route.Handler))
 } else {
 r.Handler(route.Handler)
 }
 }
 return router
}

实现身份验证的中间件

auth/middleware.go

验证的信息放在http Header

func TokenMiddleware(next http.Handler) http.Handler {
 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 tokenStr := r.Header.Get("authorization")
 if tokenStr == "" {
 helper.ResponseWithJson(w, http.StatusUnauthorized,
 helper.Response{Code: http.StatusUnauthorized, Msg: "not authorized"})
 } else {
 token, _ := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
 if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
 helper.ResponseWithJson(w, http.StatusUnauthorized,
 helper.Response{Code: http.StatusUnauthorized, Msg: "not authorized"})
 return nil, fmt.Errorf("not authorization")
 }
 return []byte("secret"), nil
 })
 if !token.Valid {
 helper.ResponseWithJson(w, http.StatusUnauthorized,
 helper.Response{Code: http.StatusUnauthorized, Msg: "not authorized"})
 } else {
 next.ServeHTTP(w, r)
 }
 }
 })
}

对需要验证的路由添加中间件

register("GET", "/movies", controllers.AllMovies, auth.TokenMiddleware) //需要中间件逻辑
register("GET", "/movies/{id}", controllers.FindMovie, nil)//不需要中间件

验证

  • 登录之后,返回对应的token信息
//请求 post http://127.0.0.1:8080/login
//返回
{
 "code": 200,
 "msg": "",
 "data": {
 "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImNvZGVybWluZXIifQ.pFzJLU8vnzWiweFKzHRsawyWA2jfuDIPlDU4zE92O7c"
 }
}
  • 获取所有的电影信息时
//请求 post http://127.0.0.1:8080/movies
在 Header中设置 "authorization":token
如果没有设置header会报 401 错误
{
 "code": 401,
 "msg": "not authorized",
 "data": null
}

源码 Github


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:CoderMiner

查看原文:使用JWT做RESTful API的身份验证-Go语言实现

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
2272 次点击
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)

给该专栏投稿 写篇新文章

每篇文章有总共有 5 次投稿机会

收入到我管理的专栏 新建专栏