Search code examples
google-cloud-platformgoogle-cloud-functionsjwtgoogle-api-gateway

How to get the jwt payload in route authenticated by api gateway inside the function?


I have a gateway configured for my project, and i added the security options in the route and it's works:

My function thats generate the jwt token:

def generate_jwt():
    payload = {"iat": iat, "exp": exp, "iss": iss, "aud":  aud, "sub": iss, "email": iss, "company": company}

    signer = google.auth.crypt.RSASigner.from_service_account_file(sa_keyfile)
    jwt = google.auth.jwt.encode(signer, payload)

    return jwt

.yaml file:

- Security:

securityDefinitions:
  apikey:
    type: "apiKey"
    name: "key"
    in: "header"
  bearer:
    authorizationUrl: ""
    flow: "implicit"
    type: "oauth2"
    x-google-issuer: "mygserviceaccount"
    x-google-jwks_uri: "mygserviceaccount.com"
    x-google-audiences: "aud"
    x-google-jwt-locations:
      - header: "Authorization"
        value_prefix: "Bearer "

- My route with jwt configurated:

/MyRoute:
    post:
      description: "Route"
      operationId: "Route"
      x-google-backend:
        address: routeadress
        deadline: 360
      security:
      - bearer: []
      responses:
        200:
          description: "Success."
        400:
          description: "Bad Request."
        401:
          description: "Unauthorized."

With this configuration, i need to send the jwt token in Header, if i don`t send this, the gateway returns an error, otherwise if the jwt is valid, my function is called. So this works!

But my question is, how i recover the payload generated by api gateway in MyRoute?

The payload should be available for me or i need to call antother google api for decode the jwt who comes in req.headers.authorization ?

The answer like said by @John Hanley is use the header x-apigateway-api-userinfo:

const userInfo = req.headers['x-apigateway-api-userinfo']

const data = Buffer.from(userInfo, 'base64').toString('utf-8')

My data have the payload that i was informed.


Solution

  • API Gateway will forward the JWT in the HTTP header X-Apigateway-Api-Userinfo. This header is Base64 URL Encoded and contains the JWT Payload.

    Receiving authenticated results in your API

    [EDIT: I added the example that @Vinicius wrote in response to my answer]

    const userInfo = req.headers['x-apigateway-api-userinfo']
    
    const data = Buffer.from(userInfo, 'base64').toString('utf-8')