awslabs / cognito-at-edge

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

Tokens exposed to users via cookies: security question #31

Closed johfer closed 2 years ago

johfer commented 2 years ago

Hi, if I understand https://aws.amazon.com/blogs/mobile/understanding-amazon-cognito-user-pool-oauth-2-0-grants/ correctly, in the preferred (from a security perspective) "Authorization code grant" flow, the actual tokens (id, access, refresh) are never exposed to the user.

However, in _getRedirectResponse in cognito-at-edge, those tokens are set as cookies, ending up in the user's browser. Does this compromise the security of the flow (albeit slightly), i.e. does using cognito-at-edge implicitly change the "Authorization code grant" flow into something that's equivalent to the less-secure "Implicit grant" flow?

jeandek commented 2 years ago

Hi @johfer, thanks for asking this interesting question.

In terms of security, Cognito@Edge is comparable to the implicit grant flow since the user pool tokens are returned to the user as cookies. Internally, it makes a call to POST /oauth2/token similar what is done in the authorization code grant flow, but only once.

If you wanted to follow the authorization code grant flow, you would need to stop returning the tokens as cookies and expecting an ID token to be sent with each request. Instead, you would treat requests with the code parameter (line 212) as the standard authenticated case. You would have to ensure that the OAuth code is valid on each request by calling POST /oauth2/token within the Lambda function.

There is a tradeoff between latency and security. The implicit flow will be faster, unless your application can cache the response from the POST /oauth2/token request (not sure that's a good practice though). When using CloudFront and Lambda@Edge to serve a React web app caching is not an option and my sensitive data is retrieved through some other means (e.g. an API) so I would settle for the implicit grant. If I was building a Java application, I would probably go with the more secure authorization code grant.

I hope that helps clear things up. I'll discuss this with the team to see if we want to support both flows in the future.

Regards, Jean

johfer commented 2 years ago

Hi @jeandek , great, thanks for this insightful response, helps/confirms my understanding of the subject.

Best wishes, Johannes