Authgear
Start BuildingHomePortalCommunity
  • Authgear Overview
  • Get Started
    • 5-Minute Guide
    • Start Building
    • 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
      • Client SDK to make authorized API calls to backend
      • Validate JWT in your backend
      • Forward Authentication to Authgear Resolver Endpoint
    • AI Coding tools
      • Cursor/Windsurf
    • Integration by OIDC
    • Integration by SAML
      • Use Authgear as SAML Identity Provider for Salesforce
      • Use Authgear as SAML Identity Provider for Dropbox
      • SAML Attribute Mapping
  • Authentication and Access
    • Authentication
      • Add Passkeys Login
      • Add WhatsApp OTP Login
      • Add Email Magic Link Login
      • Add Biometric Login
      • Add Anonymous Users
      • Enable Two-Factor Authentication (2FA)
      • Re-authentication
      • Set Password Expiry
      • Change Forgot/Reset Password settings
      • Add authentication to any web page
    • Single Sign-on Overview
      • App2App Login
      • App2Web (Pre-authenticated URLs)
      • Web2App (From Mobile Apps to Browsers)
      • Force Authgear to Show Login Page
      • Single Sign-on with OIDC
      • Single Sign-on with SAML
    • Social/Enterprise Login Providers Overview
      • 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
  • FAQ for Authentication
    • Tips for Apple App Store Review with Passwordless Login
    • Phone Number Validation
    • Skip Login Screen and Direct Users to Enterprise Login
    • Use the OAuth 2.0 State Parameter
    • Local Dev Setup for Connecting to Authgear SaaS in Cookie-based Auth
  • Integration
    • Add custom fields to a JWT Access Token
    • User Profiles
      • What is User Profile
      • Access User Profiles
      • Update User Profiles
      • Profile Custom Attributes
      • Update user profile on sign-up using Hooks
    • Mobile Apps
      • Force authentication on app launch
      • Customize the Login Pop-up / Disable the login alert box
    • Integration with other Software
      • Integrate Authgear with Firebase
      • Integrate with Google Tag Manager
    • FAQ for Integration
      • How to Track User Before and After Signup?
      • What happens with user directly access the Authgear Endpoint?
  • Customization
    • Built-in UI
      • Branding in Auth UI
      • User Settings
      • Privacy Policy & Terms of Service Links
      • Customer Support Link
      • Custom Text
      • Languages and Localization
    • 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
    • Custom Domain
    • Custom Email and SMS Templates
    • Custom Email Provider
    • Custom SMS Provider
      • Twilio
      • Webhook/Custom Script
    • Events and Hooks
      • Event List
      • Webhooks
      • JavaScript / TypeScript Hooks
      • Example: Only Allow Signups from Inside the Corporate Network using Hooks
  • Admin & Operations
    • 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
    • Migration
      • Bulk migration
      • Rolling migration
      • Zero-downtime migration
  • Security
    • Brute-force Protection
    • Bot Protection
    • Non-HTTP scheme redirect URI
    • Password Strength
  • Reference
    • APIs
      • Admin API
        • Authentication and Security
        • API Schema
        • API Queries and Mutations
        • Using global node IDs
        • Retrieving users using Admin API
        • API Examples
          • Generate OTP code
          • Search for users
          • Update user's picture
          • Update user's standard attributes
      • Authentication Flow API
      • OAuth 2.0 and OpenID Connect (OIDC)
        • Supported Scopes
        • UserInfo
      • User Import API
      • User Export API
    • Tokens
      • JWT Access Token
      • Refresh Token
    • Rate Limits
      • Account Lockout
    • Glossary
    • Billing FAQ
  • Authgear ONCE
    • What is Authgear ONCE
    • Install Authgear ONCE on a VM
    • Install Authgear ONCE on Amazon Web Services (AWS)
    • Install Authgear ONCE on Vultr
  • Concepts
    • Identity Fundamentals
    • Authgear use cases
    • User, Identity and Authenticator
  • Client App SDKs
    • Javascript SDK Reference
    • iOS SDK Reference
    • Android SDK Reference
    • Flutter SDK Reference
    • Xamarin SDK Reference
  • Deployment
    • Run with Docker
    • Deploy with Helm chart
    • Authenticating HTTP request with Nginx
    • Configuration
      • Environment Variables
      • authgear.yaml
      • authgear.secrets.yaml
    • Architecture Guides
      • AWS Reference Architecture
      • Azure Reference Architecture
      • Google Cloud Reference Architecture
      • Throughput Scaling Reference
  • Troubleshooting
    • How to Fix SubtleCrypto: digest() undefined Error in Authgear SDK
    • How to Fix CORS Error
Powered by GitBook
On this page
  • Create a project and an application on Authgear
  • Add user login to frontend code
  • Add protection to backend code
  • Protect the API calls in the frontend

Was this helpful?

Edit on GitHub
Export as PDF
  1. Get Started
  2. AI Coding tools

Cursor/Windsurf

PreviousAI Coding toolsNextIntegration by OIDC

Last updated 5 days ago

Was this helpful?

AI-assisted IDEs like Cursor and Windsurf are increasingly popular among developers for enhancing productivity. These tools offer LLM-based agents for code suggestions, debugging, and understanding codebases.

Now, you’ve created an innovative software project consisting of a frontend application and a backend server. By leveraging generative AI with the right prompts, you can integrate robust security features into your project within seconds.

Create a project and an application on Authgear

First, create an account and a project in the the Authgear portal.

In the project creation wizard, choose how your users will perform signup and login. For example:

  • By email with a password

  • By receiving OTP via SMS or WhatsApp

Next, navigate to the “Applications” page and create an application of the type Single Page Application.

There are two values you will need for the subsequent steps:

  • Client ID: An ID to identify your application application with Authgear

  • Endpoint: The URL to identify your Authgear project and allow your application to connect to it.

Under “Authorized Redirect URIs,” add the URL of your local environment with /auth-redirect appended. For example, if your frontend application runs on port 4000, use: http://localhost:4000/auth-redirect there.

Save your changes.

Add user login to frontend code

To integrate login functionality into your frontend code, follow the corresponding documentation based on your framework:

  • React: https://docs.authgear.com/get-started/single-page-app/react

  • Vue: https://docs.authgear.com/get-started/single-page-app/vue

  • Angular: https://docs.authgear.com/get-started/single-page-app/angular

In the chat, select the documentation as context and put in the following prompt.

Use `@authgear/web` package, Integrate Authgear as Authentication provider

Store these in .env for initializing Authgear:

- Authgear Client ID is [CLIENT ID]
- Authgear Endpoint is [Authgear Endpoint]
- Redirect URL is http://localhost:4000/auth-redirect

To show the login status in the home page, use the following prompt to change the appearance of the logged in status and add a button to the pre-built user settings page.

When logged in, show user id (sub) in user info, a logout button and a User settings button in the Home page
User Settings page is opened by `authgear.open(Page.Settings);`

Run the SPA with this prompt to verify the result.

Run dev frontend server at port 4000

Add protection to backend code

In the backend, add the following documentation as context:

  • Validate JWT in your application server: https://docs.authgear.com/get-started/backend-api/jwt

Additional context if the above didn't work

If the IDE failed to fetch the information from the documentation link, paste in the following as context.

Note: The prompt is designed for Express JS (Node JS) backend. For other backend technologies, copy and paste the corresponding code blocks from Validate JWT in your backend for the best result.

# Use JWKS to verify the JWT

**Find the JWKS Endpoint**

Use the following method to get the JWKS URI (you'll need to URI to extract the public signing key from a JWT).

```
const appUrl = ""; //place your authgear app endpoint here
const getJwksUri = async (appUrl) => {
    const config_endpoint = appUrl + "/.well-known/openid-configuration";
    const data = await axios.get(config_endpoint);
    return data.data.jwks_uri;
}
```

**Extract JWT from Request Header**

Use the following code to extract only the token part from a `Bearer [token]` authorization header in your Express app:

```
const express = require("express");
const axios = require("axios");
const node_jwt = require('jsonwebtoken');
const jwksClient = require('jwks-rsa');

const app = express();
const port = 3002;
app.get('/', async (req, res) => {

    const requestHeader = req.headers;
    if (requestHeader.authorization == undefined) {
        res.send("Invalid header");
        return;
    }
    const authorizationHeader = requestHeader.authorization.split(" ");
    const access_token = authorizationHeader[1];

}
```

**Decode Access Token**

Next, decode the access token so that you can extract the JWT `kid` from the result. You'll need this `kid to get the public signing key. Use the following code to decode the JWT:

```
const decoded_access_token = node_jwt.decode(access_token, {complete: true});
```

**Get JWT Signing Keys and Verify the JWT**

Use the following code to extract the JWT public keys then verify the JWT using the keys:

```
const jwks_uri = await getJwksUri(appUrl);
    const client = jwksClient({
        strictSsl: true,
        jwksUri: jwks_uri
    });
    const signing_key = await client.getSigningKey(decoded_access_token.header.kid);

    try {
        const verify = node_jwt.verify(access_token, signing_key.publicKey, { algorithms: ['RS256'] });
        res.send(JSON.stringify(verify))
    }
    catch(error) {
        res.send(error);
    }
```
In the backend, create a protected api `/me`,
When user access with a JWT access token issued by Authgear, return the user id, if not, return 401 unauthorized error

Run the backend server with this prompt to verify the result.

Run dev backend server at port 3000

Similarly you can prompt the chat to protect any API endpoints in the backend.

Protect the API calls in the frontend

Now you have the a protected API in the backend, add a button in the frontend to test it out.

Include the corresponding frontend SPA docs to the "context" added in the previous step. Then use the following prompt to add a button the test the API call:

In the frontend, show a button to test the protected api `/me` both before and after logout. Use the `authgear.fetch("URL")` to call the API.

Run both the frontend and backend servers simultaneously. Your frontend should now feature a button that calls the protected API. Logged-in users will see their user ID retrieved successfully, while logged-out users will encounter an error message.