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

byqmnocz  于 5个月前  发布在  Go
关注(0)|答案(1)|浏览(58)

我正在学习go,想使用auth 0设置一个简单的应用程序。使用他们的教程,我能够为我的API端点设置一个基本的身份验证。现在我想使用jwt令牌添加权限处理。所以我为api-endpoint激活了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()
    }
}

字符串
问题是令牌中没有自定义声明,只有默认声明:openid,profile和email。
这是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"
  ]
}


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

bxjv4tth

bxjv4tth1#

验证器是一个自定义声明,所以你需要通过validator.CustomClaims接口的实现来传递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
}

相关问题