使用JWT作RESTful API的身份驗證-Go語言實現

使用JWT作RESTful API的身份驗證-Go語言實現

使用Golang和MongoDB構建 RESTful API已經實現了一個簡單的 RESTful API應用,可是對於有些API接口須要受權以後才能訪問,在這篇文章中就用 jwt 作一個基於Token的身份驗證,關於 jwt 請訪問 JWT有詳細的說明,並且有各個語言實現的庫,請根據須要使用對應的版本。git

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

新增註冊登陸接口,並在登陸時生成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的函數便可。json

func middlewareHandler(next http.Handler) http.Handler{
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
        // 執行handler以前的邏輯
        next.ServeHTTP(w, r)
        // 執行完畢handler後的邏輯
    })
}

複製代碼

咱們使用的 mux 做爲路由,自己支持在路由中添加中間件,改造一下以前的路由邏輯bash

routes/routes.gorestful

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
}
複製代碼

實現身份驗證的中間件app

auth/middleware.go函數

驗證的信息放在http Headerpost

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)
			}
		}
	})
}
複製代碼

對須要驗證的路由添加中間件ui

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加密

相關文章
相關標籤/搜索