Golang中panic错误:接口转换jwt.claims到jwt.mapclaims的问题

Golang中panic错误:接口转换jwt.claims到jwt.mapclaims的问题 我在使用Postman调用API时遇到以下错误:提示jwt.claims转换为jwt.mapClaims时出现问题,但我不清楚如何进行修改…我的代码如下…

if token.Valid {
ctx: = context.WithValue (r.Context (), "user", token.Claims. (* models.Claim) .User)
next (w, r.WithContext (ctx))
}

问题很可能出现在token.Claims. (* models.Claim) .User)这部分,但我不知道如何将其转换为mapClaims。

有人能提供一些帮助吗?具体该如何实现?

致意。


更多关于Golang中panic错误:接口转换jwt.claims到jwt.mapclaims的问题的实战教程也可以访问 https://www.itying.com/category-94-b0.html

7 回复

你好,能否发布一下 panic 的文本信息?

更多关于Golang中panic错误:接口转换jwt.claims到jwt.mapclaims的问题的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


恐慌信息仅此而已,我使用了jwt-go、negroni以及一个自己编写的包。我可以提供恐慌信息,这不成问题,我会在这里贴出来。请稍等片刻。

它期望一个指向 jwt.mapClaims 的指针,即 *jwt.mapClaims,但你只提供了 jwt.mapClaims。请在此处阅读有关指针的内容:https://www.golang-book.com/books/intro/8

我理解这一点,但我不知道应该如何以指针形式传递 *jwt.MapClaims 的声明信息。我已经尝试使用了 *jwt.mapClaims 但并未生效,可能是我使用的方式不正确。

能请你帮帮我吗?

我已经解决了那个panic错误,但现在又遇到了另一个问题。

当我尝试操作我的API /api/comments/

我收到了错误请求,之前的处理代码是:

if token.Valid {
   ctx := context.WithValue(r.Context(), "user", token.Claims.(*models.Claim).User)
   next(w, r.WithContext(ctx))
} else {
   m.Code = http.StatusUnauthorized
   m.Message = "Su token no es válido"
   commons.DisplayMessage(w, m)
}

而我解决错误后的新代码是:

if claims , ok := token.Claims.(*models.Claim); ok && token.Valid {
   ctx := context.WithValue(r.Context(), "user", *claims)
   next(w,r.WithContext(ctx))
} else {
   m.Code = http.StatusBadRequest
   m.Message = "Su token no es válido"
   commons.DisplayMessage(w,m)
}

但我没有收到响应,这是因为令牌无效,但我使用的是正确的令牌。

在Golang中处理JWT时,接口类型转换错误很常见。问题确实出现在token.Claims.(*models.Claim)这部分,因为token.Claims返回的是jwt.Claims接口,但实际存储的可能是jwt.MapClaims类型。

以下是正确的实现方式:

if token.Valid {
    // 首先将Claims转换为MapClaims
    if claims, ok := token.Claims.(jwt.MapClaims); ok {
        // 从MapClaims中提取用户信息
        if userClaim, exists := claims["user"]; exists {
            ctx := context.WithValue(r.Context(), "user", userClaim)
            next(w, r.WithContext(ctx))
        }
    } else {
        // 处理转换失败的情况
        http.Error(w, "Invalid token claims", http.StatusUnauthorized)
        return
    }
}

如果你的JWT token是使用标准claims结构生成的,也可以这样处理:

if token.Valid {
    // 使用类型断言检查claims类型
    switch claims := token.Claims.(type) {
    case jwt.MapClaims:
        if user, exists := claims["user"]; exists {
            ctx := context.WithValue(r.Context(), "user", user)
            next(w, r.WithContext(ctx))
        }
    case *models.Claim: // 如果你确实使用了自定义Claim结构
        ctx := context.WithValue(r.Context(), "user", claims.User)
        next(w, r.WithContext(ctx))
    default:
        http.Error(w, "Unsupported claims type", http.StatusUnauthorized)
        return
    }
}

确保你的JWT解析代码与token生成时使用的claims类型一致。如果你在生成token时使用的是jwt.MapClaims,那么在解析时也应该使用相同的类型进行类型断言。

回到顶部