DEV Community

Radek
Radek

Posted on

Amplify API Auth with Cognito Custom Scopes - overview and temporary solution

Recently I have faced a truly annoying problem, whose understanding took me 1 week. Here is a simple overview of the problem and potential solution which I found:

Overview

Amplify is a tool which helps frontend developers create and manage backend resources. It comes with predefined libraries which take care of implementing communication with AWS Backend. With Amplify, we can easily create authorization which work with Cognito and Rest API requests for API Gateway. The problem begin when we want to use Cognito User pool authorization for Rest API.

Problem

Due to AWS Docs to restrict Rest API with Cognito User pool you should create Resource server and protect your endpoints with Custom scope. However, Amplify, and even more precisely AndroidSDK, doesn't return Custom Scopes if Hosted UI is not used --> link to Issue
If you don't want to use Hosted UI, currently you cannot use Custom Scopes.

First solution - stick with what you got

Use aws.cognito.signin.user.admin scope to protect endpoints. It's not perfect solution, it can work only if all your endpoints requires same permissions. It's still better than not protecting your endpoints at all. If you don't use any scope at API Endpoints, by default API Gateway would assume that openid scope is used, which will result in authenticating to API with ID token instead of Access Token.

Second solution - do it yourself

If your project requires Custom Scopes and you really don't want to use Hosted UI for your mobile app, you have to implement token management yourself. You can do it by sending a request for Grant Code and then sending another request for all tokens with Cognito credentials in the body. You also have to take care of proper protection of all requests. It's harder because you have to take care of token management by yourself (as well, you could not use Amplify/AWS SDK at all).

Third solution - move to Hosted UI

It is what it is. The simplest solution would be using Hosted UI since there are no other options right now. Let's hope that AWS will provide further improvements in the nearest future.

None of this solution is perfect, and the most recommended would be moving to Hosted UI, which will result in lower user experience.

Top comments (0)