Go中的Json Web令牌无效

时间:2016-09-12 23:50:03

标签: json parsing curl go json-web-token

我正在尝试使用Go创建一个Json Web令牌认证系统但是我似乎无法解析Web令牌的工作。 以下函数发生错误。

func RequireTokenAuthentication(rw http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
authBackend := InitJWTAuthenticationBackend()

jwtString := req.Header.Get("Authorization")


token, err := jwt.Parse(jwtString, func(token *jwt.Token) (interface{}, error) {
    if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
        log.Println("Unexpected signing method")
        return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
    } else {
        log.Println("The token has been successfully returned")
        return authBackend.PublicKey, nil
    }
})

log.Println(token)
log.Println(token.Valid)

if err == nil && token.Valid && !authBackend.IsInBlacklist(req.Header.Get("Authorization")) {
    next(rw, req)
} else {
    rw.WriteHeader(http.StatusUnauthorized)
    log.P

rintln("Status unauthorized RequireTokenAuthentication")
    }
}

返回以下日志

[negroni] Started GET /test/hello
2016/09/13 01:34:46 &{Bearer eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0NzM5NzQ4OTAsImlhdCI6MTQ3MzcxNTY5MCwic3ViIjoiIn0.mnwEwdR8nuvdLo_4Ie43me7iph2LeSj1uikokgD6VJB7isjFPShN8E7eQr4GKwuIiLTi34_i6iJRpmx9qrPugkzvsoxX44qlFi6M7FDhVySRiYbBQwTCvKCpvhnsK8BHJyEgy813aaxOMK6sKZJoaKs5JYUvnNZdNqmENYj1BM6FdbGP-oLHuR_CJK0Pym1NMhv9zLI1rpJOGu4mfj1t4tHYZAEGirPnzYMamtrK6TyEFE6Xi4voEEadq7hXvWREg6wNSQsYgww8uOaIWLy1yLbhTkPmT8zfRwLLYLqS_UuZ0xIaSWO1mF2plvOzz1WlF3ZEHLS31T1egB1XL4WTNQe <nil> map[] <nil>  false}
2016/09/13 01:34:46 false
2016/09/13 01:34:46 Status unauthorized RequireTokenAuthentication
[negroni] Completed 401 Unauthorized in 71.628ms

这是我用来启动它的cURL

curl -H "Authorization: Bearer eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0NzM5NzQ4OTAsImlhdCI6MTQ3MzcxNTY5MCwic3ViIjoiIn0.mnwEwdR8nuvdLo_4Ie43me7iph2LeSj1uikokgD6VJB7isjFPShN8E7eQr4GKwuIiLTi34_i6iJRpmx9qrPugkzvsoxX44qlFi6M7FDhVySRiYbBQwTCvKCpvhnsK8BHJyEgy813aaxOMK6sKZJoaKs5JYUvnNZdNqmENYj1BM6FdbGP-oLHuR_CJK0Pym1NMhv9zLI1rpJOGu4mfj1t4tHYZAEGirPnzYMamtrK6TyEFE6Xi4voEEadq7hXvWREg6wNSQsYgww8uOaIWLy1yLbhTkPmT8zfRwLLYLqS_UuZ0xIaSWO1mF2plvOzz1WlF3ZEHLS31T1egB1XL4WTNQe" http://localhost:5000/test/hello

我还尝试过没有Bearer

的卷曲
curl -H "Authorization:eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0NzM5NzQ4OTAsImlhdCI6MTQ3MzcxNTY5MCwic3ViIjoiIn0.mnwEwdR8nuvdLo_4Ie43me7iph2LeSj1uikokgD6VJB7isjFPShN8E7eQr4GKwuIiLTi34_i6iJRpmx9qrPugkzvsoxX44qlFi6M7FDhVySRiYbBQwTCvKCpvhnsK8BHJyEgy813aaxOMK6sKZJoaKs5JYUvnNZdNqmENYj1BM6FdbGP-oLHuR_CJK0Pym1NMhv9zLI1rpJOGu4mfj1t4tHYZAEGirPnzYMamtrK6TyEFE6Xi4voEEadq7hXvWREg6wNSQsYgww8uOaIWLy1yLbhTkPmT8zfRwLLYLqS_UuZ0xIaSWO1mF2plvOzz1WlF3ZEHLS31T1egB1XL4WTNQe" http://localhost:5000/test/hello

发生错误是因为令牌无效token.Valid = false我使用以下过程生成了它。

这是路由器

router.HandleFunc("/token-auth", controllers.Login).Methods("POST")

这是登录控制器

    func Login(w http.ResponseWriter, r *http.Request) {
    requestUser := new(models.User)
    decoder := json.NewDecoder(r.Body)
    decoder.Decode(&requestUser)    
    responseStatus, token := utils.Login(requestUser) //here the util file seen below is used
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(responseStatus)
    w.Write(token)

}

这是util文件

    func Login(requestUser *models.User) (int, []byte) {
        authBackend := authentication.InitJWTAuthenticationBackend()

        if authBackend.Authenticate(requestUser) {
            token, err := authBackend.GenerateToken(requestUser.UUID)
            if err != nil {
                return http.StatusInternalServerError, []byte("")
            } else {
                response, _ := json.Marshal(parameters.TokenAuthentication{token})
                return http.StatusOK, response
            }
        }
        return http.StatusUnauthorized, []byte("")
    }

这是用于生成令牌

的方法
    func (backend *JWTAuthenticationBackend) GenerateToken(userUUID string) (string, error) {
    token := jwt.New(jwt.SigningMethodRS512)

    claims := token.Claims.(jwt.MapClaims)

    claims["exp"] = time.Now().Add(time.Hour * time.Duration(settings.Get().JWTExpirationDelta)).Unix()
    claims["iat"] = time.Now().Unix()
    claims["sub"] = userUUID

    tokenString, err := token.SignedString(backend.privateKey)
    if err != nil {
        panic(err)
        return "", err
    }

    return tokenString, nil
}

如何修复令牌解析系统以使令牌有效? 如果您需要任何其他信息,我将非常乐意使用相应的信息进行编辑。 感谢

2 个答案:

答案 0 :(得分:1)

jwt.Parse()返回的错误

  

tokenstring不应包含'bearer'

所以如果你删除“Bearer”:

jwtString = strings.Split(jwtString, "Bearer ")[1]

你得到了更多的信息

  

已成功返回令牌

然而现在出现了一个新错误:

  

键的类型无效

对不起,这不是一个完整的答案!

答案 1 :(得分:0)

  

密钥的类型无效

在这种情况下,

type 指的是Go中的动态数据类型。

对于SigningMethodRSA,公钥必须为*rsa.PublicKey类型,可以通过调用jwt.ParseRSAPublicKeyFromPEM()来构造。

返回解析器的键值可能是用类似以下的内容创建的:

keyStruct, _ := jwt.ParseRSAPublicKeyFromPEM(myPublicKeyString)

请参阅:

相关: