Skip to content
Related Articles

Related Articles

Google Cloud Platform – Securing Cloud Run REST API using JWT
  • Last Updated : 29 Dec, 2020

If you happen to be building a REST API on Google Cloud Run, securing the API is one of the crucial aspects of it. It is serverless and exposes data from a Cloud SQL database as a REST API. Securing the REST API can be done using JWT. To better understand it, let’s take an example.

Problem Statement:

Suppose there exist an app say TripBuddy, which logs your trips. TripBuddy has built a system for logging client’s trips online. You are a developer working for TripBuddy, a service for logging your trips. You built a REST API to enable users to track their activity from a web and mobile app. It turns out it’s quite easy to build a REST API in Cloud Run. As a bonus, Cloud Run is serverless, so there are no servers to manage. And TripBuddy will only pay-per-call with no fixed costs.


In this article, we’ll see how the company made sure that each user can only access their own logged trips.

You built the REST API in Cloud Run as a proof of concept. Now that it’s working well, you need to address security. A user should only be able to view and edit their own trips, not those of other users. The first thought is that the server would send the user’s ID to the web client. When that user logs in, the web client would then send the user’s ID back to the server when accessing the REST API. 

But you remember that one cannot trust code running on the client. A malicious user could modify the client code so it sends a different user ID than the one it received from the server. You’re back where we started as any client can read any recorded trip.

This is where JWT (JSON Web Tokens) comes into play. When the client app logs in, it gets the user ID from the server signed by the server. The client app then attaches the JSON Web Token to any REST call it makes to the server. 

As part of the JWT standard, the server signs all tokens digitally. If the client app modifies the token and sends it back to the server, the server will know that it was tampered with and can refuse the call.

This means that your code that runs on the server can trust the user ID it gets from the client. You can use that user ID in your SQL code when looking up the user’s recorded trips. 

This sounds great in principle and is equally easy to implement. You might not have experience with cryptography. Whenever you write security-related code like this, it’s best to lean on well-tested libraries. If you do that, there’s less risk of leaving a security hole open.

Fortunately, you do not have to create the JSON Web Token. Google’s servers do that. And when you decode the token, you can use a library provided by Google.

My Personal Notes arrow_drop_up
Recommended Articles
Page :