Authgear
Start BuildingHomePortalCommunity
  • Authgear Overview
  • Get Started
    • Start Building
    • 5-Minute Guide
    • Single-Page App
      • JavaScript (Web)
      • React
      • Angular
      • Vue
    • Native/Mobile App
      • iOS SDK
      • Android SDK
        • Android Kotlin coroutine support
        • Android OKHttp Interceptor Extension (Optional)
      • Flutter SDK
      • React Native SDK
      • Ionic SDK
      • Xamarin SDK
      • Using Authgear without SDK (Client side)
    • Regular Web App
      • Express
      • Next.js
      • Python Flask App
      • Java Spring Boot
      • ASP.NET Core MVC
      • Laravel
      • PHP
    • Backend/API Integration
      • Validate JWT in your application server
      • Forward Authentication to Authgear Resolver Endpoint
    • AI Coding tools
      • Cursor/Windsurf
  • How-To Guides
    • Authenticate
      • Add Passkeys Login
      • Add WhatsApp OTP Login
      • Add Email Magic Link Login
      • Add Biometric Login
      • Add Anonymous Users
      • Add authentication to any web page
      • Enable Two-Factor Authentication (2FA)
      • How to Use the OAuth 2.0 State Parameter
      • Reauthentication
      • How to Use Social/Enterprise Login Providers Without AuthUI
      • Passwordless Login for Apple App Store Review
      • Setup local development environment for Cookie-based authentication
      • Forgot/Reset Password settings
      • Phone number validation
      • Set Password Expiry
    • Single Sign-on
      • App2App Login
      • Pre-authenticated URLs
      • SSO between Mobile Apps / Websites
      • Force Authgear to Show Login Page
      • Single Sign-On with OIDC
      • Single Sign-On with SAML
        • Use Authgear as SAML Identity Provider for Salesforce
        • Use Authgear as SAML Identity Provider for Dropbox
        • SAML Attribute Mapping
    • Social Login / Enterprise Login Providers
      • Social Login Providers
        • Connect Apps to Apple
        • Connect Apps to Google
        • Connect Apps to Facebook
        • Connect Apps to GitHub
        • Connect Apps to LinkedIn
        • Connect Apps to WeChat
      • Enterprise Login Providers
        • Connect Apps to Azure Active Directory
        • Connect Apps to Microsoft AD FS
        • Connect Apps to Azure AD B2C
      • Force Social/Enterprise Login Providers to Show Login Screen
    • Built-in UI
      • Branding in Auth UI
      • User Settings
      • Privacy Policy & Terms of Service Links
      • Customer Support Link
      • Custom Text
    • Custom UI
      • Authentication Flow API
      • Implement Authentication Flow API using Express
      • Implement Authentication Flow API using PHP
      • Add Custom Login/Signup UI to Native Apps
      • Manually Link OAuth Provider using Account Management API
      • Implement a custom account recovery UI using Authentication Flow API
    • Integrate
      • Add custom fields to a JWT Access Token
      • User Analytics by Google Tag Manager
      • Track User Before and After Signup
      • Custom domain
      • Custom Email Provider
      • Custom SMS Provider
        • Twilio
        • Webhook/Custom Script
    • Monitor
      • Audit Log For Users Activities
      • Audit Log for Admin API and Portal
      • Analytics
    • User Management
      • Account Deletion
      • Import Users using User Import API
      • Export Users using the User Export API
      • Manage Users Roles and Groups
      • How to Handle Password While Creating Accounts for Users
    • User Profiles
      • What is User Profile
      • Access User Profiles
      • Update User Profiles
      • Profile Custom Attributes
      • Update user profile on sign-up using Hooks
    • Events and Hooks
      • Event List
      • Webhooks
      • JavaScript / TypeScript Hooks
      • Only Allow Signups from Inside the Corporate Network using Hooks
    • Mobile Apps
      • Use SDK to make authorized API calls to backend
      • Force authentication on app launch
      • Customize the Login Pop-up / Disable the login alert box
    • Languages and Localization
    • Custom Email and SMS Templates
    • Directly accessing Authgear Endpoint
    • Migration
      • Bulk migration
      • Rolling migration
      • Zero-downtime migration
    • Troubleshoot
      • How to Fix SubtleCrypto: digest() undefined Error in Authgear SDK
      • How to Fix CORS Error
  • Concepts
    • Identity Fundamentals
    • Authgear use cases
    • User, Identity and Authenticator
  • Security
    • Brute-force Protection
    • Bot Protection
    • Non-HTTP scheme redirect URI
    • Password Strength
  • Reference
    • APIs
      • Admin API
        • Authentication and Security
        • API Schema
        • Admin API Examples
        • Using global node IDs
        • Retrieving users using Admin API
        • User Management Examples
          • Search for users
          • Update user's standard attributes
          • Update user's picture
          • Generate OTP code
      • Authentication Flow API
      • OAuth 2.0 and OpenID Connect (OIDC)
        • UserInfo
        • Supported Scopes
      • User Import API
      • User Export API
    • Tokens
      • JWT Access Token
      • Refresh Token
    • Glossary
    • Billing FAQ
    • Rate Limits
      • Account Lockout
  • Client App SDKs
    • Javascript SDK Reference
    • iOS SDK Reference
    • Android SDK Reference
    • Flutter SDK Reference
    • Xamarin SDK Reference
  • Deploy on your Cloud
    • Running locally with Docker
    • Deploy with Helm chart
    • Authenticating HTTP request with Nginx
    • Configurations
      • Environment Variables
      • authgear.yaml
      • authgear.secrets.yaml
    • Reference Architecture Diagrams
      • Google Cloud Reference Architecture
      • Azure Reference Architecture
      • AWS Reference Architecture
      • Throughput Scaling Reference
Powered by GitBook
On this page
  • How to Prevent or Allow Signups Using Webhooks
  • Step 1: Configure Webhook on Authgear Portal
  • Step 2: Create an Endpoint
  • Step 3: Read Data from Webhook Request
  • Only Allow Signups from Inside the Corporate Network using JavaScript/TypeScript Hooks
  • Step 1: Configure TypeScript Hook on Authgear Portal
  • Step 2: Write the JavaScript for the Hook
  • Step 3: Test the Hook

Was this helpful?

Edit on GitHub
  1. How-To Guides
  2. Events and Hooks

Only Allow Signups from Inside the Corporate Network using Hooks

PreviousJavaScript / TypeScript HooksNextMobile Apps

Last updated 1 year ago

Was this helpful?

Authgear Webhook is a feature that sends notifications in the form of HTTP requests to an external URL that you specify when certain events occur. For example, Webhook can send the user.pre_create event just before a new user is created.

Webhooks also listen for response from your external services. For , this response determines if the process that triggered the event should continue to completion or be terminated. In this post, we'll use a blocking event and a custom webhook endpoint to restrict user signup to only devices from inside a corporate network.

How to Prevent or Allow Signups Using Webhooks

Configuring a webhook for the user.pre-created event will prevent Authgear from creating new users if your webhook endpoint returns is_allowed: false in its response. In contrast, a new user will be created successfully when the endpoint returns is_allowed: true in its response.

We will be using this behavior to prevent users from outside a corporate network from signing up by checking their IP address (which is provided in the payload of the webhook HTTP request from Authgear). When the IP address matches a specified allowed IP address, we set the value for is_allowed to true. Otherwise, we return false.

The following tutorial shows detailed steps for allowing signups from inside a corporate network only.

Step 1: Configure Webhook on Authgear Portal

In this step, we'll create a webhook for the User pre-create event in the Authgear Portal. To do that, login to the Authgear Portal and navigate to Advance > Hooks. Next, under Blocking Events section, click on Add, then select Webhook as the type and User pre-create as the Event.

Enter the full URL that points to the page that will be receiving and processing the webhook requests in the Endpoint text field.

Once you're done, click on the Save button at the top.

Step 2: Create an Endpoint

You'll need to create an endpoint in your preferred programming language or framework and host it online. For this tutorial, we'll be creating a basic Express.js endpoint.

Create a new Express.js project and add the following code to app.js:

const express = require("express");
const app = express();
const bodyParser = require('body-parser');
const port = process.env.PORT || 3002;
app.use(bodyParser.json());


app.post('/', (request, response) => {

    response.status(200).send(
        {
            "is_allowed": false,
            "reason": "some reason",
            "title": "some title"
          }
    );
});

app.listen(port, () => {
    console.log("server started!");
});

Let's walk through what the above code will do:

  • Express creates an endpoint that accepts POST requests. (Note that the Authgear webhook only sends POST HTTP requests and your endpoint must support HTTPS).

  • Deploying the above code and pointing your Authgear webhook endpoint to it should prevent any user from signing up.

  • This is because the code returns is_allowed: false as a response to the Webhook. Hence terminating the signup process.

  • You can also state a more descriptive reason for termination in the endpoint response using the reason field.

Step 3: Read Data from Webhook Request

Authgear webhooks send data to the endpoint URL to enable developers to build custom features and more. In this step, we'll read the data from the User pre-created event call and get the IP address for the user trying to register.

To read the request body and output the value to the console add the following code to app.js on a new line just above response.status(200)...

const requestPayload = request.body;
console.log(requestPayload)

Attempting to register a new user again should print JSON data similar to this to your endpoints console:

{
    id: '0000000000022b55',
    seq: 142165,
    type: 'user.pre_create',
    payload: {
      user: {
        id: '413fe869-dba2-43a8-b671-95fd471b7950',
        created_at: '2023-08-14T03:44:36.383367Z',
        updated_at: '2023-08-14T03:44:36.473456Z',
        is_anonymous: false,
        is_verified: true,
        is_disabled: false,
        is_deactivated: false,
        is_anonymized: false,
        can_reauthenticate: true,
        standard_attributes: [Object],
        x_web3: [Object]
      },
      identities: [ [Object] ]
    },
    context: {
      timestamp: 1691984676,
      user_id: '413fe869-dba2-43a8-b671-95fd471b7950',
      triggered_by: 'user',
      audit_context: null,
      preferred_languages: [ 'en-US', 'en' ],
      language: 'en',
      ip_address: '123.456.78.009',
      user_agent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/116.0',
      app_id: 'my_test_app'
    }
  }

The data we're interested in for this example is ip_address in the context object (context.ip_address). We'll use this IP address to determine whether a user is inside the corporate network.

Now, update app.js so that it returns is_allowed: true when the user's IP address is within the corporate network's IP address.

The code for app.js should look like this after the modification:

app.post('/', (request, response) => {

    const requestPayload = request.body;
    console.log(requestPayload)

    const allowedIp = '123.456.78.009'; //replace the value with the corporate network IP address 
    if (requestPayload.context.ip_address == $orgIp) {

        //this user is from the organisation network, continue with sign up.
        response.status(200).type('json').send(
            {
                "is_allowed": true
              }
        );

    } else {
        //user has an IP address outside of the organisation network so disallow sign up.
        response.status(200).type('json').send(
            {
                "is_allowed": false,
                "reason": "You are not allow to sign up to this organisation",
                "title": "Sign-up not allowed!"
              }
        )
    }
    
});

You should replace the value for allowedIp with the IP address you wish to allow.

At this point, if you deploy your endpoint and try signing up from the allowed IP the process should complete without issue, and you've successfully implemented signups only from a corporate network.

Only Allow Signups from Inside the Corporate Network using JavaScript/TypeScript Hooks

Step 1: Configure TypeScript Hook on Authgear Portal

Navigate to Advance > Hooks in the Authgear portal. Next, click on Add under the Blocking Events section. Or, modify the previous webhook.

Select TypeScript as the type and User pre-create as the Event.

The third field in a TypeScript hook is different from a regular webhook. The field allows you to enter JavaScript code that the hook can execute when an event is triggered.

You can click on the Edit Script button near the Script field to open the hook script editor.

Step 2: Write the JavaScript for the Hook

Modify the code in the script editor to the following:

export default async function (e: EventUserPreCreate): Promise<HookResponse> {
  // Write your hook with the help of the type definition.
  const allowedIp = "123.456.78.009";
  if (e.context.ip_address == allowedIp) {
    return {
      is_allowed: true,
    };
  } else {
    return {
      is_allowed: false,
      reason: "You are not allow to sign up to this organisation",
      title: "Sign-up not allowed!",
    };
  }
}

Make sure to update the value for allowedIp to the IP address you wish to allow.

Once you're done, click on Finish Editing to return to the Hooks configuration page. Save your new hook by clicking on the Save button at the top of the configuration page.

Step 3: Test the Hook

To test that your TypeScript hook is working properly, try signing up a new user from the IP address you specified earlier. Also, try signing up outside that IP address to see if everything works as expected.

Authgear offers an alternative for regular webhooks called the . This kind of hook makes it possible to implement our earlier solution without hosting an external endpoint. In the following section, we'll walk through the steps for allowing signups from inside a corporate network only using the Typescript hook.

JavaScript/TypeScript hooks
blocking events