使用JWT做RESTful API的身份驗(yàn)證-Go語(yǔ)言實(shí)現(xiàn)

使用JWT做RESTful API的身份驗(yàn)證-Go語(yǔ)言實(shí)現(xiàn)

使用Golang和MongoDB構(gòu)建 RESTful API已經(jīng)實(shí)現(xiàn)了一個(gè)簡(jiǎn)單的 RESTful API應(yīng)用,但是對(duì)于有些API接口需要授權(quán)之后才能訪問(wèn),在這篇文章中就用 jwt 做一個(gè)基于Token的身份驗(yàn)證,關(guān)于 jwt 請(qǐng)?jiān)L問(wèn) JWT有詳細(xì)的說(shuō)明,而且有各個(gè)語(yǔ)言實(shí)現(xiàn)的庫(kù),請(qǐng)根據(jù)需要使用對(duì)應(yīng)的版本。

image

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

新增注冊(cè)登錄接口,并在登錄時(shí)生成token

  • 自定義返回結(jié)果,并封裝 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(),// 可以添加過(guò)期時(shí)間
    })

    return token.SignedString([]byte("secret"))//對(duì)應(yīng)的字符串請(qǐng)自行生成,最后足夠使用加密后的字符串
}

http中間件

go http的中間件實(shí)現(xiàn)起來(lái)很簡(jiǎn)單,只需要實(shí)現(xiàn)一個(gè)函數(shù)簽名為func(http.Handler) http.Handler的函數(shù)即可。

func middlewareHandler(next http.Handler) http.Handler{
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
        // 執(zhí)行handler之前的邏輯
        next.ServeHTTP(w, r)
        // 執(zhí)行完畢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)
    //如果這個(gè)路由有中間件的邏輯,需要通過(guò)中間件先處理一下
        if route.Middleware != nil {
            r.Handler(route.Middleware(route.Handler))
        } else {
            r.Handler(route.Handler)
        }
    }
    return router
}

實(shí)現(xiàn)身份驗(yàn)證的中間件

auth/middleware.go

驗(yàn)證的信息放在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)
            }
        }
    })
}

對(duì)需要驗(yàn)證的路由添加中間件

register("GET", "/movies", controllers.AllMovies, auth.TokenMiddleware) //需要中間件邏輯
register("GET", "/movies/{id}", controllers.FindMovie, nil)//不需要中間件

驗(yàn)證

  • 登錄之后,返回對(duì)應(yīng)的token信息
//請(qǐng)求 post http://127.0.0.1:8080/login
//返回

{
    "code": 200,
    "msg": "",
    "data": {
        "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImNvZGVybWluZXIifQ.pFzJLU8vnzWiweFKzHRsawyWA2jfuDIPlDU4zE92O7c"
    }
}
  • 獲取所有的電影信息時(shí)
//請(qǐng)求 post http://127.0.0.1:8080/movies
在 Header中設(shè)置 "authorization":token
如果沒有設(shè)置header會(huì)報(bào) 401 錯(cuò)誤

{
    "code": 401,
    "msg": "not authorized",
    "data": null
}

源碼 Github

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容