go - 如何使用 go gin 从 Auth0 jwt token 检索权限

标签 go jwt auth0 go-gin

我正在学习 go,想使用 auth0 设置一个简单的应用程序。 使用their教程 我能够为我的 api 端点设置基本身份验证。 现在我想使用 jwt token 添加权限处理。 因此,我为 api 端点激活了 RBAC 并添加了权限。 我使用教程中的流程进行自定义声明,但用它编写了我自己的中间件并将其调整为与 Gin 一起使用。

func NeedsPermission(expectedScope string) gin.HandlerFunc {
    return func(context *gin.Context) {
        token := context.Request.Context().Value(jwtmiddleware.ContextKey{}).(*validator.ValidatedClaims)

        claims := token.CustomClaims.(*CustomClaims)

        if !claims.HasScope(expectedScope) {
            context.AbortWithStatus(403)
        }
        context.Next()
    }
}

问题是 token 中没有自定义声明,只有默认声明:openid、个人资料和电子邮件声明。

这是 token 内容:

{
  "iss": "https://dev-****.us.auth0.com/",
  "sub": "google-oauth2|****",
  "aud": [
    "localhost:3000/books",
    "https://dev-****.us.auth0.com/userinfo"
  ],
  "iat": 1701789297,
  "exp": 1701875697,
  "azp": "***",
  "scope": "openid profile email",
  "permissions": [
    "read:books"
  ]
}

所以它确实有一个字段权限,但是我如何使用 auth0/go-jwt-middleware 访问它,或者我必须先以某种方式解码它?

最佳答案

Permissions 是自定义声明,因此您需要通过 validator.CustomClaims 接口(interface)的实现来传递 WithCustomClaims 选项。 然后当您创建验证器时:

    ...
    jwtValidator, _ := validator.New(
        keyFunc,
        validator.HS256,
        issuer,
        audience,
        validator.WithCustomClaims(func() validator.CustomClaims {
            return &MyClaims{}
        }),
    )
    mw := jwtmiddleware.New(jwtValidator.ValidateToken)
    ...

其中 MyClaims 是这样的。请注意您的 HasScope 方法:

type MyClaims struct {
    Permissions    []string `json:"permissions"`
}

func (c *MyClaims) Validate(ctx context.Context) error {
    // Validate structure of permissions here, i.e. check for 400 not 403
    return nil
}

func (c MyClaims) HasScope(requiredPerm string) bool {
    for _, perm := range c.Permissions {
        if perm == requiredPerm {
            return true
        }
    }
    return false
}

关于go - 如何使用 go gin 从 Auth0 jwt token 检索权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77608552/

相关文章:

go - 使用 Go 在一片结构中按时间平均

function - 使用方法而不是函数有什么好处吗?

go - go中如何与UDP服务器中的多个客户端进行通信?

javascript - 浏览器刷新后 Nuxt auth 用户重置

mysql - 如何在 Auth0 Connection 中配置自定义数据库 Mysql?

javascript - 配置 Auth0 工作流程时出现问题

go - 选择忽略慢的情况?

javascript - 如何在 Angular 8 中存储 jwt token 之类的数据?是否有另一种使用本地存储或 session 存储安全存储的方法?

vuejs2 - Auth0和Vue : Error in render function: "InvalidTokenError: Invalid token specified: Cannot read property ' replace' of undefined"

security - JOSE jwe/jws 有效负载