Deploying a web app with JWT authorization in Yandex API Gateway and authentication in Firebase
- Prepare your cloud
- Create a project and set up Google OAuth in Google Cloud
- Set up authentication in Firebase
- Complete Google resource configuration
- Create an API gateway
- Create web app files
- Deploy Yandex Cloud resources and upload the web app to an Object Storage bucket
- Test the created app
- How to delete the resources you created
In this tutorial, you will learn how to implement authentication and authorization based on OAuth 2.0
- Firebase external authentication service.
- Simple REST API deployed as API Gateway.
- Static website deployed in a Yandex Object Storage bucket.
To deploy your web app:
- Prepare your cloud.
- Create a project and set up Google OAuth in Google Cloud.
- Set up authentication in Firebase.
- Complete Google resource configuration.
- Create an API gateway.
- Create web app files.
- Deploy Yandex Cloud resources and upload the web app to a bucket.
- Test the created app.
If you no longer need the resources you created, delete them.
Prepare your cloud
Sign up for Yandex Cloud and create a billing account:
- Go to the management console
and log in to Yandex Cloud or create an account if you do not have one yet. - On the Yandex Cloud Billing
page, make sure you have a billing account linked and it has theACTIVE
orTRIAL_ACTIVE
status. If you do not have a billing account, create one.
If you have an active billing account, you can go to the cloud page
Learn more about clouds and folders.
Required paid resources
The infrastructure support cost for running the web app includes:
- Fee for data storage in a bucket and operations with data (see Object Storage pricing).
- Fee for using the API gateway (see API Gateway pricing).
Create a project and set up Google OAuth in Google Cloud
Set up Google OAuth:
- Log in to the Google Cloud Console
and create a new project. - Go to API & Services → OAuth consent screen, select
External
as the app type, and click Create. - Under OAuth consent screen, enter the app name and your email address in the User support email and Developer contact information fields. Click Save and continue.
- Under Scopes, click Add or Remove Scopes and add the
openid
,/auth/userinfo.email
, and/auth/userinfo.profile
scopes. Click Update → Save and continue. - Under Test users, specify your email address. Finish creating your app.
- In the API & Services → Credentials tab, click Create credential and select
OAuth client ID
. SpecifyWeb application
as the app type. - Confirm the app creation and save the
Client ID
andClient secret
.
Set up authentication in Firebase
- Log in to the Firebase Console
and create a new project. - Go to Authentication → Sign-in method → Custom providers and select
OpenID Connect
. - Confirm the selection of
OpenID Connect
. - Enter the provider name as well as the
Client ID
andClient secret
you obtained in the previous step. Fill in the Issuer field (for Google OAuth, specifyhttps://accounts.google.com
). - Save the
Callback URL
and complete the OpenID setup.
Complete Google resource configuration
Google Console:
- In the API & Services → Credentials tab, click the name of the created client.
- Add the Callback URL from Firebase you obtained in the previous step to the Authorized redirect URIs list. Save your changes.
Firebase:
- Go to Project Overview → Project settings.
- Create a web app in the
General
tab. Specify the app name and click Register App. - Save the app configuration generated under
firebaseConfig
.
Create an API gateway
-
In the management console
, select the folder where you want to create an API gateway. -
In the list of services, select API Gateway.
-
Click Create API gateway.
-
In the Name field, enter
jwt-api-gw
. -
In the Specification section, add the specification:
openapi: 3.0.0 info: title: Sample API version: 1.0.0 paths: /: get: x-yc-apigateway-integration: type: http url: https://oauth2.googleapis.com/tokeninfo method: GET query: id_token: '{token}' parameters: - name: token in: query required: true schema: type: string security: - OpenIdAuthorizerScheme: [ ] components: securitySchemes: OpenIdAuthorizerScheme: type: openIdConnect x-yc-apigateway-authorizer: type: jwt jwksUri: https://www.googleapis.com/oauth2/v3/certs identitySource: in: query name: token issuers: - https://accounts.google.com requiredClaims: - email
-
Click Create.
If you do not have the Yandex Cloud command line interface yet, install and initialize it.
The folder specified in the CLI profile is used by default. You can specify a different folder using the --folder-name
or --folder-id
parameter.
-
Save the following specification to the
jwt-auth.yaml
file:openapi: 3.0.0 info: title: Sample API version: 1.0.0 paths: /: get: x-yc-apigateway-integration: type: http url: https://oauth2.googleapis.com/tokeninfo method: GET query: id_token: '{token}' parameters: - name: token in: query required: true schema: type: string security: - OpenIdAuthorizerScheme: [ ] components: securitySchemes: OpenIdAuthorizerScheme: type: openIdConnect x-yc-apigateway-authorizer: type: jwt jwksUri: https://www.googleapis.com/oauth2/v3/certs identitySource: in: query name: token issuers: - https://accounts.google.com requiredClaims: - email
-
Run this command:
yc serverless api-gateway create \ --name jwt-api-gw \ --spec=jwt-auth.yaml
Where:
--name
: API gateway name.--spec
: Specification file.
Result:
done (29s) id: d5dug9gkmu187i******** folder_id: b1g55tflru0ek7******** created_at: "2020-06-17T09:20:22.929Z" name: jwt-api-gw status: ACTIVE domain: d5dug9gkmu187i********.apigw.yandexcloud.net log_group_id: ckghq1hm19********
If you don't have Terraform, install it and configure the Yandex Cloud provider.
-
In the configuration file, describe the API gateway parameters:
resource "yandex_api_gateway" "jwt-api-gateway" { name = "jwt-api-gw" spec = <<-EOT openapi: 3.0.0 info: title: Sample API version: 1.0.0 paths: /: get: x-yc-apigateway-integration: type: http url: https://oauth2.googleapis.com/tokeninfo method: GET query: id_token: '{token}' parameters: - name: token in: query required: true schema: type: string security: - OpenIdAuthorizerScheme: [ ] components: securitySchemes: OpenIdAuthorizerScheme: type: openIdConnect x-yc-apigateway-authorizer: type: jwt jwksUri: https://www.googleapis.com/oauth2/v3/certs identitySource: in: query name: token issuers: - https://accounts.google.com requiredClaims: - email EOT }
Where:
name
: API gateway name.spec
: API gateway specification.
For more information about the
yandex_api_gateway
resource parameters in Terraform, see the relevant provider documentation . -
Create resources:
-
In the terminal, change to the folder where you edited the configuration file.
-
Make sure the configuration file is correct using the command:
terraform validate
If the configuration is correct, the following message is returned:
Success! The configuration is valid.
-
Run the command:
terraform plan
The terminal will display a list of resources with parameters. No changes are made at this step. If the configuration contains errors, Terraform will point them out.
-
Apply the configuration changes:
terraform apply
-
Confirm the changes: type
yes
in the terminal and press Enter.
-
This will create an API gateway in the specified folder.
To create an API gateway, use the create REST API method for the ApiGateway resource or the ApiGatewayService/Create gRPC API call.
Create web app files
-
Clone the repository
with the app source code:git clone https://github.com/yandex-cloud-examples/yc-serverless-apigw-jwt-authorizer-firebase.git
-
Open the
src/App.js
file using a text editor and specify the following parameters:firebaseConfig
: Firebase configuration for your app that you saved when completing Google resource configuration.providerId
: ID of the OpenID Connect provider previously created in Firebase, inoidc.<provider_name>
format.apiGwDomain
: Service domain of the API gateway you created earlier.
-
Install Node.js
and the npm package manager: The package manager will be installed automatically during Node.js installation. -
In the folder with your app:
-
Install react-scripts in your project and add it to
devDependencies
in thepackage.json
file:npm install react-scripts --save-dev
-
Run your app build:
npm run build
Result:
File sizes after gzip: 96.05 kB build\static\js\main.de7af71f.js 672 B build\static\css\main.021818e9.css The project was built assuming it is hosted at /. You can control this with the homepage field in your package.json. The build folder is ready to be deployed.
-
Deploy Yandex Cloud resources and upload the web app to an Object Storage bucket
Deploy a static website.
-
Create an Object Storage bucket:
Management consoleCLITerraformAPI- In the management console
, select the folder you want to create a bucket in. - Select Object Storage.
- Click Create bucket.
- On the bucket creation page:
- Enter a name for the bucket:
bucket-for-tutorial
. - In the Object read access field, select
Public
. - Click Create bucket to complete the operation.
- Enter a name for the bucket:
If you do not have the Yandex Cloud command line interface yet, install and initialize it.
The folder specified in the CLI profile is used by default. You can specify a different folder using the
--folder-name
or--folder-id
parameter.-
Run the following command:
yc storage bucket create \ --name bucket-for-tutorial \ --public-read
Where:
--name
: Bucket name.--public-read
: Flag to enable public access to read bucket objects.
Result:
name: bucket-for-tutorial folder_id: b1gmit33******** anonymous_access_flags: ... versioning: VERSIONING_DISABLED acl: {} created_at: "2023-06-08T11:57:49.898024Z"
If you don't have Terraform, install it and configure the Yandex Cloud provider.
-
In the configuration file, describe the resource parameters:
... resource "yandex_iam_service_account" "sa" { name = "<service_account_name>" } resource "yandex_resourcemanager_folder_iam_member" "sa-editor" { folder_id = "<folder_ID>" role = "storage.editor" member = "serviceAccount:${yandex_iam_service_account.sa.id}" } resource "yandex_iam_service_account_static_access_key" "sa-static-key" { service_account_id = yandex_iam_service_account.sa.id description = "static access key for object storage" } resource "yandex_storage_bucket" "test" { access_key = yandex_iam_service_account_static_access_key.sa-static-key.access_key secret_key = yandex_iam_service_account_static_access_key.sa-static-key.secret_key bucket = "bucket-for-tutorial" acl = "public-read" } ...
Where:
yandex_iam_service_account
: Description of the service account to create and use the bucket:name
: Service account name.
yandex_storage_bucket
: Bucket description:bucket
: Bucket name.acl
: Bucket access settings.
For more information about the
yandex_storage_bucket
resource parameters in Terraform, see the provider documentation . -
Create resources:
-
In the terminal, change to the folder where you edited the configuration file.
-
Make sure the configuration file is correct using the command:
terraform validate
If the configuration is correct, the following message is returned:
Success! The configuration is valid.
-
Run the command:
terraform plan
The terminal will display a list of resources with parameters. No changes are made at this step. If the configuration contains errors, Terraform will point them out.
-
Apply the configuration changes:
terraform apply
-
Confirm the changes: type
yes
in the terminal and press Enter.
-
This will create a bucket in the specified folder.
To create a bucket, use the create REST API method for the Bucket resource, the BucketService/Create gRPC API call, or the create S3 API method.
- In the management console
-
Upload objects to the Object Storage bucket:
Management console- In the management console
, select the folder to upload objects to. - Select Object Storage.
- Click
bucket-for-tutorial
. - Click Upload and select the previously generated objects in the
build
folder. - The management console displays all the objects selected for uploading and prompts you to select a storage class. The default storage class is defined in the bucket settings.
- Click Upload.
- Refresh the page.
In the management console, the information about the number of objects in the bucket and used up space is updated with a few minutes delay.
- In the management console
-
Set up static website hosting:
Management consoleCLITerraformAPI- In the management console
, go tobucket-for-tutorial
. - In the left-hand panel, select Settings.
- On the Website tab:
- Select
Hosting
. - In the Home page field, specify the absolute path to the file of the website home page,
index.html
. - In the Error page field, specify the absolute path to the file to display in case of 4xx errors,
error.html
.
- Select
- Click Save.
- In the Link field, copy your website's URL.
If you do not have the Yandex Cloud command line interface yet, install and initialize it.
The folder specified in the CLI profile is used by default. You can specify a different folder using the
--folder-name
or--folder-id
parameter.-
Create the
setup.json
file with hosting settings in JSON format.{ "index": "index.html", "error": "error404.html" }
Where:
index
: Absolute path to the file of the website home page.error
: Absolute path to the file the user will see in case of 4xx errors.
-
Run this command:
yc storage bucket update --name bucket-for-tutorial \ --website-settings-from-file setup.json
Where:
--name
: Bucket name.--website-settings-from-file
: Path to the redirect configuration file.
Result:
name: my-bucket folder_id: b1gjs8dck******** default_storage_class: STANDARD versioning: VERSIONING_SUSPENDED max_size: "10737418240" acl: {} created_at: "2022-12-14T08:42:16.273717Z"
If you don't have Terraform, install it and configure the Yandex Cloud provider.
To set up a redirect for all requests:
-
Open the Terraform configuration file and add the
redirect_all_requests_to
parameter to theyandex_storage_bucket
resource description:... resource "yandex_storage_bucket" "test" { access_key = yandex_iam_service_account_static_access_key.sa-static-key.access_key secret_key = yandex_iam_service_account_static_access_key.sa-static-key.secret_ke bucket = "bucket-for-tutorial" acl = "public-read" website { index_document = "index.html" error_document = "error.html" } } ...
Where:
website
: Website parameters:index_document
: Absolute path to the website home page file. This is a required parameter.error_document
: Absolute path to the file the user will see in case of4xx
errors. This is an optional parameter.
For more information about the
yandex_storage_bucket
resource parameters in Terraform, see the provider documentation . -
Create resources:
-
In the terminal, change to the folder where you edited the configuration file.
-
Make sure the configuration file is correct using the command:
terraform validate
If the configuration is correct, the following message is returned:
Success! The configuration is valid.
-
Run the command:
terraform plan
The terminal will display a list of resources with parameters. No changes are made at this step. If the configuration contains errors, Terraform will point them out.
-
Apply the configuration changes:
terraform apply
-
Confirm the changes: type
yes
in the terminal and press Enter.
-
This will set up hosting in the bucket.
To set up hosting for a static website, use the update REST API method for the Bucket resource, the BucketService/Update gRPC API call, or the upload S3 API method.
- In the management console
-
Add this URL to the list of authorized domains in Firebase:
- Go to Authentication → Settings → Authorized domains.
- Click Add domain and paste the copied URL.
Test the created app
- Access the static website via the URL obtained when setting up website hosting and click Call API Gateway without authorization. Make sure the response is
Got error: Request failed with status code 401
. - To log in to the website, click Log in.
- Once authorized, click Call API Gateway again. Make sure your call is processed successfully and you get information about the authorized user.
How to delete the resources you created
To stop paying for the resources you created: