awslabs / cognito-at-edge

Serverless authentication solution to protect your website or Amplify application
Apache License 2.0
168 stars 54 forks source link

How to get the logged in user in the application #62

Open nagendrakumar02 opened 1 year ago

nagendrakumar02 commented 1 year ago

How can we help?

I am currently using cognito@edge and attached it to the CDN. How can I retrieve the userId who has logged into the application?

unitypark commented 1 year ago

all retrieved information are saved in the cookie. one of them has a value of userId which has .LastAuthUser as suffix in key

nagendrakumar02 commented 1 year ago

Thanks!

From: Junghwa Theodore Park @.> Date: Saturday, April 15, 2023 at 2:01 PM To: awslabs/cognito-at-edge @.> Cc: nagendrakumar02 @.>, Author @.> Subject: Re: [awslabs/cognito-at-edge] How to get the logged in user in the application (Issue #62)

all retrieved information are saved in the cookie. one of them has a value of userId.

— Reply to this email directly, view it on GitHubhttps://www.google.com/url?q=https://github.com/awslabs/cognito-at-edge/issues/62%23issuecomment-1509916115&source=gmail-imap&ust=1682186468000000&usg=AOvVaw0PMOS6CSPA0C9Tf1XNdCxZ, or unsubscribehttps://www.google.com/url?q=https://github.com/notifications/unsubscribe-auth/AY4N7ZORVHEQR6FU7T4LNOLXBLO6HANCNFSM6AAAAAAWUUBCNE&source=gmail-imap&ust=1682186468000000&usg=AOvVaw39B_wxa-84rWgUq1We1jRV. You are receiving this because you authored the thread.Message ID: @.***>

67726e commented 1 year ago

At a high-level, this is the flow of the code in the application at-present.

this._cookieBase = `CognitoIdentityServiceProvider.${params.userPoolAppId}`;

_buildCookieAccessTokenKey = (username: string) => `${this._cookieBase}.${username}.accessToken`;
_buildCookieIDTokenKey = (username: string) => `${this._cookieBase}.${username}.idToken`;
_buildCookieRefreshTokenKey = (username: string) => `${this._cookieBase}.${username}.refreshToken`;
_buildCookieScopeKey = (username: string) => `${this._cookieBase}.${username}.tokenScopesString`;
_buildCookieUsernameKey = () => `${this._cookieBase}.LastAuthUser`;

// Assumed that `cookieHeaders[string] => { key: string, value: string, };`
// Bearing in mind that the cookies may not actually exist :)
const cookieUsername = cookieHeaders[this._buildCookieUsernameKey()];
const cookieAccessToken = cookieHeaders[this._buildCookieAccessTokenKey(cookieUsername?.value)];
const cookieIDToken = cookieHeaders[this._buildCookieIDTokenKey(cookieUsername?.value)];
const cookieRefreshToken = cookieHeaders[this._buildCookieRefreshTokenKey(cookieUsername?.value)];

const tokens: Tokens = {
  accessToken: cookieAccessToken.value,
  idToken: cookieIDToken.value,
  refreshToken: cookieRefreshToken.value,
};