I am learning go and want to set up a simple application using auth0. Using their tutorial I was able to set up basic auth for my api endpoint. Now I want to add permission handling using jwt token. So I activated RBAC for the api endpoint and added permissions. I used the flow from the tutorial for custom declarations, but wrote my own middleware with it and adapted it to work with 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() } }
The problem is that there are no custom claims in the token, only the default claims: openid, profile and email claims.
This is the token content:
{ "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" ] }
So it does have a field permission, but how do I access it using auth0/go-jwt-middleware or do I have to decode it somehow first?
Permissions are custom claims, so you need to pass the WithCustomClaims
option along with an implementation of the validator.CustomClaims
interface.
Then when you create the validator:
... jwtValidator, _ := validator.New( keyFunc, validator.HS256, issuer, audience, validator.WithCustomClaims(func() validator.CustomClaims { return &MyClaims{} }), ) mw := jwtmiddleware.New(jwtValidator.ValidateToken) ...
Among them MyClaims
is like this. Please note your HasScope
method:
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 }
The above is the detailed content of How to retrieve permissions from Auth0 jwt token using go gin. For more information, please follow other related articles on the PHP Chinese website!