Authgear Integration
Overview
This skill helps developers integrate Authgear authentication into their applications quickly and correctly. It provides framework-specific guidance, reusable code templates, and common patterns for:
- Frontend Applications: Protected routes, user profiles, API integration, role-based access control for React, React Native, Flutter, Android, iOS, and more
- Backend Applications: JWT token validation, API authentication, user verification for Python, Node.js, Go, Java, PHP, and ASP.NET servers
Integration Workflow
1. Detect Project Type
Identify the project type by examining:
- Package files:
package.json,pubspec.yaml,build.gradle,Podfile,requirements.txt,pom.xml,composer.json,*.csproj - Project structure: presence of
src/,android/,ios/,lib/,app/,main/directories - Configuration files:
vite.config.js,next.config.js,angular.json,go.mod,appsettings.json
Common project types:
Frontend/Mobile Frameworks:
- React SPA:
package.jsonwithreactandreact-dom, typically withviteorreact-scripts - React Native:
package.jsonwithreact-native,ios/andandroid/directories - Flutter:
pubspec.yamlwithflutterdependency - Android:
build.gradlefiles,AndroidManifest.xml - iOS:
Podfile,.xcodeprojor.xcworkspacefiles, Swift source files - Vue.js:
package.jsonwithvuedependency - Next.js:
package.jsonwithnextdependency
Backend Frameworks:
- Python (Flask/Django/FastAPI):
requirements.txt,setup.py, orpyproject.tomlwith Flask/Django/FastAPI - Node.js (Express):
package.jsonwithexpressor other Node.js server frameworks - Go:
go.modfile,main.goor*.gofiles - Java (Spring Boot):
pom.xmlorbuild.gradlewith Spring Boot dependencies - PHP:
composer.jsonwith PHP dependencies - ASP.NET Core:
*.csprojfile with ASP.NET Core packages
2. Ask User for Configuration
Use AskUserQuestion to gather required information:
{
"questions": [
{
"question": "Do you have an Authgear project setup? If yes, provide your Client ID.",
"header": "Client ID",
"multiSelect": false,
"options": [
{
"label": "I have a Client ID",
"description": "Provide your Authgear Client ID from the portal"
},
{
"label": "Not yet, help me set it up",
"description": "Guide me through creating an Authgear project"
}
]
},
{
"question": "What is your Authgear endpoint URL?",
"header": "Endpoint",
"multiSelect": false,
"options": [
{
"label": "I have an endpoint",
"description": "Provide your Authgear endpoint (e.g., https://myapp.authgear.cloud)"
},
{
"label": "Help me find it",
"description": "Show me where to find my endpoint"
}
]
}
]
}
If user doesn't have Client ID or Endpoint, guide them:
- Visit https://portal.authgear.com
- Create a new project or select existing
- Navigate to Applications → Create Application
- Select appropriate application type (Native App for mobile, SPA for web)
- Configure redirect URIs
- Copy Client ID and Endpoint
3. Install Dependencies
Based on detected framework:
React SPA:
npm install --save --save-exact @authgear/web
React Native:
npm install --exact @authgear/react-native
cd ios && pod install
Flutter:
flutter pub add flutter_authgear
Android:
Add to build.gradle - see references/android.md
iOS:
Via Swift Package Manager: https://github.com/authgear/authgear-sdk-ios.git
Or CocoaPods: pod 'Authgear', :git => 'https://github.com/authgear/authgear-sdk-ios.git'
4. Configure Environment Variables
Create or update .env file (or appropriate config for framework):
React (Vite):
VITE_AUTHGEAR_CLIENT_ID=<CLIENT_ID>
VITE_AUTHGEAR_ENDPOINT=<ENDPOINT>
VITE_AUTHGEAR_REDIRECT_URL=http://localhost:5173/auth-redirect
React (Create React App):
REACT_APP_AUTHGEAR_CLIENT_ID=<CLIENT_ID>
REACT_APP_AUTHGEAR_ENDPOINT=<ENDPOINT>
REACT_APP_AUTHGEAR_REDIRECT_URL=http://localhost:3000/auth-redirect
For React Native, Flutter, Android: credentials typically hardcoded in config or stored in platform-specific secure storage.
5. Implement Core Authentication
Use framework-specific templates from assets/ and detailed guides from references/:
For React:
- Copy
assets/react/UserProvider.tsxtosrc/ - Copy
assets/react/AuthRedirect.tsxtosrc/pages/orsrc/components/ - Copy
assets/react/useAuthgear.tstosrc/hooks/ - Update routing to include
/auth-redirectroute - Wrap app with
UserContextProvider
See references/react.md for complete implementation details.
For React Native:
- Initialize SDK in
App.tsx - Configure platform-specific redirect handling (AndroidManifest.xml, Info.plist)
- Implement authentication flow with session state management
See references/react-native.md for complete implementation details.
For Flutter:
- Add SDK initialization in app state
- Configure platform-specific URL schemes
- Implement authentication UI
See references/flutter.md for complete implementation details.
For Android:
- Add SDK dependency
- Initialize in MainActivity
- Configure redirect activity in manifest
See references/android.md for complete implementation details.
For iOS:
- Add SDK via Swift Package Manager or CocoaPods
- Initialize Authgear instance in app
- Configure custom URI scheme in Info.plist
See references/ios.md for complete implementation details.
6. Implement Requested Features
Based on user requirements, implement common patterns from references/common-patterns.md:
Protected Routes:
- Use
ProtectedRoutecomponent (React) fromassets/react/ProtectedRoute.tsx - Implement navigation guards for React Native/Flutter
- See examples in common-patterns.md
User Profile Page:
- Fetch user info using
authgear.fetchUserInfo() - Display user details (ID, email, phone)
- Add settings button using
authgear.open(Page.Settings)
API Integration:
- Use
authgear.fetch()for automatic token handling - Or manually add Authorization header with
authgear.accessToken - Implement token refresh logic
Role-Based Access:
- Extract roles/permissions from user info
- Create permission checking hooks/utilities
- Conditionally render UI based on roles
7. Add Login/Logout UI
Create UI components for authentication:
Login Button:
// React
import { useAuthgear } from './hooks/useAuthgear';
const LoginButton = () => {
const { login } = useAuthgear();
return <button onClick={login}>Login</button>;
};
Logout Button:
const LogoutButton = () => {
const { logout } = useAuthgear();
return <button onClick={logout}>Logout</button>;
};
Settings Button:
const SettingsButton = () => {
const { openSettings } = useAuthgear();
return <button onClick={openSettings}>Settings</button>;
};
8. Test Integration
For Frontend Applications:
Guide user to test:
- Start development server
- Click login button → should redirect to Authgear
- Complete authentication
- Should redirect back to app at
/auth-redirect - Should then navigate to home page as authenticated user
- Verify protected routes work
- Test logout functionality
For Backend Applications:
Guide user to test:
- Start backend server
- Get a test access token from frontend or Auth API
- Make request to protected endpoint with
Authorization: Bearer <token>header - Should receive successful response with user data
- Test without token → should receive 401 Unauthorized
- Test with expired token → should receive 401 Unauthorized
- Verify user claims are correctly extracted
Backend Integration Workflow
For backend API applications that need to validate JWT access tokens:
1. Ask User for Configuration
Use AskUserQuestion to gather required information:
{
"questions": [
{
"question": "What is your Authgear endpoint URL?",
"header": "Endpoint",
"multiSelect": false,
"options": [
{
"label": "I have an endpoint",
"description": "Provide your Authgear endpoint (e.g., https://myproject.authgear.cloud)"
},
{
"label": "Help me find it",
"description": "Show me where to find my endpoint in the Portal"
}
]
},
{
"question": "What is your Authgear Client ID?",
"header": "Client ID",
"multiSelect": false,
"options": [
{
"label": "I have a Client ID",
"description": "Provide your application's Client ID from the portal"
},
{
"label": "Help me set it up",
"description": "Guide me through creating an application"
}
]
}
]
}
Authgear Endpoint Format:
- Usually looks like:
https://[project-name].authgear.cloud - Or custom domain:
https://auth.yourdomain.com - Should NOT have trailing slash
- Example:
https://myapp.authgear.cloud
If user doesn't have endpoint or Client ID, guide them:
- Visit https://portal.authgear.com
- Select your project or create a new one
- Navigate to Applications → Create Application or select existing
- Select "Machine-to-Machine" or "Single Page Application" type (depending on use case)
- Enable "Issue JWT as access token" in application settings
- Copy the Client ID from application details
- Copy the Endpoint from project settings (format:
https://[project-name].authgear.cloud)
2. Verify Prerequisites
- Enable JWT tokens: Ensure "Issue JWT as access token" is enabled in Authgear Portal for your application
- Token-based auth required: Cookie-based authentication does not support JWT validation
- Note configuration: Have your Authgear Endpoint and Client ID ready
3. Install Backend Dependencies
Based on detected language:
Python:
pip install PyJWT cryptography requests
Node.js:
npm install jwks-rsa jsonwebtoken axios
Go:
go get github.com/lestrrat-go/jwx/v2/jwt
go get github.com/lestrrat-go/jwx/v2/jwk
Java (Maven):
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>9.31</version>
</dependency>
PHP:
composer require firebase/php-jwt guzzlehttp/guzzle
ASP.NET Core:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
4. Implement JWT Validation
Follow language-specific implementation from references/backend-api.md:
Key Steps:
- Fetch JWKS (JSON Web Key Set) from discovery endpoint
- Extract token from
Authorization: Bearer <token>header - Decode token header to get Key ID (
kid) - Find matching public key from JWKS
- Verify signature using RS256 algorithm
- Validate expiration (
exp) and audience (aud) claims - Extract user information from validated claims
Performance Tip: Cache JWKS for 10-60 minutes to avoid fetching on every request
5. Create Authentication Middleware
Implement middleware/decorator to protect endpoints:
Python (Flask):
@require_auth
def protected_endpoint():
user_id = request.user_id
return jsonify({"user_id": user_id})
Node.js (Express):
app.get('/api/profile', verifyToken, (req, res) => {
res.json({ user_id: req.userId });
});
Go:
http.HandleFunc("/api/profile", verifyTokenMiddleware(profileHandler))
Java (Spring Boot):
@GetMapping("/api/profile")
public ResponseEntity<?> getProfile(HttpServletRequest request) {
String userId = (String) request.getAttribute("user_id");
return ResponseEntity.ok(userId);
}
ASP.NET Core:
[Authorize]
[HttpGet("profile")]
public IActionResult GetProfile() {
var userId = User.FindFirst("sub")?.Value;
return Ok(new { user_id = userId });
}
6. Add Protected Endpoints
Create API endpoints that require authentication:
- Extract user ID from validated claims (
subclaim) - Use user ID to fetch user-specific data
- Return appropriate error codes (401 for auth failures)
- Implement role-based access control if needed
7. Test Backend Integration
- Using Authgear SDK's Built-in Fetch (Recommended for Frontend Apps):
If your frontend uses Authgear's JavaScript SDK, use the built-in fetch function:
// Automatically includes Authorization header and refreshes token
authgear
.fetch("http://localhost:3000/api/profile")
.then(response => response.json())
.then(data => console.log(data));
Benefits:
- Automatic Authorization header injection
- Automatic token refresh handling
- No manual token management needed
Note: JavaScript/Web SDK only. Mobile platforms (iOS, Android) must manually call refreshAccessTokenIfNeeded() and construct headers.
- Using cURL (Manual Testing):
Get test token and make request:
# Get token from frontend or use OAuth password grant
curl http://localhost:3000/api/profile \
-H "Authorization: Bearer <VALID_TOKEN>"
-
Test error cases:
- No token → 401 Unauthorized
- Invalid token → 401 Unauthorized
- Expired token → 401 Unauthorized
-
Verify claims extraction:
- Check that user ID and email are correctly extracted
- Verify custom claims are accessible
See references/backend-api.md for complete implementation details, code examples, security best practices, and troubleshooting guides for all supported languages.
Framework-Specific Guides
For detailed implementation instructions, consult these framework-specific references:
Frontend/Mobile:
- React SPA: references/react.md
- React Native: references/react-native.md
- Android: references/android.md
- iOS: references/ios.md
- Flutter: references/flutter.md
Backend:
- Backend API (Python, Node.js, Go, Java, PHP, ASP.NET): references/backend-api.md
Common Patterns
For implementing specific features, see references/common-patterns.md:
- Protected routes and navigation guards
- User profile pages with settings
- API integration with automatic token handling
- Role-based access control
Quick Setup Examples
React SPA - Minimal Setup
// 1. Install
npm install --save --save-exact @authgear/web react-router-dom
// 2. Wrap app with provider (App.tsx)
import { UserContextProvider } from './UserProvider';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import AuthRedirect from './AuthRedirect';
import Home from './Home';
function App() {
return (
<UserContextProvider>
<BrowserRouter>
<Routes>
<Route path="/auth-redirect" element={<AuthRedirect />} />
<Route path="/" element={<Home />} />
</Routes>
</BrowserRouter>
</UserContextProvider>
);
}
// 3. Add login button (Home.tsx)
import { useAuthgear } from './hooks/useAuthgear';
import { useUser } from './UserProvider';
function Home() {
const { login, logout } = useAuthgear();
const { isLoggedIn } = useUser();
return (
<div>
{isLoggedIn ? (
<button onClick={logout}>Logout</button>
) : (
<button onClick={login}>Login</button>
)}
</div>
);
}
React Native - Minimal Setup
// 1. Install
npm install --exact @authgear/react-native
cd ios && pod install
// 2. Initialize in App.tsx
import authgear, { SessionState } from '@authgear/react-native';
import { useEffect, useState } from 'react';
import { Button, Text, View } from 'react-native';
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
useEffect(() => {
authgear.configure({
clientID: '<CLIENT_ID>',
endpoint: '<ENDPOINT>',
}).then(() => {
authgear.delegate = {
onSessionStateChange: (container) => {
setIsLoggedIn(container.sessionState === SessionState.Authenticated);
},
};
});
}, []);
const handleLogin = () => {
authgear.authenticate({ redirectURI: 'com.myapp://host/path' });
};
const handleLogout = () => {
authgear.logout();
};
return (
<View>
{isLoggedIn ? (
<Button title="Logout" onPress={handleLogout} />
) : (
<Button title="Login" onPress={handleLogin} />
)}
</View>
);
}
// 3. Configure AndroidManifest.xml and Info.plist (see references/react-native.md)
Resources
- assets/react/: Ready-to-use React components (UserProvider, AuthRedirect, ProtectedRoute, useAuthgear hook)
- references/: Detailed framework-specific integration guides
- Authgear Documentation: https://docs.authgear.com
- Authgear Portal: https://portal.authgear.com
Important Notes
Frontend Applications:
- Always use environment variables for Client ID and Endpoint (never hardcode in React web apps)
- For mobile apps, configure platform-specific URL schemes in AndroidManifest.xml and Info.plist
- Use
useRefin React 18+ to prevent duplicate authentication in StrictMode - Call
refreshAccessTokenIfNeeded()before using access tokens - Use
authgear.fetch()for automatic token handling in API calls
Backend Applications:
- Enable "Issue JWT as access token" in Authgear Portal settings
- Cache JWKS for 10-60 minutes to improve performance
- Always validate signature, expiration, audience, and issuer claims
- Use HTTPS only - never transmit tokens over HTTP
- Token-based authentication required (cookie-based auth not supported for JWT validation)
- Implement proper error handling for expired and invalid tokens