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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?