dongli8722 2016-09-12 23:50
浏览 166
已采纳

Go中无效的Json Web令牌

I am trying to make a Json web token authentication system with Go however I cant seem to get the parsing of the web token working. The error occurs in the following function.

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")
    }
}

returns the following log

[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

and here is the cURL that I am using to initiate it

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

I have also tried curl without Bearer

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

The error is occurring because the token is invalid token.Valid = false I have generated it using the following process.

Here is the router

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

Here is the login controller

    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)

}

This is the util file

    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("")
    }

and here is the method used to generate the token

    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
}

How do I fix the Token Parsing system so that the token is valid? If you need any additional information I would be more than happy to make an edit with the respective information. Thank

  • 写回答

2条回答 默认 最新

  • dongshen9686 2016-09-13 00:38
    关注

    The error returned by jwt.Parse() says

    tokenstring should not contain 'bearer '

    So if you remove "Bearer ":

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

    you get a bit further

    The token has been successfully returned

    however now there's a new error:

    key is of invalid type

    Sorry it's not a complete answer!

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

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题