I use AWS Lambda + Cognito (User Pool + Federated Identity) + API Gateway. Users authenticate in WEB application with amazon-cognito-identity-js and invokes API with aws-api-gateway-client. API Gateway methods have AWS_IAM authorizer. How to get username (from User Pool) in Lambda function?
How to get current user username in AWS Lambda?
Asked Answered
How is this a different question from your previous post(s)? #46121381 #46108931 –
Obscenity
Related: #37964406 –
Jerlenejermain
@MarkB I've removed that post –
Ballade
You can use event.identity.username
exports.handler = async (event, _, callback) => {
try {
console.log('event', event);
console.log('event.identity.username', event.identity.username);
const userId = event.identity.username;
console.log('userId', userId);
callback(null, true);
} catch(e) {
console.log(e);
callback(e);
}
};
event.identity dosent have a field named username. Am I missing something? –
Convertiplane
@VikasSaini hmm, maybe because of you not use cognito? –
Serena
Ok let me share more details, apologies for delay in comment response. I use Cognito User Pool + Identity Pool, my lambda is in VPC behind API gateway secured via IAM Authorizer. After passing APIG, my lambda receives the event that contains event.requestContext.identity , now this object dosent have much information, only cognitoIdentityPoolId, cognitoAuthenticationType, cognitoAuthenticationProvider. Ofcourse I can get sub Id from this but I wanted email, name, groups etc. For this I had to do another call to cognito which takes another 500ms –
Convertiplane
@VikasSaini I guess if you use IAM Authorizer it would not work, try to change type –
Serena
Modify the request sent to your Lambda function using aws-api-gateway-client
to pass the JWT ID Token
in the request header.
You may need to ensure your API gateway is configured to forward headers.
apigClient.invokeApi(
params,
pathTemplate,
method,
{ { headers: { IDToken } } },
body);
The ID Token should be used here as its payload contains cognito:username field
The ID Token
is gotten after authentication using amazon-cognito-identity-js
.
You can parse this field from the header of the request in your lambda handler function.
Verify its signature before trusting the contents of its payload.
import { util } from 'aws-sdk/global';
exports.handler = function(event, context) {
// Parse ID Token from request header
const headers = event.headers;
const idToken = headers.IDToken;
...
};
You cannot securely encrypt a token on the client side and expect it to be untouched on the server side. Retrieving details from a JWT token without checking the signature is very unsafe. –
Spatterdash
You make a good point about not trusting the JWT token. My answer can be updated to forward the IDToken since that contains the Cognito username. –
Arboreous
event.requestContext.authorizer.claims.username
Thats where I get it from other places it gives null
© 2022 - 2024 — McMap. All rights reserved.