douou6696 2016-03-24 06:02
浏览 50

GoLang JWT与马提尼酒抛出<无效值>?

I'm trying the JWT middleware examples to get JWT to work with Martini and it's giving me an return when it hits the authentication handler.

Here's the code, straight from the examples..

package main

import (
    "encoding/json"
    "github.com/auth0/go-jwt-middleware"
    "github.com/dgrijalva/jwt-go"
    "github.com/go-martini/martini"
    "net/http"
)

func main() {

    StartServer()

}

func StartServer() {
    m := martini.Classic()

    jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
        ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
            return []byte("My Secret"), nil
        },
        SigningMethod: jwt.SigningMethodHS256,
    })

    m.Get("/ping", PingHandler)
    m.Get("/secured/ping", jwtMiddleware.CheckJWT, SecuredPingHandler)

    m.Run()
}

type Response struct {
    Text string `json:"text"`
}

func respondJson(text string, w http.ResponseWriter) {
    response := Response{text}

    jsonResponse, err := json.Marshal(response)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Type", "application/json")
    w.Write(jsonResponse)
}

func PingHandler(w http.ResponseWriter, r *http.Request) {
    respondJson("All good. You don't need to be authenticated to call this", w)
}

func SecuredPingHandler(w http.ResponseWriter, r *http.Request) {
    respondJson("All good. You only get this message if you're authenticated", w)
}

If I hit the unauthenticated route, it works. If I hit the authenticated route, it tells me I need a token. If I hit the authenticated route with a token that's not right, I get an error stating,

signature is invalid
<*errors.errorString Value>

So all that works. If I hit the authenticated route with the right token, it gives me as the return text. I can't find out why. This is straight from their example, though I get the same in my personal project.

  • 写回答

1条回答 默认 最新

  • dqve65954 2017-02-17 05:04
    关注

    Instead of

    m.Get("/secured/ping", jwtMiddleware.CheckJWT, SecuredPingHandler)
    

    Try this instead

    m.Get("/secured/ping", jwtMiddleware.Handler(SecuredPingHandler))
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器