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()
})
}
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{}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With