登录
首页 >  Golang >  Go问答

使用 Auth0 jwt 令牌来检索权限的 go gin 实践指南

来源:stackoverflow

时间:2024-02-06 09:09:21 229浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《使用 Auth0 jwt 令牌来检索权限的 go gin 实践指南》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

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

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()
    }
}

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

这是令牌内容:

{
  "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 访问它,或者我必须先以某种方式解码它?


正确答案


权限是自定义声明,因此您需要传递 WithCustomClaims 选项以及 validator.CustomClaims 接口的实现。 然后当您创建验证器时:

...
    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
}

终于介绍完啦!小伙伴们,这篇关于《使用 Auth0 jwt 令牌来检索权限的 go gin 实践指南》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>