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)
      • Reauthentication
      • Passwordless Login for Apple App Store Review
      • Change Forgot/Reset Password settings
      • Adjust Phone Number Validation
      • Set Password Expiry
      • Use the OAuth 2.0 State Parameter
      • Setup local development environment for Cookie-based authentication
      • Use Social/Enterprise Login Providers Without AuthUI
    • 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
    • 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
      • Integrate Authgear with Firebase
    • 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
    • Migration
      • Bulk migration
      • Rolling migration
      • Zero-downtime migration
    • Directly accessing Authgear Endpoint
    • Troubleshoot
      • How to Fix SubtleCrypto: digest() undefined Error in Authgear SDK
      • How to Fix CORS Error
  • Design
    • 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
    • Languages and Localization
    • Custom Email and SMS Templates
  • Concepts
    • Identity Fundamentals
    • Authgear use cases
    • User, Identity and Authenticator
  • Security
    • Brute-force Protection
    • Bot Protection
    • Non-HTTP scheme redirect URI
    • Password Strength
  • Authgear ONCE
    • What is Authgear ONCE
    • Install Authgear ONCE on a VM
    • Install Authgear ONCE on Vultr
    • Install Authgear ONCE on Amazon Web Services (AWS)
  • 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
  • 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 toolsNextAuthenticate

Last updated 1 month 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 .

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:

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
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:

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 application server 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.

React:

Vue:

Angular:

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 .

Validate JWT in your application server:

the Authgear portal
https://docs.authgear.com/get-started/single-page-app/react
https://docs.authgear.com/get-started/single-page-app/vue
https://docs.authgear.com/get-started/single-page-app/angular
pre-built user settings page
https://docs.authgear.com/get-started/backend-api/jwt