Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to add a RequestTemplate to enrich REST API requests to Lambda with Cognito UserPool user details (like username and user ID) #657

Open
troygoode opened this issue Jan 4, 2019 · 1 comment

Comments

@troygoode
Copy link

@troygoode troygoode commented Jan 4, 2019

** Which Category is your question related to? **

API, Auth

** What AWS Services are you utilizing? **

Lambda, API Gateway, Cognito User Pools

** Provide additional details e.g. code snippets **

I'd like to have access to information about the Cognito User when they issue a call to an authenticated Serverless Express REST API created via amplify add api. I've seen that Request Templates should be able to be used to inject User claims information into the request. I'm having difficulty finding which part of my myapi-cloudformation-template.json I should add this to.

Ultimately I'd like to be able to write code similar to:

app.post('/posts', async (req, res, next) => {
  try {
    const cognito = new aws.CognitoIdentityServiceProvider()
    const email = req.apiGateway.event.requestContext.user.email
    const myCustomAttribute = req.apiGateway.event.requestContext.user['custom:myCustomAttribute']

    //TODO use the above values for stuff
  } catch (err) {
    next(err)
  }
})
@troygoode

This comment has been minimized.

Copy link
Author

@troygoode troygoode commented Jan 4, 2019

Note that in lieu of the above, I'm currently doing this (which I do not love):

app.post('/my-api', async (req, res, next) => {
  try {
    const IDP_REGEX = /.*\/.*,(.*)\/(.*):CognitoSignIn:(.*)/
    const authProvider = req.apiGateway.event.requestContext.identity.cognitoAuthenticationProvider
    const [,, userPoolId, userSub] = authProvider.match(IDP_REGEX)

    const cognito = new aws.CognitoIdentityServiceProvider()
    const listUsersResponse = await cognito.listUsers({
      UserPoolId: userPoolId,
      Filter: `sub = "${userSub}"`,
      Limit: 1
    }).promise()
    const user = listUsersResponse.Users[0]

    // now I can actually do stuff...
    const myCustomAttribute = user.Attributes.find((a) => a.Name === 'custom:myCustomAttribute').Value
    res.json({})
  } catch (err) {
    console.error(err)
    next(err)
  }
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants
You can’t perform that action at this time.