首頁 > 後端開發 > Golang > 主體

如何使用 go gin 從 Auth0 jwt 令牌檢索權限

WBOY
發布: 2024-02-12 15:09:07
轉載
979 人瀏覽過

如何使用 go gin 从 Auth0 jwt 令牌检索权限

問題內容

我正在學習 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
}
登入後複製

以上是如何使用 go gin 從 Auth0 jwt 令牌檢索權限的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!