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 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?