在 使用Golang和MongoDB构建 RESTful API已经实现了一个简单的 RESTful API应用,可是对于有些API接口须要受权以后才能访问,在这篇文章中就用 jwt
作一个基于Token的身份验证,关于 jwt
请访问 JWT有详细的说明,并且有各个语言实现的库,请根据须要使用对应的版本。git
须要先安装 jwt-go
接口 go get github.com/dgrijalva/jwt-go
github
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"})
}
}
复制代码
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"))//对应的字符串请自行生成,最后足够使用加密后的字符串
}
复制代码
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.go
restful
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 Header
中post
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)//不须要中间件
复制代码
//请求 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
}
复制代码