繁体   English   中英

如何在 jwt-go ParseWithClaims 中使用 RSA 解析 JWT 令牌?

[英]How to parse a JWT token with RSA in jwt-go ParseWithClaims?

我开发了以下方法,它应该启用基于令牌的身份验证 (jwt)。 应使用异步过程来生成令牌。

源代码似乎适用于并包括签名令牌的生成。 使用ParseWithClaims查询令牌时遇到问题。 有人可以帮忙吗?

package controllers

import (
    "crypto/rand"
    rsaKeys "crypto/rsa"
    "fmt"

    jwtgo "github.com/dgrijalva/jwt-go"
    "github.com/gofiber/fiber"
)

func Login(c *fiber.Ctx) error {
    
    type TestClaims struct {
        HAPP string `json:"happ"`
        jwtgo.StandardClaims
    }

    currentPrivateKey, err := rsaKeys.GenerateKey(rand.Reader, 512)

    claims := TestClaims{
        "owa",
        jwtgo.StandardClaims{
            Issuer:    "test",
            ExpiresAt: 15000,
        },
    }

    token := jwtgo.NewWithClaims(jwtgo.SigningMethodRS256, claims)

    tokenSigned, err := token.SignedString(currentPrivateKey)
    if err != nil {
        fmt.Printf("Failed to sign in account %v", err)
    }

    //Issue is in this statement
    _, errTest := jwtgo.ParseWithClaims(tokenSigned, &TestClaims{"owa", jwtgo.StandardClaims{}}, func(token *jwtgo.Token) (interface{}, error) {
        return currentPrivateKey, nil
    })

    if errTest != nil {
        fmt.Printf("Error Message: %v", errTest) //Does throw error: key is of invalid type
    }

    return c.JSON(fiber.Map{
        "message": "success",
    })
}

为了验证你所需要的公共密钥的智威汤逊,具体ParseWithClaims预计类型的密钥*rsa.PublicKey

您可以使用PrivateKey.Public从私钥中获取它:

tok, err := jwtgo.ParseWithClaims(tokenSigned, &TestClaims{"owa", jwtgo.StandardClaims{}}, func(token *jwtgo.Token) (interface{}, error) {
    return currentPrivateKey.Public(), nil
})

请注意dgrijalva/jwt-go是未维护的 如果可以,请切换到社区分支golang-jwt/jwt ,其中包括关键的安全修复程序。

暂无
暂无

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

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