gpt4 book ai didi

rest - go-restful + JWT认证

转载 作者:数据小太阳 更新时间:2023-10-29 03:05:44 24 4
gpt4 key购买 nike

我正在尝试将 JWT 身份验证插入到使用 go-restful 编写的非常简单的 go 服务中.

代码非常类似于:

package main

import (
"github.com/emicklei/go-restful"
"log"
"net/http"
)

type User struct {
Id, Name string
}

type UserList struct {
Users []User
}

func getAllUsers(request *restful.Request, response *restful.Response) {
log.Printf("getAllUsers")
response.WriteEntity(UserList{[]User{{"42", "Gandalf"}, {"3.14", "Pi"}}})
}

func NewUserService() *restful.WebService {
ws := new(restful.WebService)
ws.
Path("/users").
Consumes(restful.MIME_XML, restful.MIME_JSON).
Produces(restful.MIME_JSON, restful.MIME_XML)

ws.Route(ws.GET("").To(getAllUsers))

return ws
}


func main() {
restful.Add(NewUserService())
log.Printf("start listening on localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}

其中 restful.Requesthttp.Request 的包装器。

也就是说,可以使用 Auth0 jwt middleware .

但作为一个 golang 新手,我在管道过程中有点迷茫。我看到我必须使用像

这样的 Filter 函数
ws.Filter(jwtAuthentication)

在哪里

func jwtAuthentication(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
// Jwt Magic goes here \o
chain.ProcessFilter(req, resp)
}

但我不知道应该如何以及在何处实例化 JWT 中间件。

最佳答案

这是使用 auth0/go-jwt-middleware 实现过滤器的示例.在现实生活中,您可能希望避免每次都创建 jwtMiddleware 的新实例。

func jwtAuthentication(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte("My Secret"), nil
},
SigningMethod: jwt.SigningMethodHS256,
})

if err := jwtMiddleware.CheckJWT(resp.ResponseWriter, req.Request); err != nil {
logger.Errorf("Authentication error: %v", err)
}
chain.ProcessFilter(req, resp)
}

在过滤器之后,解析的 token 将在上下文中( auth0/go-jwt-middleware 使用 gorilla/context )。默认上下文键是 user

注意:设置 JWTMiddleware.SigningMethod 时,中间件会验证 token 是否已使用特定的签名算法签名。

如果签名方法不是常量,则可以使用 ValidationKeyGetter 回调来实现额外的检查。

避免安全问题的重要说明here .

关于rest - go-restful + JWT认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39779243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com