Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access JWT claims from API handler functions in go-swagger?

I'm using go-swagger with BearerAuth using JWT tokens. Along with the actual token I'm receiving claims which include such data as username.

How can I access claims in api.ItemsCreateItemHandler function below?

package restapi

func configureAPI(api *operations.MyAPI) http.Handler {
    api.BearerAuth = func(token string) (interface{}, error) {
        jwtToken := strings.Replace(token, "Bearer ", "", -1)
        // skipped token verification

        claims, _ := parsedToken.Claims.(jwt.MapClaims)
  }

  api.ItemsCreateItemHandler = items.CreateItemHandlerFunc(func(params items.CreateItemParams, principal interface{}) middleware.Responder {
    // FIXME: Here I need to be able to access JWT claims
    if err := createItem(params.Body, claims); err != nil {
            return nil // handle error
        }
        return items.NewCreateItemCreated()
    })
}
like image 400
Maklaus Avatar asked Aug 29 '18 19:08

Maklaus


1 Answers

First your BearerAuth implementation is meant to return the security principal (which can be your claims in this case), this value will subsequently be passed to your handler in the principal argument.

So the way to do this is:

package restapi

import (
    jwt "github.com/dgrijalva/jwt-go"
    // ...
)

func configureAPI(api *operations.MyAPI) http.Handler {
    api.BearerAuth = func(token string) (interface{}, error) {
        jwtToken := strings.Replace(token, "Bearer ", "", -1)
        // skipped token verification
        claims, _ := parsedToken.Claims.(jwt.MapClaims)
        return claims, nil
    }

    api.ItemsCreateItemHandler = items.CreateItemHandlerFunc(func(params items.CreateItemParams, principal interface{}) middleware.Responder {
        claims, ok := principal.(jwt.MapClaims)
        if !ok {
            // handle error
        }
        if err := createItem(params.Body, claims); err != nil {
            return nil // handle error
        }
        return items.NewCreateItemCreated()
    })
}

You can make this less cumbersome by using the --principal jwt.MapClaims option to swagger generate so that it uses this type for the claims instead of interface{}.

like image 98
Ezequiel Muns Avatar answered Nov 09 '22 22:11

Ezequiel Muns