简体   繁体   English

Golang JWT 与 go-jwt-middleware 无效

[英]Golang JWT is invalid with go-jwt-middleware

Got JWT is invalid with new version of "github.com/auth0/go-jwt-middleware/v2"得到JWT is invalid"github.com/auth0/go-jwt-middleware/v2"的新版本无效

successfully generate token with "github.com/golang-jwt/jwt/v4" plugin, and try to use it on request but rejected on middleware, i guess the issues in go-jwt-middleware .使用"github.com/golang-jwt/jwt/v4"插件成功生成令牌,并尝试根据请求使用它但在中间件上被拒绝,我猜是go-jwt-middleware中的问题。 there is some missing with implementation, maybe anyone has already implement and want to share please实施中有一些缺失,也许有人已经实施并想分享

Here is the code:这是代码:

type Claims struct {
    Username string `json:"username"`
    Role     string `json:"role"`
    Id       string `json:"id"`
    Avatar   string `json:"avatar"`
    jwt.StandardClaims
}

func (c *Claims) Validate(ctx context.Context) error {
    return nil
}

var jwtKey = []byte("secret")

func Middleware(h http.Handler) http.Handler {
    keyFunc := func(ctx context.Context) (interface{}, error) {
        return jwtKey, nil
    }

    customClaims := func() validator.CustomClaims {
        return &Claims{}
    }

    jwtValidator, err := validator.New(
        keyFunc,
        validator.HS256,
        "issuer",
        []string{"audience"},
        validator.WithCustomClaims(customClaims),
        validator.WithAllowedClockSkew(30*time.Second),
    )
    if err != nil {
        log.Fatalf("Failed to set up the validator: %v", err)
    }

    // Set up the middleware.
    middleware := jwtmiddleware.New(jwtValidator.ValidateToken)
    return middleware.CheckJWT(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        _, token, err := ParseToken(r)
        if !token.Valid || err != nil {
            w.WriteHeader(401)
            w.Write([]byte("Unauthorized"))
            return
        }

        h.ServeHTTP(w, r)
    }))
}

func GenerateToken(id string, username string, role string, avatar string) (string, int64, error) {
    expirationTime := time.Now().Add(time.Hour * 24).Unix()
    claims := &Claims{
        Id:       id,
        Username: username,
        Role:     role,
        Avatar:   avatar,
        StandardClaims: jwt.StandardClaims{
            ExpiresAt: expirationTime,
        },
    }

    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    tokenString, err := token.SignedString(jwtKey)
    if err != nil {
        return "", 0, err
    }

    return tokenString, expirationTime, nil
}

And i don't found any doccumentation for the value for issuer && audience option on validator.而且我没有找到任何关于验证器上的issuer者 && audience选项的价值的文档。 just follow the example :只需按照示例进行操作:

    jwtValidator, err := validator.New(
        keyFunc,
        validator.HS256,
        "issuer", <------------ issuer
        []string{"audience"}, <------------ audience
        validator.WithCustomClaims(customClaims),
        validator.WithAllowedClockSkew(30*time.Second),
    )
        Issuer:   issuerURL,
        Audience: audience,

The audience value is a string -- typically, the base address of the resource being accessed.受众值是一个字符串——通常是被访问资源的基地址。 for example which services, APIs, products should accept this token as an access token for the service.例如,哪些服务、API、产品应该接受这个令牌作为服务的访问令牌。 A token valid for Stackoveflow should not be accepted for the Stack exchange website, even if both of them have the same issuer, they'll have different audiences. Stack 交换网站不应接受对 Stackoveflow 有效的令牌,即使它们都有相同的发行者,它们也会有不同的受众。

Issuer value is a string like this https://<issuer-url>/ Who created the token.颁发者值是这样的字符串https://<issuer-url>/谁创建了令牌。 like token issued by GitHub or LinkedIn and this can be verified by using the OpenID configuration endpoint类似于 GitHub 或 LinkedIn 发布的令牌,这可以通过使用 OpenID 配置端点来验证

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

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