dongzhitao4839 2016-09-29 20:16
浏览 42

轻松+ JWT认证

I'm trying to plug JWT authentication within a very simple go service written with go-restful.

The code is very similar to:

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))
}

where restful.Request is a wrapper around http.Request.

That being said, it might be possible to use the Auth0 jwt middleware.

But as a golang newbie, I'm a bit lost in the plumbing process. I see that I must use a Filter function like

ws.Filter(jwtAuthentication)

where

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

But I don't figure how and where should I instanciate the JWT middleware.

  • 写回答

2条回答 默认 最新

  • duanlu1950 2017-03-22 15:39
    关注

    Here is the example of filter implementation using auth0/go-jwt-middleware. In real life you probably want to avoid creating new instance of jwtMiddleware every time.

    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)
    }
    

    After the filter the parsed token will be in the context (auth0/go-jwt-middleware uses gorilla/context). Default context key is user.

    Note: when JWTMiddleware.SigningMethod is set, the middleware verifies that tokens are signed with the specific signing algorithm.

    If the signing method is not constant, the ValidationKeyGetter callback can be used to implement additional checks.

    Important to avoid security issues described here.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。