Authenticate and Route API vs. App Traffic Based on User Agent
If you're serving both web app and API services from the same hostname, you can use ngrok and the Traffic Policy engine to:
- Automatically enforce OAuth or JWT validation on browser or curl/machine-to-machine traffic, respectively.
- Route only authenticated requests to your upstream app and API services.
This way, your users can hit the same hostname, authenticate themselves, and get the response they expect, while you know that all your services are protected.
1. Set up your JWT provider
You can use any provider/issuer, but we have a guide for defining an API and generating tokens with Auth0.
2. Start internal endpoints for your services
Start an internal Agent Endpoint, replacing $PORT
based on where your app service listens.
You can also use one of our SDKs or the Kubernetes Operator.
Loading…
Start a second endpoint for your API service.
Loading…
3. Reserve a domain
Navigate to the Domains section of the ngrok dashboard and click New + to reserve a free static domain like https://your-service.ngrok.app
or a custom domain you already own.
4. Create a Cloud Endpoint
Navigate to the Endpoints section of the ngrok dashboard, then click New + and Cloud Endpoint.
Now you have a Cloud Endpoint with the URL like https://your-service.ngrok.app
.
5. Add JWT validation, OAuth, and routing with Traffic Policy
Apply this policy to your public Cloud Endpoint. You may need to change:
$YOUR_JWT_DOMAIN
: The domain name for your tenant at your JWT provider—for example, with Auth0, it looks something likehttps://example.us.auth0
.$YOUR_EMAIL_DOMAIN
: The domain name associated with your organization's Google accounts for OAuth checks.
Loading…
What's happening here?
In the first section, Traffic Policy checks whether the request's user agent comes from an API user, then applies the jwt-validation
action.
If the request has the appropriate Authorization: Bearer …
header, then ngrok forwards it to your API service.
In the second section, Traffic Policy checks whether the user agent is from a human/browser, then asks them to authenticate with Google's OAuth.
If the account they sign into matches $YOUR_EMAIL_DOMAIN
, then ngrok forwards it to your web app service.
In all other cases, ngrok returns a 403 Forbidden response because the request was not properly authenticated.
6. Try out your endpoint
-
In your browser: https://your-service.ngrok.app
-
In your terminal, using a valid JWT from your provider:
Loading…
What's next?
- Read more about Traffic Policy and its core concepts.
- Explore all the configuration options in the
jwt-validate
andoauth
actions. - View your traffic in Traffic Inspector.