dsuvs66406 2018-01-12 11:58
浏览 21
已采纳

将变量从中间件传递到最终功能

im using a middleware (CheckToken) to check a JWT and get the custom claim (Id) (it will be the id of the user on my DB) but i need to pass it to campaign.Attack (so i can know who is the user who is doing the "attack") but i cant find out a way to do it.

i tried to pass it as a parameter in next(w, req, claim.id) in token.go but i would need to touch the http.HandlerFunc function so this isnt a valid option.

any idea about how to pass the claim.id from CheckToken to campaign.Attack() ?

thank you

         ***** main.go*****

            func main() {

                router := mux.NewRouter()

                router.HandleFunc("/attack", token.CheckToken(campaign.Attack)).Methods("GET", "OPTIONS")

               log.Fatal(http.ListenAndServe(":3000", handlers.CORS(handlers.AllowedOrigins([]string{"*"}),
                    handlers.AllowedHeaders([]string{"Content-Type", "authorization"}))(router)))
            }



            ******campaign.go*****

            package campaign

            import (
                "log"
                "net/http"

            )


            func init() {

            }

            func Attack(w http.ResponseWriter, req *http.Request) {
                log.Println("attack")

                //i need to get the claim.Id here
            }


            ****token.go****

type MyCustomClaims struct {
    Id int `json:"id"`  //the Id of the user 
    jwt.StandardClaims
}

            func CheckToken(next http.HandlerFunc) (MyCustomClaims, http.HandlerFunc) {
                return MyCustomClaims{}, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {

                    authorizationHeader := req.Header.Get("authorization")
                    if authorizationHeader != "" {
                        bearerToken := strings.Split(authorizationHeader, " ")
                        if len(bearerToken) == 2 {
                            token, err := jwt.ParseWithClaims(bearerToken[1], &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
                                return []byte("magicword"), nil
                            })

                            if token.Valid {


                                if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
                               //**************************
                              //***********i have the claims.id here and it works.*******
                              //**************************
                                    log.Println(claims.Id)

                              //but i need to pass it or find a way to read it in campaign.Attack()
                                    next(w, req)
                                } else {
                                    log.Println(err)
                                }
                            } else if ve, ok := err.(*jwt.ValidationError); ok {
                                if ve.Errors&jwt.ValidationErrorMalformed != 0 {


                                } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
                                    // Token is either expired or not active yet

                                } 
                            } 
                        } 
                    } 


                })

            }
  • 写回答

2条回答 默认 最新

  • douxing6532 2018-01-12 14:09
    关注

    Look into CheckToken .. It should be middleware, and typical midleware pass http.Handler and maybe another argument and return another http.Handler (this is bit better than using http.HandlerFunc). Returned function typically call argument and do some action before or after this call.

    func CheckToken(next http.Handler) http.Handler
    {
       return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
         // and body the same as you have in the answer, but instead of next(w, req) put there two lines "WithValue"
       }
    }
    

    and into begin of Attack put next few lines that I've already give you

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示