简体   繁体   English

Go 中的 Json 网络令牌无效

[英]Invalid Json web token in Go

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.我正在尝试使用 Go 制作一个 Json Web 令牌身份验证系统,但是我似乎无法解析 Web 令牌的工作。 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

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

I have also tried curl without Bearer我也试过没有Bearer curl

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.发生错误是因为令牌无效token.Valid = false我使用以下过程生成了它。

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

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谢谢

The error returned by jwt.Parse() says jwt.Parse()返回的错误说

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!对不起,这不是一个完整的答案!

key is of invalid type密钥的类型无效

type in this context is referring to the dynamic data-type in Go.这种上下文中的类型指的是 Go 中的动态数据类型。

For SigningMethodRSA , the public key must be of type *rsa.PublicKey which can be constructed by calling jwt.ParseRSAPublicKeyFromPEM() .对于SigningMethodRSA ,公钥必须是*rsa.PublicKey类型,它可以通过调用jwt.ParseRSAPublicKeyFromPEM()来构造。

The key value returned to the parser might be created with something like:返回给解析器的键值可能是用以下内容创建的:

keyStruct, _ := jwt.ParseRSAPublicKeyFromPEM(myPublicKeyString)

See:看:

Related:有关的:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM