Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Manage users and their access
Loading...
Loading...
Loading...
Loading...
You need to protect a JavaScript SPA application that runs entirely in a browser
Integrate Authgear to your website with the Web SDK
This guide uses the Authgear Web SDK for integrating Authgear with a Web app. Supported browsers include:
Last 2 Firefox major versions
Last 2 Chrome major versions
Last 2 Edge major versions
Last 3 Safari major versions
From the Project listing, create a new Project or select an existing Project. After that, we will need to create an application in the project.
The SDK must be properly configured before use. Call the configure
method every time your page loads up.
Token-based authentication
sessionType
should be set to refresh_token
Cookie-based authentication
endpoint
must be a custom domain endpoint
sessionType
should be set to cookie
When the user clicks login/signup on your website, make a start authorization call to redirect them to the login/signup page.
By default, Authgear will not ask user to login again if user has already logged in. You can optionally set prompt
to login
if you want the user always reach the login page and login again.
After the user authenticates on the login page, the user will be redirected to the redirectURI
with a code
parameter in the URL query. In the redirectURI
of your application, make a finish authorization call to handle the authentication result. This will attempt to exchange the code
for the access token and user info.
Once authorization succeed, the application should navigate the user to other URL such as the user's home page and remove the code
query parameters.
Now, your user is logged in!
When you start launching the application. You may want to know if the user has logged in. (e.g. Redirect users to log in if they haven't logged in). The sessionState
reflects the user logged in state in the SDK local state. That means even thesessionState
is AUTHENTICATED
, the session may be invalid if it is revoked remotely. After initializing the Authgear SDK, call fetchUserInfo
to update the sessionState
as soon as it is proper to do so.
The value of sessionState
can be UNKNOWN
, NO_SESSION
or AUTHENTICATED
. Initially the sessionState
is UNKNOWN
. After a call to authgear.configure
, the session state would become AUTHENTICATED
if a previous session was found, or NO_SESSION
if such session was not found.
Use the logout
function to log out the user. The user will be redirected to your Authgear endpoint to log out their session. You should provide the redirectURI
for the user to return to your app.
To include the access token to the HTTP requests to your application server, there are two ways to achieve this.
You can get the access token through authgear.accessToken
. Call refreshAccessTokenIfNeeded
every time before using the access token, the function will check and make the network call only if the access token has expired. Include the access token into the Authorization header of the application request.
In this guide, you'll learn how to integrate Authgear into your website using the . In the token approach, the Authgear server returns an access token and refresh token to your SPA application after successful user authentication. Your application can send this access token in subsequent HTTP requests to access protected resources. The alternative to the token approach is the which involves Authgear setting cookies after successful authentication. Your application will send the cookies in subsequent requests to access protected resources.
Signup for an Authgear Portal account in . Or you can use your self-deployed Authgear.
Step 1: Create an application in the Portal
Go to Applications on the left menu bar.
Click ⊕Add Application in the top tool bar.
Input the name of your application and select the application type Single Page Application or Traditional Web Application. Click "Save".
You will see a list of guides that can help you for setting up, then click "Next".
Step 2: Configure the application
Decide the paths in your website that users will be redirected to after they have authenticated or logged out with Authgear.
For after authentication (Authorized Redirect URIs). e.g.https://yourdomain.com/after-authentication
, or http://localhost:4000/after-authentication
for local development.
For after logging out (Post Logout Redirect URIs). e.g.https://yourdomain.com/after-logout
, or http://localhost:4000/after-logout
for local development.
Fill in the Authorized Redirect URIs and Post Logout Redirect URIs that you have defined in the previous steps.
Click "Save" in the top tool bar and keep the Client ID. You can also obtain it again from the applications list later.
Go to Custom Domains
Add your custom domain in Input New Domain
Follow the instructions to verify and configure the custom domain.
Click "Activate" to change the domain status to "Active". The custom domain will be your new Authgear endpoint.
The Web JS SDK is available as . Install the package in your project directory
The SDK should be according to the authentication approach of your choice
In some cases, you may need to obtain current user info through the SDK. (e.g. Display email address in the UI). Use the fetchUserInfo
function to obtain the user info, see .
Authgear SDK provides the fetch
function for you to call your application server. This fetch
function will include the Authorization header in your application request, and handle refresh access token automatically. The authgear.fetch
implements .
To protect your application server from unauthorized access. You will need to .
For detailed documentation on the JavaScript Web SDK, visit
If you want to validate JWT access token in your server, under Access Token, turn on Issue JWT as access token. If you will forward incoming requests to Authgear Resolver Endpoint for authentication, leave this unchecked. See comparisons in .
Step 3: Setup a custom domain (Required for )
Choose your application type for a getting-started guide
The Authgear Android SDK provides an optional Okhttp
interceptor which handles everything from refreshing the access token to putting the access token in the header.
The extension is included in the SDK. Please refer to the above section for getting the SDK.
Configure OkHttpClient
to use AuthgearInterceptor
as follows:
The client would then include the access token in every request and refresh the access token when necessary before the requests.
Authgear is a highly adaptable identity-as-a-service (IDaaS) platform for web and mobile applications
Authgear is an authentication & user management solution which makes it very easy for developers to integrate and customize their consumer applications, it includes these features out of the box:
Easy-to-use interfaces for user registration and login, including email, phone, username as login ID, and password, OTP, magic links, etc for authentication.
Support biometric login on mobile, Passkeys, and Multi-Factor Authentication (MFA) such as SMS/email-based verification and authenticator apps with TOTP.
A user management portal, like password resets, account locking, scheduled deletion or anonymization, and user profile management.
Single Sign-On (SSO) provides a single unified experience for your customers to log into multiple web/mobile apps, including Web2Web, Web2App, and App2App SSO.
Session management with Authgear Portals, and a pre-built setting page for users to control concurrent sessions.
Customizable UI with a user-friendly low-code dashboard.
Various security features such as audit logs, brute force protection, smart account lockout, password policy, etc.
Authgear contains the following high-level components:
Auth UI - is the default batteries included UI for login, signup and setting page. You can customize the style via the Portal, including the CSS and HTML of each page.
Features for managing your users via Authgear Portal.
Zero trust authentication architecture with (OIDC) standard.
Support a wide range of identity providers, such as , , and (AD).
APIs for further integration and customizations. For example, build your own custom login and sign-up pages from the ground up powered by .
Most importantly, you can with Authgear for free.
Client App SDKs - for developers to quickly implement authentication with Auth UI on your web and mobile applications. Check out for tutorials and API References.
- for developers to implement their own login, signup and reauthenticate UI (e.g. a mobile native view); or to define a customized login, signup and reauth flow.
- for developers to use Authgear with other software that already support OIDC login, you can use Authgear as an OpenID Connect Provider.
- explain the common approach of using Access Token or Cookies (JWT or random string) to authenticate an API or HTTP Requests.
- allow your backend to interact directly with Authgear for user management purpose.
- call external web endpoint or use the hosted type-script to customize the behaviour of Authgear. E.g. blocking certain type of sign up, or call external endpoint for each login.
- Import multiple users from another service to your project.
- Export user data from Authgear into a CSV or file.
- Link an OAuth provider to a user's account without AuthUI.
Authgear Portal - You can configure your projects, manage users, check out , or customize the AuthUI. See the for Authgear Portal.
Analytics Page - View reports of all users and active users over a specific time interval on the .
- Set account Lockout Policy to safeguard a user account from brute-force login attempts.
- Bot protection tools to block automated attackers.
- Learn how to set password strength and how the password strength is calculated.
- Add biometric login to your application.
- Enable 2FA in your Authgear project.
- Allow users to log in without a password using a magic link.
- Set up passkey for your project.
- Allow users to log in to your application using their existing account with a social media site or enterprise login provider.
- Customize the look and feel of AuthUI to match your branding.
- Change the language for display texts.
- Create a new account for a user from Authgear Portal.
- Delete a user account from your project.
- Detailed guide on how to use Roles and Groups.
- Guides on how to view and manage user profile information.
Get Started
Jump in with Authgear's getting started guides.
How-To Guides
Find a step-by-step guide to take your project to the next level.
Concepts
Learn the basics.
A quick guide on getting started with Authgear
Authgear makes it easy to add user authentication and authorization to any application. In this guide, we'll show you how to get started with Authgear in 5 minutes.
After you sign up, you'll see the onboarding screen that will guide you through the process of creating your first Authgear project.
An Authgear project is similar to a container that holds all your users, settings, and client applications. You need an Authgear project before you can start signing users up.
You can create multiple projects under one account based on your needs. When you create multiple projects, each project is isolated from the others. For example, you can create Project 1 for your e-commerce business and Project 2 for a fitness club you organize. Project 1 and Project 2 will not share the same users or settings.
To create an additional project, log in to your Authgear account then click on the Create Project button.
Before any integration, you can try out the signup flow for your project from the "Getting Started" page.
You should be greeted with the AuthUI Login/Sign-up page. Use the form to create a new user account under your project.
After logging in from the previous step, you can check out the Pre-Built User Settings Page. This page is the default page where users of your project can edit their profile and manage security settings.
Click on the More link under My profile to view and edit profile attributes such as first name, last name, photo, etc.
The Security section of the User Settings page has the following options:
Password: users can change their password from here.
2-step verification: users can click on this option to view and manage 2-step authenticators for their account.
Signed-in device: from this page, the user can view browsers and devices that their account is currently signed in on.
To get more from Authgear and use Authgear to add user authentication to your web or mobile application, you should integrate Authgear to your application or website.
Authgear offers multiple options for viewing and managing all users who sign up for your project. These options include:
Authgear Portal
The quickest way to manage your users is from the Authgear Portal. To open the user management page in the Authgear Portal, click on the User Management link in the navigation bar on the left side.
Click on Users to view a list of all the users in your project. Click on a user from the list to view their complete profile and perform administrative operations like modify profile details, suspend/unsuspend user, delete account, etc.
You can also add new users to your project from the User Management page. To do that, click on the Create User button on the right.
Continue to navigate around the Authgear Portal to see all the features and settings available for your project.
You can also check out any of the following guides to learn more about Authgear:
Follow this quickstart tutorial to add authentication to your Angular application
Authgear helps you add user logins to your Angular apps. It provides prebuilt login page and user settings page that accelerate the development.
Table of Content
After that, we will need to create an Application in the Project Portal.
Go to Applications on the left menu bar.
Click ⊕Add Application in the top tool bar.
Input the name of your application, e.g. "MyAwesomeApp".
Select Single Page Application as the application type
Click "Save" to create the application
The Redirect URI is a URL in you application where the user will be redirected to after login with Authgear. In this path, make a finish authentication call to complete the login process.
For this tutorial, add http://localhost:4000/auth-redirect
to Authorize Redirect URIs.
The Post Logout Redirect URI is the URL users will be redirected after they have logged out. The URL must be whitelisted.
For this tutorial, add http://localhost:4000/
to Post Logout Redirect URIs.
Save the configuration before next steps.
Here are some recommended steps to scaffold an Angular project. You can skip this part if you are adding Authgear to an existing project. See Step 2: Install Authgear SDK to the project in the next section.
To install the Angular CLI, open a terminal window and run the following command:
Run the following cli command to create a new workspace and initial app called my-app
with a routing module generated.
In the package.json
file, edit the start
script in the script
section
The start
script run the app in development mode on port 4000 instead of the default one.
app.component.html
fileBy default, the Angular CLI generated an initial application for us, but for simplicity, we recommend to modify some of these files to scratch.
In the src/app/app.component.html
file, remove all the lines and add the following line:
Run npm start
now to run the project and you will see "Hello world" on http://localhost:4000
.
Run the following command within your Angular project directory to install the Authgear Web SDK
In src/app/app.component.ts
, import authgear
and call the configure
function to initialize an Authgear instance on application loads.
The Authgear container instance takes endpoint
and clientID
as parameters. They can be obtained from the application page created in Setup Application in Authgear.
It is recommend to render the app after configure()
resolves. So by the time the app is rendered, Authgear is ready to use.
Since we want to reference the logged in state in anywhere of the app, let's put the state in a service with user.service.ts
in the /src/app/services/
folder.
In user.service.ts
, it will have a isLoggedIn
boolean variable. The isLoggedIn
boolean variable can be auto updated using the onSessionStateChange
callback. This callback can be stored in delegate
which is in the local SDK container.
Next, we will add an "auth-redirect" page for handling the authentication result after the user have been authenticated by Authgear.
Create the auth-redirect
component using the following command:
We will inject the router and the UserService to get the use of navigation and the isLoggedIn
state.
Call the Authgear finishAuthentication()
function in the Auth Redirect component to send a token back to Authgear server in exchange for access token and refresh token. Don't worry about the technical jargons, finishAuthentication()
will do all the hard work for you and and save the authentication data.
When the authentication is finished, the isLoggedIn
state from the UserService will automatic set to true
. Finally, navigate back to root (/
) which is our Home page.
The final auth-redirect.component.ts
will look like this
Next, we will add a "Home" page . Create a home
component using the following command:
Then import HomeComponent and AuthRedirectComponent as routes. We can add those routes in the app-routing.module.ts
file:
You can apply those routes in src/app/app.component.html
by replace the lines with the following:
The file structure should now look like
First we will import the Authgear dependency and inject the UserService in home.component.ts
. Then add the startLogin
method which will call startAuthentication(ConfigureOptions)
. This will redirect the user to the login page.
Then you can add a button which will trigger the startLogin
method in home.component.html
:
You can now run npm start
and you will be redirected to the Authgear Login page when you click the Login button.
The Authgear SDK helps you get the information of the logged in users easily.
In the last step, the user is successfully logged in so let's try to print the user ID (sub) of the user in the Home page.
In home
component, we will add a simple Loading splash and a greeting message printing the Sub ID. We will add two conditional elements such that they are only shown when user is logged in. We can also change the login button to show only if the user is not logged in.
Make use of isLoggedIn
from the UserService
to control the components on the page. Fetch the user info by fetchInfo()
and access its sub
property.
In the home.component.html
:
Run the app again, the User ID (sub) of the user should be printed on the Home page.
Finally, let's add an Logout button when user is logged in.
In home.component.html
, we will add a conditional element in the markup:
And add the logout
method:
Run the app again, we can now logout by clicking the logout button.
Authgear provide a built-in UI for the users to set their attributes and change security settings.
Use the open
function to open the setting page at <your_app_endpoint>/settings
In home.component.html
append a conditional link to the logout button section.
And add the userSetting
method:
This the resulting home.component.ts
:
This is the resulting home.component.html:
To access restricted resources on your backend application server, the HTTP requests should include the access token in their Authorization headers. The Web SDK provides a fetch
function which automatically handle this, or you can get the token with authgear.accessToken
.
You can get the access token through authgear.accessToken
. Call refreshAccessTokenIfNeeded
every time before using the access token, the function will check and make the network call only if the access token has expired. Include the access token into the Authorization header of the application request.
Follow this quickstart tutorial to add authentication to your Vue application
Authgear helps you add user logins to your Vue apps. It provides prebuilt login page and user settings page that accelerate the development.
Table of Content
After that, we will need to create an Application in the Project Portal.
Go to Applications on the left menu bar.
Click ⊕Add Application in the top tool bar.
Input the name of your application, e.g. "MyAwesomeApp".
Select Single Page Application as the application type
Click "Save" to create the application
The Redirect URI is a URL in you application where the user will be redirected to after login with Authgear. In this path, make a finish authentication call to complete the login process.
For this tutorial, add http://localhost:4000/auth-redirect
to Authorize Redirect URIs.
The Post Logout Redirect URI is the URL users will be redirected after they have logged out. The URL must be whitelisted.
For this tutorial, add http://localhost:4000/
to Post Logout Redirect URIs.
Save the configuration before next steps.
Here are some recommended steps to scaffold a Vue project. You can skip this part if you are adding Authgear to an existing project. See Step 3: Install Authgear SDK to the project in the next section.
Create the project folder and install the dependencies. We will use vite
as the build tool and the vue-router
package. Also, we will use TypeScript in this tutorial.
As we are using port 4000 for this tutorial, we need to add the port information to the config. In the vite.config.ts
file, modify the file with the following lines:
After doing so, when you run npm run dev
, the server will be running on port 4000.
Home.vue
fileCreate a new file called Home.vue
in the src/components
folder with simply showing Hello World
on the screen.
App.vue
fileThe App.vue
file is generated by Vite
already but some sections might not being needed for this tutorial.
Some of the files might not being used and thus can be deleted. You can perform the following script to delete these files:
The file structure in your project is now:
Run npm run dev
now to run the project and you will see default page with the title Vite + Vue
and a count button on http://localhost:4000
.
Create a AuthRedirect.vue
file in the src/components
folder with the same content as src/components/Home.vue
at this moment.
Create a file called router.ts
in the src/
folder. We will import Home
and AuthRedirect
component as the route and we will implement these components later. The content of this file will look like this:
Run the following command within your Vue project directory to install the Authgear Web SDK
In src/main.ts
, import authgear
and call the configure
function to initialize an Authgear instance on application loads. We will also import router
and use it to build routes for us.
The Authgear container instance takes endpoint
and clientID
as parameters. They can be obtained from the application page created in Setup Application in Authgear.
It is recommend to render the app after configure()
resolves. So by the time the app is rendered, Authgear is ready to use.
Since we want to reference the logged in state in anywhere of the app, let's put the state in a context provider with UserProvider.vue
in the /src/contexts
folder.
In UserProvider.vue
, it will have a isLoggedIn
boolean value. The isLoggedIn
boolean state can be auto updated using the onSessionStateChange
callback. This callback can be stored in delegate
which is in the local SDK container.
Next, we will add an "AuthRedirect" page for handling the authentication result after the user have been authenticated by Authgear.
Create the AuthRedirect.vue
component file in the src/components/
folder.
Call the Authgear finishAuthentication()
function in the Auth Redirect component to send a token back to Authgear server in exchange for access token and refresh token. Don't worry about the technical jargons, finishAuthentication()
will do all the hard work for you and and save the authentication data.
When the authentication is finished, the isLoggedIn
state from the UserContextProvider will automatic set to true
. Finally, navigate back to root (/
) which is our Home page.
The final AuthRedirect.vue
will look like this
As we have already configure the routes in the previous section, we can simply add <router-view />
tag to the App.vue
. We can then Import UserProvider and wrap the router-view
with it.
Your final App.vue
should look like this:
The file structure should now look like
First we will import the Authgear dependency. Then add the login button which will call startAuthentication(ConfigureOptions)
through startLogin
callback on click. This will redirect the user to the login page.
You can now run npm run dev
and you will be redirected to the Authgear Login page when you click the Login button.
The Authgear SDK helps you get the information of the logged in users easily.
In the last step, the user is successfully logged in so let's try to print the user ID (sub) of the user in the Home page.
In Home.vue
, we will add a simple Loading splash and a greeting message printing the Sub ID. We will add two conditional elements such that they are only shown when user is logged in. We can also change the login button to show only if the user is not logged in.
Make use of isLoggedIn
from the UserProvider
to control the components on the page. Fetch the user info by fetchInfo()
and access its sub
property.
The Login button can be also rendered conditionally which only visible if the user is not logged in.
Run the app again, the User ID (sub) of the user should be printed on the Home page.
Finally, let's add an Logout button when user is logged in.
In Home.vue
, we will add a conditional elements in the template:
And add the logout
callback:
Run the app again, we can now logout by clicking the logout button.
Authgear provide a built-in UI for the users to set their attributes and change security settings.
Use the open
function to open the setting page at <your_app_endpoint>/settings
In Home.vue
append a conditional link to the logout button section.
And add the userSetting
callback:
This the the resulting Home.vue
:
To access restricted resources on your backend application server, the HTTP requests should include the access token in their Authorization headers. The Web SDK provides a fetch
function which automatically handle this, or you can get the token with authgear.accessToken
.
You can get the access token through authgear.accessToken
. Call refreshAccessTokenIfNeeded
every time before using the access token, the function will check and make the network call only if the access token has expired. Include the access token into the Authorization header of the application request.
How to integrate with a React Native app
This guide provides instructions on integrating Authgear with a React Native app. Supported platforms include:
React Native 0.60.0 or higher
From the Project listing, create a new Project or select an existing Project. After that, we will need to create an application in the project.
Step 1: Create an application in the Portal
Go to Applications on the left menu bar.
Click ⊕Add Application in the top tool bar.
Input the name of your application and select Native App as the application type. Click "Save".
You will see a list of guides that can help you for setting up, then click "Next".
Step 2: Configure the application
Head back to Authgear Portal, fill in the URI that you have defined in the previous steps.
Click "Save" in the top tool bar and keep the Client ID. You can also obtain it again from the Applications list later.
Follow the documentation of React Native to see how you can create a new React Native app.
To finish the integration, setup the app to handle the redirectURI specified in the application. This part requires platform specific integration.
Add the following activity entry to the AndroidManifest.xml
of your app. The intent system would dispatch the redirect URI to OAuthRedirectActivity
and the sdk would handle the rest.
If your Android app is targeting API level 30 or above (Android 11 or above), you need to add a queries
section to AndroidManifest.xml
.
In Info.plist
, add the matching redirect URI.
In AppDelegate.m
, add the following code snippet.
Add this code to your react native app. This snippet configures authgear to connect to an authgear server deployed at endpoint
with the client you have just setup via clientID
, opens a browser for authentication, and then upon success redirects to the app via the redirectURI
specified.
Now, your user is logged in!
When you start launching the application. You may want to know if the user has logged in. (e.g. Show users the login page if they haven't logged in). The sessionState
reflects the user logged in state in the SDK local state. That means even the sessionState
is AUTHENTICATED
, the session may be invalid if it is revoked remotely. After initializing the Authgear SDK, call fetchUserInfo
to update the sessionState
as soon as it is proper to do so.
The value of sessionState
can be UNKNOWN
, NO_SESSION
or AUTHENTICATED
. Initially the sessionState
is UNKNOWN
. After a call to authgear.configure
, the session state would become AUTHENTICATED
if a previous session was found, or NO_SESSION
if such session was not found.
To include the access token to the HTTP requests to your application server, there are two ways to achieve this.
You can access the access token through authgear.accessToken
. Call refreshAccessTokenIfNeeded
every time before using the access token, the function will check and make the network call only if the access token has expired. Include the access token into the Authorization header of your application request.
To log out the user from the current app session, you need to invoke the logout
function.
To protect your application server from unauthorized access. You will need to integrate your backend with Authgear.
If you are developing mobile or desktop applications, choose from one of these SDKs for your platform to get started.
Follow this quickstart tutorial to add authentication to your React application
Authgear helps you add user logins to your React apps. It provides prebuilt login page and user settings page that accelerate the development.
Table of Content
After that, we will need to create an Application in the Project Portal.
Go to Applications on the left menu bar.
Click ⊕Add Application in the top tool bar.
Input the name of your application, e.g. "MyAwesomeApp".
Select Single Page Application as the application type
Click "Save" to create the application
The Redirect URI is a URL in you application where the user will be redirected to after login with Authgear. In this path, make a finish authentication call to complete the login process.
For this tutorial, add http://localhost:4000/auth-redirect
to Authorize Redirect URIs.
The Post Logout Redirect URI is the URL users will be redirected after they have logged out. The URL must be whitelisted.
For this tutorial, add http://localhost:4000/
to Post Logout Redirect URIs.
Save the configuration before next steps.
Create the project folder and install the dependencies. We will use parcel
as the build tool and the react-router-dom
, react
, and react-dom
packages. Also, we will use TypeScript in this tutorial.
In the package.json
file, add these two lines to the script
section
The start
script run the app in development mode on port 4000. The build
script build the app for production to the dist/
folder.
index.html
fileIn src/
, create a new file called index.html
for parcel to bundle the app:
src/index.html
:
App.tsx
fileCreate a new file called App.tsx
with simply showing Hello World
in the screen:
index.tsx
fileCreate a new file called index.tsx
as the entry point of the application.
The file structure in your project is now:
Run npm start
now to run the project and you will see "Hello World" on http://localhost:4000
.
Run the following command within your React project directory to install the Authgear Web SDK
In src/index.tsx
, import authgear
and call the configure
function to initialize an Authgear instance on application loads.
It is recommend to render the app after configure()
resolves. So by the time the app is rendered, Authgear is ready to use.
Since we want to reference the logged in state in anywhere of the app, let's put the state in a context provider with UserProvider.tsx
in the /src/context
folder.
In UserProvider.tsx
, it will have a isLoggedIn
boolean and a setIsLoggedIn
function. The is LoggedIn
boolean state can be auto updated using the onSessionStateChange
callback. This callback can be stored in delegate
which is in the local SDK container.
Next, we will add an "AuthRedirect" page for handling the authentication result after the user have been authenticated by Authgear.
Create the AuthRedirect.tsx
component file in the src/
folder.
Call the Authgear finishAuthentication()
function in the Auth Redirect component to send a token back to Authgear server in exchange for access token and refresh token. Don't worry about the technical jargons, finishAuthentication()
will do all the hard work for you and and save the authentication data.
When the authentication is finished, the isLoggedIn
state from the UserContextProvider will automatic set to true
. Finally, navigate back to root (/
) which is our Home page.
The final AuthRedirect.tsx
will look like this
Next, we will add a "Home" page . Create a Home.tsx
component file the src/
folder.
Then import Home and AuthRedirect as routes. And Import UserContextProvider and wrap the routes with it.
Your final App.tsx
should look like this:
The file structure should now look like
First we will import the Authgear dependency and the React Hook that we will use to Home.tsx
. Then add the login button which will call startAuthentication(ConfigureOptions)
through startLogin
callback on click. This will redirect the user to the login page.
You can now run npm start
and you will be redirected to the Authgear Login page when you click the Login button.
The Authgear SDK helps you get the information of the logged in users easily.
In the last step, the user is successfully logged in so let's try to print the user ID (sub) of the user in the Home page.
In Home.tsx
, we will add a simple Loading splash and a greeting message printing the Sub ID. We will add two conditional elements such that they are only shown when user is logged in. We can also change the login button to show only if the user is not logged in.
Make use of isLoggedIn
from the UserContext
to control the components on the page. Fetch the user info by fetchInfo()
and access its sub
property.
Run the app again, the User ID (sub) of the user should be printed on the Home page.
Finally, let's add an Logout button when user is logged in.
In Home.tsx
, we will add a conditional elements in the elements:
And add the logout
callback:
Run the app again, we can now logout by clicking the logout button.
Authgear provide a built-in UI for the users to set their attributes and change security settings.
Use the openURL
function to open the setting page at <your_app_endpoint>/settings
In Home.tsx
Add a conditional link to the elements.
And add the userSetting
callback:
This the the resulting Home.tsx
:
To access restricted resources on your backend application server, the HTTP requests should include the access token in their Authorization headers. The Web SDK provides a fetch
function which automatically handle this, or you can get the token with authgear.accessToken
.
You can get the access token through authgear.accessToken
. Call refreshAccessTokenIfNeeded
every time before using the access token, the function will check and make the network call only if the access token has expired. Include the access token into the Authorization header of the application request.
The Authgear Android SDK comes with kotlin support out of the box. In fact, the SDK is written in kotlin!
If you are using kotlin, you can benefit from the suspend function APIs authgear provides. For example, the above authorize example can be written as follows:
Integrate your iOS application with Authgear iOS SDK
This guide provides instructions on integrating Authgear with an iOS app. Supported platforms include:
iOS 11.0 or higher
From the Project listing, create a new Project or select an existing Project. After that, we will need to create an application in the project.
In your application's Info.plist
, register your custom URL scheme, (e.g. com.myapp
).
SDK must be properly configured before use.
When the user clicks login/signup on your app, you can use the following code to start authorization.
Your user is now logged in!
When you start launching the application. You may want to know if the user has logged in. (e.g. Show users the login page if they haven't logged in). The sessionState
reflects the user logged in state in the SDK local state. That means even the sessionState
is .authenticated
, the session may be invalid if it is revoked remotely. After initializing the Authgear SDK, call fetchUserInfo
to update the sessionState
as soon as it is proper to do so.
The value of sessionState
can be .unknown
, .noSession
or .authenticated
. Initially, the sessionState
is .unknown
. After a call to authgear.configure
, the session state would become .authenticated
if a previous session was found, or .noSession
if such session was not found.
Call refreshAccessTokenIfNeeded
every time before using the access token, the function will check and make the network call only if the access token has expired. Include the access token into the Authorization header of your application request.
To log out the user from the current app session, you need to invoke thelogout
function.
To protect your application server from unauthorized access. You will need to integrate your backend with Authgear.
To start using Authgear in your application, create a free Authgear account on .
Now that you have created a project in Authgear, you're ready to integrate Authgear into your applications for your customers/users to sign up and log in. See our documentation for adding Authgear to your application or website for your favourite framework and programming language.
You can learn more about the User Settings page .
Authgear has official SDKs for integrating Authgear with React, React Native, ionic, Native Android, iOS, and Flutter applications. See the section of Authgear documentation for detailed instructions for each SDK and using other frameworks without the official SDK.
login and sign-up page to match your branding needs using the Design tool
guides on how to .
how to .
Follow this 15 minutes tutorial to create a simple app using Angular with Authgear SDK.
Check out and clone .
Signup for an account in and create a Project.
For Windows clients, please find your reference in for more information on installing the Angular CLI.
Authgear SDK provides the fetch
function for you to call your application server. This fetch
function will include the Authorization header in your application request, and handle refresh access token automatically. The authgear.fetch
implements .
Follow this 15 minutes tutorial to create a simple app using Vue with Authgear SDK.
Check out and clone .
Signup for an account in and create a Project.
Authgear SDK provides the fetch
function for you to call your application server. This fetch
function will include the Authorization header in your application request, and handle refresh access token automatically. The authgear.fetch
implements .
React Native have opt-in support for the since 0.68. Given that the New Architecture is still considered as unstable, we do not support it at the moment.
Signup for an Authgear Portal account in . Or you can use your self-deployed Authgear.
In your IDE, define a custom URI scheme that the users will be redirected back to your app after they have authenticated with Authgear, e.g. com.myapp.example://host/path
. For further instruction on setting up custom URI scheme in React Native, see
If you wish to , turn on "Issue JWT as access token". If you wish to , leave this unchecked. See comparisons in . For more explanation on JWT, see
In some cases, you may need to obtain current user info through the SDK. (e.g. Display email address in the UI). Use the fetchUserInfo
function to obtain the user info, see .
Authgear SDK provides the fetch
function for you to call your application server. The fetch
function will include the Authorization header in your application request, and handle refresh access token automatically. authgear.fetch
implement .
For detailed documentation on the JavaScript React Native SDK, visit
Follow this 15 minutes tutorial to create a simple app using React with Authgear SDK.
Check out and clone .
Signup for an account in and create a Project.
Here are some recommended steps to scaffold a React project. You can skip this part if you are adding Authgear to an existing project. See in the next section.
The Authgear container instance takes endpoint
and clientID
as parameters. They can be obtained from the application page created in .
Since in React 18, useEffect will be fired twice in development mode, we need to implement a to stop it from firing twice. We will use an useRef
Hook to stop the user token from being sent twice to the Authgear Endpoint.
Authgear SDK provides the fetch
function for you to call your application server. This fetch
function will include the Authorization header in your application request, and handle refresh access token automatically. The authgear.fetch
implements .
Signup for an Authgear Portal account in . Or you can use your self-deployed Authgear.
Step 1: Create an application in the Portal
Go to Applications on the left menu bar.
Click ⊕Add Application in the top tool bar.
Input the name of your application and select Native App as the application type. Click "Save".
You will see a list of guides that can help you for setting up, then click "Next".
Step 2: Configure the application
In your IDE (e.g. XCode), define a custom URI scheme that the users will be redirected back to your app after they have authenticated with Authgear, e.g. com.myapp.example://host/path
.[^1]
Head back to Authgear Portal, fill in the Redirect URI that you have defined in the previous steps.
Click "Save" in the top tool bar and keep the Client ID. You can also obtain it again from the Applications list later.
In some cases, you may need to obtain current user info through the SDK. (e.g. Display email address in the UI). Use the fetchUserInfo
function to obtain the user info, see .
For detailed documentation on the iOS SDK, visit .
[^1]: For further instruction on setting up custom URI scheme in iOS, see [^2]: For more explanation on JWT, see
If you wish to , turn on "Issue JWT as access token".[^2] If you wish to , leave this unchecked. See comparisons in .
Authentication for Next.js app with Authgear
You will learn the following throughout the article:
How to add user login, sign-up, and logout to Next.js Applications.
How to create a middleware to protect Next.js application pages.
Before you begin, you'll need the following:
After you created the Authgear app, you choose how users need to authenticate on the login page. From the Authentication tab, navigate to Login Methods, you can choose a login method from various options including, by email, mobile, or social, just using a username or the custom method you specify. For this demo, we choose the Email+Passwordless approach where our users are asked to register an account and log in by using their emails. They will receive a One-time password (OTP) to their emails and verify the code to use the app.
Since you've cloned a working repo, you don't need to follow the next section. If you'd like to understand more about what was done in the demo application, feel free to read them.
If you want to create your own application instead of using our demo project, you can create a new Next.js application by running the command below.
The create-next-app
wizard will ask you a few questions on how to set up your application. Answer them accordingly.
Now, you need to create a file named exactly like [...nextauth].js
in src/pages/api/auth
. First, make the directory and then create a file named [...nextauth].js
in that directory.
In the following code, we made a few config:
We have made id
and name
in the Next Auth session (under callbacks
). You can also add other attributes such as email
, phone_number
, and preferred_username
to the session as well.
To allow components to check whether the current user is logged in, change src/pages/_app.js
to have your application rendered inside a <SessionProvider>
context, as shown below.
Then, you change your home component located at src/pages/index.js
to include the <LoginButton />
component inside <main>
.
In the root directory of your project, add the file .env.local
with the following environment variables:
replace with Authgear app settings values from Part1 such as Issuer
, ClientId
, ClientSecret
.
Start the HTTP server by running the following command.
Click the "Log in" button to be taken to a page with a "Sign in with Authgear" button.
After clicking it, you should be redirected to your Authgear login screen.
After you have authenticated with a one-time password sent to your email, you'll arrive back at your Next.js application home screen, with your email address displayed and a "Log out" button.
This tutorial showed how to quickly implement an end-to-end OpenID Connect flow in Next.js with Authgear. Only simple code is needed, after which protected views are secured with built-in UI login pages.
How to integrate with a Flutter app
This guide provides instructions on integrating Authgear with a Flutter app. Supported platforms include:
Flutter 2.5.0 or higher
From the Project listing, create a new Project or select an existing Project. After that, we will need to create an application in the project.
Follow the documentation of Flutter to see how you can create a new Flutter app.
To finish the integration, setup the app to handle the redirectURI specified in the application. This part requires platform specific integration.
This declares the URL schemes supported by your app, so the device can redirect the user to the app after authentication using the redirect URI.
Add the following <activity>
entry to the AndroidManifest.xml
of your app. The intent system would dispatch the redirect URI to OAuthRedirectActivity
and the SDK would handle the rest.
If your Android app is targeting API level 30 or above (Android 11 or above), you need to add a queries
section to AndroidManifest.xml
.
In Info.plist
, add the matching redirect URI by adding the key CFBundleURLTypes
and the values inside <dict>
as shown as the following example.
Add this code to your app. This snippet configures authgear to connect to an authgear server deployed at endpoint
with the client you have just setup via clientID
, opens a browser for authentication, and then upon success redirects to the app via the redirectURI
specified.
Now, your user is logged in!
When you start launching the application. You may want to know if the user has logged in. (e.g. Show users the login page if they haven't logged in). The sessionState
reflects the user logged in state in the SDK local state. That means even the sessionState
is SessionState.authenticated
, the session may be invalid if it is revoked remotely. After initializing the Authgear SDK, call fetchUserInfo
to update the sessionState
as soon as it is proper to do so.
The value of sessionState
can be SessionState.unknown
, SessionState.noSession
or SessionState.authenticated
. Initially, the sessionState
is SessionState.unknown
. After a call to authgear.configure
, the session state would become SessionState.authenticated
if a previous session was found, or SessionState.noSession
if such session was not found.
To include the access token to the HTTP requests to your application server, use wrapHttpClient
.
The wrapped client will include the Authorization header in every HTTP request, and refresh access token automatically.
To log out the user from the current app session, you need to invoke thelogout
function.
To protect your application server from unauthorized access. You will need to integrate your backend with Authgear.
How to use authgear android SDK
This guide provides instructions on integrating Authgear with an Android app. Supported platforms include:
Android 5.0 (API 21) or higher
From the Project listing, create a new Project or select an existing Project. After that, we will need to create an application in the project.
Add jitpack
repository to gradle
Add authgear in dependencies. Use $branch-SNAPSHOT
(e.g. main-SNAPSHOT
) for the latest version in a branch or a release tag/git commit hash of the desired version.
Add the following activity entry to the AndroidManifest.xml
of your app. The intent system would dispatch the redirect URI to OauthRedirectActivity
and the SDK would handle the rest.
If your Android app is targeting API level 30 or above (Android 11 or above), you need to add a queries
section to AndroidManifest.xml
.
The above call of authorize
passes in the exact redirect URI as configured in the applications and manifest, the callback then indicates authorization success or failure. By default, the callback is called on the main thread.
Now, your user is logged in!
When you start launching the application. You may want to know if the user has logged in. (e.g. Show users the login page if they haven't logged in). The SessionState
reflects the user logged in state in the SDK local state. That means even the SessionState
is AUTHENTICATED
, the session may be invalid if it is revoked remotely. After initializing the Authgear SDK, call fetchUserInfo
to update the SessionState
as soon as it is proper to do so.
The value of SessionState
can be UNKNOWN
, NO_SESSION
or AUTHENTICATED
. Initially, the sessionState
is UNKNOWN
. After a call to authgear.configure
, the session state would become AUTHENTICATED
if a previous session was found, or NO_SESSION
if such session was not found.
To log out the user from the current app session, you need to invoke thelogout
function.
To protect your application server from unauthorized access. You will need to integrate your backend with Authgear.
Guide on how to use Authgear in an Ionic project
In this post, you'll learn how to use Authgear with your Ionic project using the Authgear Ionic SDK.
At the end of this tutorial, we'll build an Ionic app that can do the following:
Allow users to log in to their account on your Authgear project
Allow new users to sign up
Allow signed-in users to view their user info and logout.
The final UI for the app we'll build should look like this:
To follow this guide seamlessly, make sure to have the following:
Node.js installed on your local machine
Android Studio (for building the Android client of your application)
X-code (for building the iOS client of your application)
Any code editor (VS Code, Sublime, etc)
Now let us get into the steps for using Authgear in an Ionic project.
In this part, you'll learn how to configure an Authgear application so that you can use it in your Ionic project. You'll do this by performing the following steps in the Authgear Portal.
In your project, navigate to the Applications section then click on Add Application to create a new Authgear application. Enter a name for your application and select Native App as the Application Type. Next, click Save to continue to the configuration page for your new application.
In this step, you'll set up authorized redirect URIs for your application. An authorized redirect URI should be a URI pointing to a page on your Ionic app where you want to redirect users at the end of the authorization flow.
To add a URI, scroll to the URIs section of your application configuration page and enter the URI in the text field. You can click the Add URI button to add additional URIs.
For our example app, add the following URIs:
com.authgear.example.capacitor://host/path
capacitor://localhost
http://localhost:8100/oauth-redirect
https://localhost
Once you're done, click on the Save button.
Now that we have our Authgear application configured, we can now proceed with creating the Ionic application that will have all the features stated in our objective earlier.
For this tutorial, we'll be implementing an Ionic app using React.
Before you can create an Ionic project, install the Ionic CLI on your computer by running the following command in Terminal or Command Prompt:
Now create a new Ionic project by running the following command:
After running the above command, follow the wizard to create a new blank project.
Next, open your new project in a code editor and update for appId
in capacitor.config.ts to the following value:
This new value for appId
is the same value we used in the authorized redirect URI earlier.
Note: It is important that you update the value for appId
before you create the Android and iOS projects for your Ionic application. Doing this will enable Capacitor to create your Android and iOS project with the value for appId as the package name and app ID.
You can run the ionic serve
command to preview your new blank project on a browser.
Finally, create the Android and iOS projects for your app by running the following commands from your Ionic project's root folder:
First, install the Android and iOS platforms:
Then, create the projects:
In this step, you'll install the Authgear SDK for Ionic (Capacitor) and the Javascript SDK for the web. The web SDK will help you test your application on a web browser.
To install the SDKs, run the following commands in your Terminal or Command Prompt:
Authgear Ionic SDK
Authgear Web SDK
In this step, you'll learn how to configure your Ionic project using the details from your Authgear application configuration.
To get started, open src/pages/Home.tsx in your code editor and import the Authgear SDK by adding the following code to the top of the file:
The above code imports all the components of the Authgear SDK we need for our example app.
Because Ionic apps can run on the web and native mobile platforms, we have to import both Authgear web and Authgear Capacitor SDKs.
Next, add the following constants to Home.tsx just below the last import statement:
Update the values for the constants (CLIENT_ID
, ENDPOINT
) you just added to the correct values from your application's configuration page in the Authgear Portal.
Also, add this small utility function that will help to check whether your Ionic app is running natively or on a web browser:
Now implement a new AuthenticationScreen
component in Home.tsx by pasting the following code:
Here, we'll implement an authenticate()
method inside the AuthenticationScreen
component we created in the previous step.
To do this, first, add the following constants that the method will depend on to the top of AuthenticationScreen
component:
Then, add the authenticate()
method by pasting the following code to the end of the AuthenticationScreen
component:
Calling this authenticate()
method will initialize an authentication flow. The page
parameter can be used to specify whether to start the authentication flow on the login page or signup page.
At the end of an authentication flow, your users will be redirected to the URL you specified in redirectURI
. In this step, we'll set up the routes and code to process redirects to the URIs.
First, create a new file OAuthRedirect.tsx in src/pages/ and add the following code to it:
Change the values for CLIENT_ID
and ENDPOINT
in the above code to the correct value from your Authgear application configuration page.
Now open src/App.tsx and create a new route for OAuthRedirect
using the following code:
Remember to import OAuthRedirect
in App.tsx.
To handle redirect in the Android project, add the following code to android/app/src/main/AndroidManifest.xml:
At this point, you will create the User Interface for the AuthenticationScreen component.
To do that, add the following code to the end of the AuthenticationScreen
component method:
To deploy your app to a mobile device (for example Android) run the following commands:
First build your project by running:
Then sync the changes to the mobile project using this command:
You can run the project by opening the android
project folder in Android Studio or ios
folder in X-code.
You can quickly open the project in Android Studio using the following command:
Once your project builds successfully, you can try the Login, Signup, Fetch User Info, and Logout buttons.
How to integrate with a Xamarin app
This guide provides instructions on integrating Authgear with a Xamarin app. Supported packages include:
Xamarin.Essentials 1.7.2 or higher
Xamarin.Forms 5.0.0.2401 or higher
From the Project listing, create a new Project or select an existing Project. After that, we will need to create an application in the project.
Open Visual Studio
Create a new project
Choose the Xamarin.Forms template
Authgear.Xamarin targets MonoAndroid 12.0 on Android, and Xamarin.iOS10 on iOS. Update the target framework of the Android and iOS projects to match Authgear.Xamarin's target frameworks.
Update Android and iOS project's Xamarin.Essentials to 1.7.2.
To finish the integration, setup the app to handle the redirectURI specified in the application. This part requires platform specific integration.
If your Android app is targeting API level 30 or above (Android 11 or above), you need to add a queries
section to AndroidManifest.xml
.
In your MainActivity.cs
In your AppDelegate.cs
When you start launching the application. You may want to know if the user has logged in. (e.g. Show users the login page if they haven't logged in). The SessionState
reflects the user logged in state in the SDK locally on the device. That means even the SessionState
is Authenticated
, the session may be invalid if it is revoked remotely. After initializing the Authgear SDK, call FetchUserInfoAsync
to update the SessionState
as soon as it is proper to do so.
The value of SessionState
can be Unknown
, NoSession
or Authenticated
. Initially, the SessionState
is Unknown
. After a call to authgear.configure
, the session state would become Authenticated
if a previous session was found, or NoSession
if such session was not found.
To log out the user from the current app session, you need to invoke thelogout
function.
To include the access token to the HTTP requests to your application server, you set the bearer token manually by using authgear.AccessToken
.
You can get the access token through authgear.AccessToken
. Call RefreshAccessTokenIfNeededAsync
every time before using the access token, the function will check and make the network call only if the access token has expired. Then, include the access token into the Authorization header of the http request.
To protect your application server from unauthorized access. You will need to integrate your backend with Authgear.
Add authentication for ASP.NET app with Authgear
You will learn the following throughout the article:
Before you get started, you will need the following:
Use the interactive selector to create a new Authgear OIDC Client application or select an existing application that represents the project you want to integrate with.
Also, enable Issue JWT as an access token option under the Access Token section of the app configuration:
After you create the Authgear app, you choose how users need to authenticate on the login page. From the Authentication tab, navigate to Login Methods, you can choose a login method from various options including, by email, mobile, or social, just using a username or the custom method you specify. For this demo, we choose the Email+Passwordless approach where our users are asked to register an account and log in by using their emails. They will receive a One-time password (OTP) to their emails and verify the code to use the app.
Assume that there is a protected resource like a Razor page Protected.cshtml
that is used to represent views:
And ProtectedModel.cs
class to which Authorize
the attribute is applied requires authorization.
To see protected data, users need to go through the authentication process via Authgear.
If a user has not authenticated yet, Unauthenticated.chtml
the page is rendered, an OpenID Connect redirect flow is triggered and the user needs to authenticate through the Authgear login page. See Run the Application section
After successful authentication, you should see the protected page with the following details:
As part of the OAuth 2.0 standard, we can use the refresh token returned by the token endpoint to get a new access token. Doing so enables our application to replace an expired access token without requiring the user to repeat the entire login process.
The following code in ProtectedModel.cs
is responsible for doing that:
Note: You must include offline_access
in your OAuth 2.0 scope for the Authgear authorization server to return a refresh token.
The Logout button on the Protected.cshtml
page calls the OnPostLogout()
method in ProtectedModel.cs. The method will delete the current user session and redirect to Authgear's end session endpoint for the user to complete the logout process.
The code sample below shows the implementation of the OnPostLogout()
method:
Start by cloning the project into your local machine:
Make the project directory your current working directory:
Update the following configuration variables in the appsettings.json
file with your Authgear app settings values from Part1 such as Issuer
, ClientId
, ClientSecret
, and Authgear endpoint:
After you have authenticated, a protected view is rendered. The application receives an Access token that it uses to present user data on the screen, and tokens that could be used in upstream requests to some backend API, to access data on behalf of the user.
This guide showed how to quickly implement an end-to-end OpenID Connect flow in .NET with Authgear. Only simple code is needed, after which protected views are secured with built-in UI login pages.
Traditional web app that runs on the server
Authentication for Spring Boot App with Authgear and OAuth2
You will learn the following:
How to create an app on Authgear.
How to enable Email based login.
Add sign-up and login features to Spring Boot App.
Before you get started, you will need the following:
Java 17 or higher.
Use the interactive selector to create a new Authgear OIDC Client application or select an existing application that represents the project you want to integrate with.
A Redirect URI is a URL in your application that you would like Authgear to redirect users to after they have authenticated. In our case, it will be a home page for our Spring Boot App. If not set, users will not be returned to your application after they log in.
To follow the example in this post, add the following URL as a redirect URI:
After you create the Authgear app, you choose how users need to authenticate on the login page. From the “Authentication” tab, navigate to “Login Methods”, you can choose a login method from various options including by email, mobile, or social, just using a username or the custom method you specify. For this demo, we choose the Email+Passwordless approach where our users are asked to register an account and log in by using their emails. They will receive a One-time password (OTP) to their emails and verify the code to use the app.
Spring Security makes it easy to configure your application for authentication with OIDC providers such as Authgear. We need to add the client credentials to the application.properties file with your Auhgear provider configuration. You can use the sample below and replace properties with the values from your Authgear app:
To enable user login with Authgear, create a class that will provide an instance of SecurityFilterChain, add the @EnableMethodSecurity
annotation, and override the necessary method:
We create a simple home.html page using Thymeleaf templates. When a user opens the page running on http://localhost:8080/, we show the page with buttons for login or logout:
Next, we create a controller class to handle the incoming request. This controller renders the home.html page. When the user authenticates, the application retrieves the user's profile information attributes to render the page.
To run the application, you can execute the mvn spring-boot:run
goal. Or run from your editor the main ExampleApplication.java file. The sample application will be available at http://localhost:8080/.
Click on the Login button to be redirected to the Authgear login page.
You can also customize the login page UI view from the Authgear Portal. After you sign up, you will receive an OTP code in your email to verify your identity.
And log into your new account, you will be redirected back to the home page:
An API or service protected by Authgear
If your API or backend service needs authentication, you can validate the JWT token in your application server code.
Authentication for PHP websites with Authgear and OAuth2
Using OAuth, you can use Authgear to add user authentication in a vanilla PHP application.
In this guide, we'll cover how to implement OAuth 2.0 login in a regular PHP web application with Authgear as the Identity Provider.
At the end of this post, you'll learn the following:
How to create an Authgear Application
How to enable email and password sign-in
How to sign in with Authgear from a PHP app
How to request user info from Authgear
How to use a refresh token
And finally how to log users out and revoke access tokens.
To follow along, you'll need the following:
PHP runtime (E.g XAMPP for testing offline on Windows devices)
Your preferred code editor (e.g VS Code).
In this guide, we'll build a basic PHP application that lets a user sign in with their registered email and password.
The application will welcome the user with their email address after they sign in successfully. If the user is not signed in, the application will display links to Register or Login.
The following screenshot shows what the User Interface for the app will look like:
Now let's dive into the actual steps of how to add Authgear to a PHP application.
Under this section, we will cover the steps for configuring the Authgear application our PHP website will be connecting to. We'll do all these configurations in the Authgear Portal.
To do that, log in to the Authgear Portal, and select your project (or create a new one if you don't have any yet). From your project dashboard navigate to the Applications section and enter the details for your new application as shown below:
Once you're done, click on the Save button to continue. Then, click on Next to see the configuration page for your application.
The application configuration page contains basic information like Client ID
and Client Secret
that we'll use later in this tutorial. Hence, try to note the values down.
In addition to basic information, you can find other configuration information including endpoints and Authorized Redirect URIs.
The Authorized Redirect URIs section contains a link to the page you want Authgear to redirect users to after login.
Update the value for Authorized Redirect URIs to a page on your application. For our example PHP application the value will be http://localhost
because we plan to test run it offline using XAMPP. Also, try to note this value down as we'll be using it in later steps.
Here we will cover the steps for implementing a PHP website that interacts with Authgear using the Open ID Connect (OIDC) standard.
Create a new PHP project on your computer and add an index.php
file to the root of the project folder.
Add the following code to index.php to create the User Interface of the example app.
Note: The Login and Logout links in the above code currently point to login.php and logout.php respectively, we'll create both files later.
In this step, we'll add our Authgear application configuration to the PHP project.
Install the package manually from Github or via Composer by running the following command from your PHP project's root directory:
Next, after the package is installed, create a new config.php
file in the PHP project folder. Add the following code to the file:
Note: Replace the values for clientId
, clientSecret
, redirectUri
with corresponding values from the Authgear application you created in Step 1.
Including the offline_access
scope is required to get a refresh token from Authgear.
The flow for Login on our app is as follows:
The user clicks on the Login button
User is redirected to the Authgear authorization page where they can sign in using email and password or any other sign-in methods you have enabled for your Authgear project.
The user is redirected back to your website with an authorization code.
In order to implement the above, you need to create a login.php
file in your project's root directory. Add the following code to the login.php file:
At this point, if you try running the example app in a browser and click the Login link in index.php, your app should redirect to the Authgear login page. If you sign in successfully, you should be redirected back to the redirect URL you specified earlier in your project configuration.
Authgear will redirect to your Authorized Redirect URI with extra parameters like code
or an error message in the URL. The value for the code parameter is your authorization code. In the next step, we'll use the authorization code to generate an access token.
Usually, after successful sign-in, you'll want to start using the current user's info to offer custom experience in your app.
In this step, we'll use the PHP OAuth 2.0 Client once more to interact with our Authgear app.
First, open index.php
and search for the line with the following code:
Replace the above line with this code:
The above code exchanges the authorization code returned in the redirect for an access token. It then stores the access token in the PHP session so that we can use this token in future requests to protected resources.
Now that we have the access token, let's try to get the current user's details. To do that, update the HTML part in index.php like this:
Now test the app on your browser again and you should get the following page after login:
We've successfully added user authentication to our PHP app using Authgear as the identity provider. The above page displays a welcome message with the email address the user registered with on your Authgear project. You can display other info about the user from the value of $userInfo
variable.
In OAuth 2.0, a refresh token is a key that's usually included in the response from the token endpoint when a client application exchanges the authorization code for an access token.
Access tokens expire after some time. Hence, we can use this refresh token to request a new access token without requiring our application users to log in again. In this step, we'll show you how to use the refresh token.
In the last step, we stored the value for the refresh token in the $_SESSION['refreshToken']
variable. So, to get the refresh token, simply read the value from that variable.
Now, add the following code to index.php to read and use the refresh token to get a new access token:
First, find the line with the following code:
Replace that line with the following blocks of code:
Note: It is required to include offline_access in your OAuth 2.0 scopes to get a refresh token from Authgear.
Authgear provides a token revoke endpoint that you can use to revoke a refresh token and all the access associated with it.
To use the token revoke endpoint to log users out of your application, create a new logout.php
file in your project directory then add the following code to the file:
The above code will revoke your refresh token and delete all the session variables.
In this post, we covered how to get started with adding Authgear to a regular web app built with PHP and no framework.
We also tried out an example of using the Authgear authorization code to retrieve an access token, then we used the token to access the user info endpoint.
Authentication for a Python web application
You will learn the following:
How to create an app on Authgear.
How to enable Email-based login.
Add sign-up and login features to the Flask app.
Before you begin, you'll need the following:
Every application in Authgear is assigned an alphanumeric, unique client ID that your application code will use to call Authgear APIs through the Authlib client library in the Flask app. Record the generated Authgear Issuer Domain
(for example, example-auth.authgear-apps.com
), CLIENT ID
, CLIENT SECRET
from the output. You will use these values in Part 2 for the Flask app config.
After you create the Authgear app, you choose how users need to authenticate on the login page. From the Authentication tab, navigate to Login Methods, you can choose a login method from various options including, by email, mobile, or social, just using a username or the custom method you specify. For this demo, we choose the Email+Passwordless approach where our users are asked to register an account and log in by using their emails. They will receive a One-time password (OTP) to their emails and verify the code to use the app.
Next, create a Flask application with a single page and routes for home, callback, login, and logout flows.
Start with creating a requirements.txt
file in your project directory:
Run pip install -r requirements.txt
from your command-line interface to make these dependencies available to the Python project.
Create a server.py
file in the project directory that contains application logic. Add the necessary libraries the application uses.
Load the configuration .env
file to use values such as AUTHGEAR_CLIENT_ID AUTHGEAR_CLIENT_SECRET
, AUTHGEAR_DOMAIN
and APP_SECRET_KEY
in the app.
Configure Authlib to handle the application's authentication with Authgear based on OIDC:
When visitors to the app visit the /login
route, they'll be redirected to Authgear to begin the authentication flow.
Once users complete the login process using Authgear, they will be redirected back to the application's /callback
route. This route ensures that the user's session is saved, so they won't need to log in again during subsequent visits.
Refresh Token
Calling the authorize_access_token()
method of the Flask Authlib package will include a refresh token in the token response, provided your Flask application has offline_access
as one of the OAuth 2.0 scopes.
Authlib will also use the refresh token to obtain a new access token automatically when the current access token has expired.
Logout
The route /logout
manages the user's logout process from the application. It clears the user's session within the app and momentarily redirects to Authgear's logout endpoint to guarantee a thorough session clearance. After this, users are navigated back to your home route (which we'll discuss shortly).
The home route will either display the details of a logged-in user or provide an option for visitors to sign in.
Create a new sub-directory in the project folder named templates
, and create a file home.html
.
Run the application from the project root directory:
python server.py
In this guide, you'll learn how to implement authentication for the application, a popular React-based framework for JavaScript, and as the OIDC provider. The source code can be found on .
In the , the Next.js app is integrated with Authgear, and the client library is used for sending authentication requests as an OpenID Connect middleware from the app to Authgear.
A free Authgear account. if you don't have one already.
.
Experience with framework and application development.
To use Authgear services, you’ll need to have an application set up in the Authgear . This setup allows users in Authgear to sign in to the Next.js application automatically once they are authenticated by Authgear.
To set up the application, navigate to the and select Applications on the left-hand navigation bar. Use the interactive selector to create a new Authgear OIDC Client application or select an existing application that represents the project you want to integrate with.
Every application in Authgear is assigned an alphanumeric, unique client ID that your application code will use to call Authgear APIs through the NextAuth.js Client in the Next.js app. Record the generated Authgear ISSUER
(for example, ), CLIENT ID
, CLIENT SECRET
from the output. You will use these values in the next step for the client app config.
An Authorized Redirect URI of your application is the URL that Authgear will redirect to after the user has authenticated for the OpenID Connect middleware to complete the authentication process. In our case, it will be a home page for our Next.js and it will run at .
Set the following to the Authorized Redirect URIs field. If not set, users will not be returned to your application after they log in.
You have two options here. You can either clone a or build the app from scratch.
If you want to run an already working application, you can clone the demo project from this using the following command.
Either way, continue configuring the to proceed with this tutorial.
Now that you have the application running, let's implement the authentication process by using . We recommend you look also at the for the most up-to-date instructions. First, install NextAuth.js:
Next, you'll configure a for Authgear. Doing so ensures every request to the /api/auth/*
path is handled by NextAuth.js.
We've added as the scope to make Authgear return all user profiles
This will make the React Hook accessible to your entire application. Now, create a component that will either render a "Log in" or "Log out" button, depending on the session state, in a src/components/login-button.jsx
file.
Browse to . If the installation went successful, you should see the Login page.
Your users can sign-up and login to your application through a page hosted by Authgear, which provides them with a secure, standards-based login experience that you can customize with your own branding and various authentication methods, such as , , , with SMS/WhatsApp, and multi-factor authentication (MFA).
Signup for an Authgear Portal account in . Or you can use your self-deployed Authgear.
Step 1: Create an application in the Portal
Go to Applications on the left menu bar.
You will see the "New Application" page or Click ⊕Add Application in the top tool bar.
Input the name of your application and select Native App as the application type. Click "Save".
You will see a list of guides that can help you for setting up, then click "Next".
Step 2: Configure the application
In your IDE, define a custom URI scheme that the users will be redirected back to your app after they have authenticated with Authgear, e.g. com.myapp.example://host/path
.[^1]
Head back to Authgear Portal, fill in the Redirect URI that you have defined in the previous steps.
Click "Save" in the top tool bar and keep the Client ID. You can also obtain it again from the Applications list later.
In some cases, you may need to obtain current user info through the SDK. (e.g. Display email address in the UI). Use the fetchUserInfo
function to obtain the user info, see .
For detailed documentation on the Flutter SDK, visit
[^1]: For futher instruction on setting up custom URI scheme in Flutter, see
[^2]: For more explanation on JWT, see
Signup for an Authgear Portal account in . Or you can use your self-deployed Authgear.
Step 1: Create an application in the Portal
Go to Applications on the left menu bar.
Click ⊕Add Application in the top tool bar.
Input the name of your application and select Native App as the application type. Click "Save".
You will see a list of guides that can help you for setting up, then click "Next".
Step 2: Configure the application
In your IDE (e.g. Android Studio), define a custom URI scheme that the users will be redirected back to your app after they have authenticated with Authgear, e.g. com.myapp.example://host/path
.[^1]
Head back to Authgear Portal, fill in the Redirect URI that you have defined in the previous steps.
Click "Save" in the top tool bar and keep the Client ID. You can also obtain it again from the Applications list later.
Add the following code to your app's Application
class. If there is none, add a class that extends Application
. Make sure it is declared in AndroidManifest.xml
's application
tag with the name
attribute as described .
Add the following code to your view model. Do NOT call these codes in activity as this can lead to memory leak when your activity instance is destroyed. You can read more on the view model in the official documentation .
In some cases, you may need to obtain current user info through the SDK. (e.g. Display email address in the UI). Use the fetchUserInfo
function to obtain the user info, see .
Call refreshAccessTokenIfNeeded
every time before using the access token, the function will check and make the network call only if the access token has expired. Include the access token into the Authorization header of your application request. If you are using OKHttp in your project, you can also use the interceptor extension provided by the SDK, see .
For detailed documentation on the Flutter SDK, visit
[^1]: For further instruction on setting up custom URI scheme in Android, see [^2]: For more explanation on JWT, see
An Authgear account. You can sign up for one for free .
First, log in to Authgear Portal at and select an existing project or create a new one.
Authgear Capacitor SDK makes it easier to use Authgear in your Ionic application. It provides many helpful methods and interfaces for interacting with the Authgear service from your Ionic application. To learn more about the SDK check . Also, check out the complete repo for the Authgear Ionic SDK example app .
Signup for an Authgear Portal account in . Or you can use your self-deployed Authgear.
Step 1: Create an application in the Portal
Go to Applications on the left menu bar.
Click ⊕Add Application in the top tool bar.
Input the name of your application and select Native App as the application type. Click "Save".
You will see a list of guides that can help you for setting up, then click "Next".
Step 2: Configure the application
In your IDE (e.g. Visual Studio), define a custom URI scheme that the users will be redirected back to your app after they have authenticated with Authgear, e.g. com.myapp.example://host/path
.[^1]
Head back to Authgear Portal, fill in the Redirect URI that you have defined in the previous steps.
Click "Save" in the top tool bar and keep the Client ID. You can also obtain it again from the Applications list later.
Search for "Authgear.Xamarin" on nuget.org and add it to your base project.
In some cases, you may need to obtain current user info through the SDK. (e.g. Display email address in the UI). Use the FetchUserInfoAsync
function to obtain the user info, see .
For detailed documentation on the Xamarin SDK, visit
[^1]: For further instruction on setting up custom URI scheme in Xamarin, see [^2]: For more explanation on JWT, see
In this guide, you will learn how to add authentication features with by implementing an flow, then retrieving OAuth tokens, to call APIs. View on GitHub.
How to add user login, sign-up, and logout to Core Applications.
How to use the Core Authorization Middleware to protect Core application routes.
A free Authgear account. if you don't have one already.
downloaded and installed on your machine. You can also use and to automatically detect the .NET version.
To use Authgear services, you’ll need to have an application set up in the Authgear . The Authgear application is where you will configure how you want to authenticate and manage your users.
Every application in Authgear is assigned an alphanumeric, unique client ID that your application code will use to call Authgear APIs through the OpenID Connect Client in the .NET app. Note down the Authgear ISSUER
(for example, ), CLIENT ID
, CLIENT SECRET
, and OpenID Token Endpoint
() from the output. You will use these values in the next step for the client app config.
A Redirect URI of your application is the URL that Authgear will redirect to after the user has authenticated in order for the OpenID Connect middleware to complete the authentication process. In our case, it will be a home page for our and it will run at.
Set the following redirect URI: If not set, users will not be returned to your application after they log in.
This guide will be used to provide a way for your users to log in to your Core application. The can be found on GitHub. If you are familiar with the steps, you can skip this part and clone the code repository and run the code sample by following the file there.
To integrate Authgear with Core you will use both the Cookie and OpenID Connect (OIDC) authentication handlers. If you are not using a sample project and are integrating Authgear into your own existing project, then please make sure that you add Microsoft.AspNetCore.Authentication.OpenIdConnect
packages to your application. Run the following command in your terminal or use your editor to include the NuGet package there:
To enable authentication in your Core application, use the OpenID Connect (OIDC) middleware. Open Startup
the class and in the ConfigureServices
method, add the authentication services and call the AddAuthentication
method. To enable cookie authentication, call the AddCookie
method. Next, configure the OIDC authentication handler by adding method AddOpenIdConnect
implementation. Configure other parameters, such as Issuer
, ClientId
, ClientSecret
, and Scope
. Here, is what looks like Startup.cs
after you apply these changes:
Execute the following command to run the Core web application:
You can now visit to access the application. When you click on the "View Protected Data" button, Core takes you to the Authgear’s Login page.
Your users can log in to your application through a page hosted by Authgear, which provides them with a secure, standards-based login experience that you can customize with your own branding and various authentication methods, such as , , , with SMS/WhatsApp, and multi-factor authentication (MFA).
If you have a traditional web application like Java EE, Express, PHP, GO, Laravel, or Core MVC and you want to integrate authentication features.
In this guide, you will learn how to add authentication to your Java Spring Boot application using with Authgear as the Identity Provider (IdP).
A free Authgear account. if you don't have one already.
To use Authgear services, you’ll need to have an application set up in the Authgear . The Authgear application is where you will configure how you want authentication to work for the project you are developing.
Every application in Authgear is assigned an alphanumeric, unique client ID that your application code will use to call Authgear APIs through the Spring Boot . Note down the Authgear issuer (for example, https://example-auth.authgear.cloud/), CLIENT ID, CLIENT SECRET, and OpenID endpoints from the output. You will use these values in the next step for the client app config.
To create a new Spring Boot application you use the . Then you add dependencies to pom.xml file such as starter provides all the Spring Security dependencies needed to add authentication to your web application and Thymeleaf is used just to build a single page UI.
You have successfully configured a Spring Boot application to use Authgear for authentication. Now users can sign up for a new account, log in, and log out. The full source code of the examples can be found .
There is so much more you can do with Authgear. Explore other means of login methods such as using in an email, , or . For the current application, you can also from the Authgear portal.
An Authgear account. for free if you don't have an account yet.
(PHP package manager) installation
The first step you need to take is to create a new application or configure an existing application on the Authgear .
We'll use the PHP package for the configuration.
Here's a link complete source code for .
There's so much more you can do with Authgear and you can continue learning by checking out more topics on the .
This guide demonstrates how to add authentication with Authgear to a Python web application built with the framework using the OAuth library. The full source code for this sample project can be found on the .
A free Authgear account. if you don't have one already.
Make sure that 3.10 or above is installed on your machine.
Download and Install to manage project packages.
To use Authgear services, you’ll need to have an application set up in the Authgear . This setup allows users in Authgear to sign in to the Flask application automatically once they are authenticated by Authgear.
To set up the application, navigate to the and select Applications on the left-hand navigation bar. Use the interactive selector to create a new Authgear OIDC Client application or select an existing application that represents the project you want to integrate with.
An Authorized Redirect URI of your application is the URL that Authgear will redirect to after the user has authenticated in the Authgear to complete the authentication process. In our case, it will be a home page for our Flask and it will run at .
Set the following to the Authorized Redirect URIs field. If not set, users will not be returned to your application after they log in.
The application should now be accessible to open from a browser at .
There is so much more you can do with Authgear. Explore other means of login methods such as using in an email, , or . For the current application, you can also from the Authgear portal.
If you wish to , select "Issue JWT as access token".[^2] If you wish to , leave this unchecked. See comparisons in .
If you wish to , turn on "Issue JWT as access token".[^2] If you wish to , leave this unchecked. See comparisons in .
If you wish to , turn on "Issue JWT as access token".[^2] If you wish to , leave this unchecked. See comparisons in .
Implement Authgear to control access to your applications
Authgear simplifies the use of open industry standards like OAuth 2.0, and OIDC. Users can log into your applications with a variety of user login options. This set of how-to guides provides you with detailed instructions, code snippets, and configuration examples for each type of login method.
Decide how your backend application server authenticate the incoming HTTP requests.
For Mobile App or Single Page Web App or Website, each request from the client to your application server should contain an access token or a cookie. Your backend server should validate them for each HTTP request.
There are different approaches to verify the requests based on whether you validate JWT (JSON Web Tokens) in your server, or forward authentication to Authgear Resolver Endpoint.
Forward Authentication is a process where an intermediate reverse proxy or API Gateway is responsible for authenticating a request before it reaches the intended application or service. This can add an extra layer of security and centralize the authentication logic. An intermediate service forwards each incoming HTTP request to the Authgear Resolver Endpoint to verify the access token or cookie in the HTTP header.
Validate JSON Web Token (JWT) in your application server
Forward Authentication to Authgear Resolver Endpoint
Reliability
Medium JWT only updates when expire. That means before the token expiry, your application may see the user is valid even they has been disabled
High Update near real-time, based on your reserve proxy cache setting
Integration difficulties
Easy You only need to add code in your application to validate and decode JWT
Medium Need to setup extra reverse proxy to resolve authentication information
Validate JSON Web Token (JWT) in your application server
Forward authentication with Authgear Resolver Endpoint
Authentication for Express.JS apps with Authgear and OAuth2
Authgear makes it easy to add user authentication to a regular web app that is not powered by any framework. You can do this by implementing OAuth2 in your app with Authgear as the provider.
In this post, you'll learn how to add user authentication to an Express.js application using Authgear.
How to create an Authgear Application
How to sign in with Authgear from an Express app using an authorization code.
How to request user info from Authgear
You'll need the following to follow along with this tutorial:
Node.js Installed
A free Authgear account. Sign up for one here.
For this tutorial, we'll be building a simple Express app that has the following features:
A landing page with a login link that takes users to the login route.
A /login
route that redirects users to the Authgear OAuth authorization page.
Logic that exchanges the authorization code from Authgear for an access token.
A page that uses that access token to fetch user info from Authgear.
In order to use Authgear as an OAuth identity provider in your application, you need to configure an Authgear project. This project gives you all the credentials that you'll be using to send requests from your application.
Now let's create a new application.
Log in to the Authgear portal, and select your project. From the project dashboard, navigate to the Applications section and enter your application details as shown below:
Once you're done, click on Save to reveal the OAuth configuration. The application configuration page is where you can find your OAuth credentials like client ID, client secret, and a list of supported endpoints. Note down the configuration details as you'll use them later in your Express app.
You need to provide one or more URLs within your app for Authgear to redirect to after user authorization.
To add a URL, scroll to the URIs and click on the Add button. Enter the full URL for the page you wish to redirect users to after login. For our example app for this post, we'll set this URL to http://localhost:3000
.
It is now time to set up the Express app that will be interacting with Authgear. To do that, create a new folder with the name "express-auth-example", this will be your Express project folder. Next, run the following command from the project folder :
npm install express
We'll be using the Axios library to make HTTP requests in the example app. Install Axios to your project by running this command:
npm install axios
Once Express is installed, create a new app.js
file in the root of your project folder and add the following code to the file:
Note: Paste the correct values of client id, client secret, and redirect URL for your Authgear app inside the client
object in the config variable. Also, set tokenHost to the hostname part of your Authgear app endpoint URL. That is the part before the first "/". For example, tokenHost for https://example.authgear.cloud/oauth2/token
will be https://demo-1-ea.authgear.cloud
.
Run your app.js file using the node app.js
command. You should get a page like this on a web browser when you visit localhost:3000
:
Here we'll be implementing a local login endpoint in our Express app. This endpoint will handle requests from the above login link.
Add a new route to your express app using the following code:
Now if you save your code and restart your app, clicking on the login link should redirect to the Authgear authorization page.
After the user logs in and grants authorization to your app on Authgear, they are redirected back to the redirect URL you specified earlier. In addition to this redirect, an authorization code is sent via a code
URL query parameter.
In this step, we will be exchanging the authorization code for an access code that users can later use to access protected resources.
Update the code for the app.get("/")
route to the following:
The above code sends an HTTP POST request to the token endpoint. The authorization code we got from the previous step is sent along with other client credentials in the HTTP request body. The header should contain "Content-Type": "application/x-www-form-urlencoded"
A valid access token is returned in the response to the Axios response in response.data.access_token
.
We can now use this access token to make authenticated requests to protected resources in our app or from Authgear endpoint. In the next step, we'll attempt to get the current user's info from Authgear using the access token.
Authgear provides an endpoint where your application can request user info. This endpoint will return the user's details on Authgear like their email address, gender, full name, and more.
To get user info in our example app, in app.js, replace this line :
with the following code:
This code sends another HTTP request, but this time to the user info endpoint and the request type is GET. The access token is sent as a Bearer authorization header.
At this point, save all changes and restart the application. Try logging in all over again, at the end you should be greeted with "Welcome [your email address]".
And there you have it, you've successfully added user authentication to your Express app using Authgear as the OAuth provider.
You can add so much more to your app with the new Authgear authentication, like protecting your own app endpoint with the access code. You can also store the access token securely to persist the user session using express-session and cookies.
Authentication for Laravel websites with Authgear and OAuth2
In this guide, you'll learn how to add user authentication to a Laravel app using Authgear as an OIDC provider.
Authgear supports multiple ways to allow users to log in to apps such as passwordless sign-in, phone OTP, and 2FA. In this post, we'll show you how to enable all these options in your Laravel app without worrying about the underlying logic.
How to create an Authgear Application.
How to request OAuth 2.0 authorization code from Authgear.
How to get user info from Authgear using OAuth 2.0 access code.
Link user info from Authgear with Laravel's default Breeze authentication.
To follow along with the example, you should have the following in place:
A Laravel project.
The example app we'll build in this post uses the default Laravel Breeze authentication kit. This kit provides the starter code for email and password user authentication systems.
We will be using Authgear to handle and process authentication data instead of the default Breeze database. By doing so, we get all the benefits of Authgear including more security and flexibility.
In this section, we'll walk through the complete steps for building the example app.
Before we can use Authgear as an OAuth identity provider, we need to set up an application on the Authgear portal.
To do that, log in to Authgear then select a project. Next, navigate to the Applications section for your project. Create a new application or configure an existing one with OIDC Client Application as Application Type as shown below:
Once you're done, click on Save to go to the application configuration page. This page reveals the application credentials and OAuth 2.0 endpoints.
Note down details like the Client ID, Client Secret, and the endpoints as you'll use them later in your Laravel project.
While you're still on the application configuration page, scroll down to the URL section then click on Add URI. Enter localhost:8000/oauth/callback
in the text field if you will be running your Laravel app on your local machine. Once you're done, click Save.
The redirect URI we provided above should be a valid page on our Laravel app as Authgear will redirect users to the page after authorization.
Now create a new Laravel project on your computer by running the following command:
Once your project is created, open the project folder in your preferred code editor and replace the content of resources/views/welcome.blade.php
with the following code:
Alternatively, you can create a new index.blade.php
file in the resources folder and add the above code inside it. Then, update the web.php
route file to render the new file instead of welcome.blade.php
.
Next, run the php artisan serve
command in the terminal to test your application. At this point, your application should look like the following screenshot when you access localhost:8000 on a browser:
Breeze is the official user authentication starter kit for Laravel. What that means is that Breeze helps you set up the database, routes, controller, and user interface for a user registration and user login system.
To install Breeze on your Laravel project, run the following command:
After that, run the following command to enable Breeze to set up all the resources for the user authentication system in your project:
During the setup, select blade
as the stack and leave the other options as default.
Once the setup is complete, navigate around your project file structure and you should notice some new folders and files related to authentication were added. Some of these new folders/files include an Auth sub-folder in the controllers folder, another auth sub-folder inside the views folder, and some database migration files.
Before we continue, let's add an extra oauth_uid
field to the users
table migration file. This field will store a user's unique ID from Authgear after successful login.
Open the create_users_table...
file that is inside the database/migrations/
folder (this file will have a date value at the end of its name) and add the following code to a new line inside the Schema::create()
method:
Add the MySQL database DB_DATABASE
, DB_USERNAME
, and DB_PASSWORD
for the database you wish to use with your Laravel project in your Laravel project's .env
file.
Finally, create the users and other tables by running the following command:
In this step, we'll create a new route that will handle the task of redirecting users from our app to Authgear's OAuth authorization page where they can grant our app authorization to their data on Authgear. If you've used other OAuth 2.0 providers before, for example, signing in to a website using Google OAuth, you may already be familiar with an authorization page.
First, create a new controller that will handle all OAuth operations in our Laravel app by running the following command:
Before we start implementing the logic for our new controller, we need to install a PHP OAuth 2.0 client package. This package will simplify the process of interacting with Authgear's OAuth endpoints. Run the following commands to install the package:
Now, back to implementing the controller; open the new OAuthController file (from the app/Http/Controllers
folder) and add the following code to it:
Next, add your Authgear Application's Client ID, Client Secret, and the redirect URI you specified earlier to your Laravel project's .env file using the following keys:
Note: Your Authgear project URL is the hostname of any of your endpoint URLs. For example, the project URL for a project with an authorization endpoint: https://laravel-app.authgear.cloud/oauth2/authorize
will be https://laravel-app.authgear.cloud
.
Now let's create a route in our Laravel project that will call the startAuthorization()
method.
Open the routes/web.php
file and add new routes using the following code:
We've included a second route for the redirect URI (callback), we'll implement this route in the next step.
Before we continue, let's clean up some of the additional routes added by the Breeze package that we won't be needing for this example. Open the routes/auth.php
file and delete the following lines:
At this point accessing the /login
route should redirect to the Authgear authorization page.
Update the empty handleRedirect()
method in OAuthController to the following:
The above code gets the authorization code sent in the redirect URL from Authgear after user authorization and exchanges it for an access token. With this access token, our application can access protected resources like the user info endpoint.
In this step, we'll use the access token we got from the last step to get the current user's info from Authgear.
First, add the following code at the end of the handleRedirect()
method:
The getResourceOwner()
method will call Authgear's UserInfo endpoint.
If you dump the userInfo variable (dd($userInfo)
), you should get an output similar to this:
The above array contains the user's info from Authgear. We'll proceed to use this information to link the Authgear user to a default (Breeze) Laravel authentication account. As a result, our app can start a regular Laravel authenticated user session and allow access to protected routes.
To implement the above feature, find the following line in OAuthController.php:
Add the following code after the above line:
OAuth 2.0 access tokens expire after some time. The refresh token on the other hand live longer. As a result, you can use the refresh token to request a new access token. In this step, we'll do exactly that in our Laravel application.
First, app/Http/Controllers/ProfileController.php and update the content of the edit() method to the following:
The above code checks if the current access token is expired using the hasExpired()
method. If the condition is true, we call the getAccessToken()
method with the refresh token to get a new access token.
The value of the current access token is updated to the new access token.
Next, this edit() method also displays the current user's profile details from your Authgear project on the UI. To implement this, add the following code to resources/views/profile/edit.blade.php, just below the line with "<div class="max-w-7xl mx-auto sm:px-6 lg:px-8 space-y-6">
":
At this point, if we run our app and click on the login link on the landing page, we should be redirected to the Authgear authorization page. After granting authorization, we are directed to the callback route of our Laravel app. If authentication is successful we should be redirected to the default Breeze-protected dashboard page that looks like this:
To log a user out, we'll delete all existing PHP session data and then call the Authgear token revoke endpoint.
First, add a new logout function to the OAuthController.php file using the following code:
Then, open routes/web.php and update the logout route to the following:
You should try enabling the different login methods on Authgear from the Portal to enjoy features like 2FA, passwordless login, and more without updating anything on the code for your app.
Authenticate incoming request by cookie in the HTTP header.
By using Authgear, you can add a login to your website easily. Authgear supports various authentication methods, that you can easily turn on and configure in the portal.
To authenticate with cookies, you will need to set up a custom domain for Authgear, so that your website and Authgear are under the same root domains. e.g. Your website is yourdomain.com
, and Authgear with a custom domain auth.yourdomain.com
.
In this setting, if you have multiple applications under yourdomain.com
, all applications would share the same session cookies automatically.
Your app server will receive a request with the cookie
To verify the requests in your app server, you must Forward authentication to Authgear Resolver Endpoint.
The following tutorials show you how to add user login to your website using Authgear.
Decide how should the application requests be identified, either by access tokens or by cookies.
Authgear provides token-based or cookie-based authentication. You will need to decide which approach you are going to use before starting the setup.
This approach is suitable for mobile apps or single-page web applications.
In Token-based authentication, Authgear returns the access token
and refresh token
to the client app after authentication.
The client SDK will automatically renew the access token
with the refresh token
for you, so you don't have to worry about it.
Request example:
This approach is suitable for all types of websites, including server-side rendered applications.
In Cookie-based authentication, Authgear returns Set-Cookie
headers and sets cookies to the browser. The cookies are HTTP only and share under the same root domains. So you will need to setup the custom domain for Authgear, such as identity.yourdomain.com
.
Request example:
Authenticate the incoming HTTP requests by forwarding Authentication to Authgear Resolver Endpoint
In this section, we will explain how to set up a reverse proxy in NGINX to protect your app server from unauthorized access with the Authgear resolver. You can forward the requests without the request body to the resolver endpoint. Authgear will look at the Authorization
and Cookie
in the HTTP header, verify the token, and respond to HTTP 200 with X-Authgear-
headers for session validity, the user id...etc.
You can also use the forward authentication features of the other popular reverse proxy. e.g.
Authgear provides an endpoint for forward authentication. Subrequests should be made to the following endpoint for authentication.
https://<your_app_endpoint>/_resolver/resolve
After the user is logged in, send an application request to your server from the client app with access token/cookies.
Set up a reverse proxy in your infrastructure to authenticate HTTP requests. The reverse proxy will forward the incoming HTTP requests without the request body to the Authgear Resolver Endpoint.
Authgear resolver parses the access token and returns HTTP headers including the user login state. The headers are starting with x-authgear-
.
You have to instruct your reverse proxy to include those extra headers, before forwarding the request to your backend server.
Your backend server looks at the headers and responds to the client app accordingly. e.g. Returns the user's content or HTTP 401 if the user is not logged in.
There are so many reverse proxies available in the wild. So here we are going to illustrate the idea of using Nginx as the reverse proxy.
We will use the module auth_request
in NGINX. The module is not built by default, it should be enabled with the --with-http_auth_request_module
configuration parameter.
Run this command and verify that the output includes --with-http_auth_request_module
:
The trick here is to declare an internal location
and use auth_request
to initiate a subrequest to the resolved endpoint.
If the reverse proxy, Authgear, and your backend server are in different regions, authenticating every request could result in a huge downgrade in the performance.
You may consider enabling caching.
Authenticate the incoming HTTP requests by validating JWT in your application server
In this section, we will go through how to decode the JWT token to obtain the currently logged-in user.
Before we start, make sure the option Issue JWT as access token is enabled in your Application settings in the Portal.
With the Issue JWT as access token option turned on in your application, Authgear will issue JWT as access tokens. The incoming HTTP requests should include the access token in their Authorization
headers. Without setting the reverse proxy, your backend server can use your Authgear JWKS to verify the request and decode user information from the JWT access token.
This Discovery endpoint serves as a JSON document containing the OpenID Connect configuration of your app. It includes the authorization endpoint, the token endpoint, and the JWKS endpoint.
https://<YOUR_AUTHGEAR_ENDPOINT>/.well-known/openid-configuration
The JSON Web Key Sets (JWKS) endpoint can be found in jwk_url
in the configuration.
OpenID Connect Configuration JSON
Follow this step-by-step example to verify and decode the JWT token.
Define a function to find the JWKS endpoint from the OpenID Connect configuration. Use your Authgear endpoint as the base_address
Define a function to extract the access token from the Authorization header in the incoming request. It should look like Authorization: Bearer <access_token>
.
Here we show an example of using the Flask web framework to guard a path. You may need to adjust some of the codes to suit your technologies.
Use the following method to get the JWKS URI (you'll need to URI to extract the public signing key from a JWT).
Use the following code to extract only the token part from a Bearer [token]
authorization header in your Express app:
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:
Use the following code to extract the JWT public keys then verify the JWT using the keys:
Here's what your Express app should look like after putting the code in all the steps together:
Use your Authgear endpoint as base_address
First, install the dependencies required by running these com
Create a function that finds the JWKS endpoint from your Authgear application endpoint using the following code:
Add the following code to your application to get the JWT signing key:
To extract the access token from the HTTP request use the following code:
Finally, decode the JWT signing key.
Validating JWT in your application server is currently only available for Token-based authentication.
Authgear uses for secure data transmission, authentication, and authorization. Tokens should be parsed and validated in regular web, native, and single-page applications to make sure the token isn’t compromised and the signature is authentic.
Read more on guide.
This approach is only available for and involves passing the JWT token within the HTTP Authorization header. This approach is widely used in OAuth 2.0 and OIDC implementations, providing a standardized way to authenticate users.
JWT tokens can be stored in HTTP cookies and sent with each request. It is suitable for . Storing JWTs in cookies as a way to persist the user's session across requests. The server then uses JWKS to validate the token. This approach is useful in scenarios where you want to maintain user sessions across different services in a more traditional web application setup.
For Cookie-based authentication, JWT in cookies is not supported yet. .
Read more on guide.
Before processing the request, your server or a reverse proxy forwards the request to an . This endpoint resolves and verifies the authentication information (such as an Access Token) from the request Authorization Header.
In this pattern, Access Token (JWT) is stored in a cookie, and your server or a reverse proxy may contact the to obtain more information or validate certain aspects of the request.
Here's a link to the complete code for .
A free Authgear account. if you don't have an account yet.
Find the complete code for the OAuthController .
Find the complete code for the example app in our .
Your client app should call your backend with the access token in the Authorization header, and you can verify the access token by integrating Authgear with your backend. The HTTP requests can be authenticated by or .
In this setting, if you have multiple applications under yourdomain.com
, all applications would share the same session cookie automatically. After that, you can verify the cookies by integrating Authgear with your backend. The HTTP requests must be authenticated by .
If you use a popular reverse proxy on your deployment, such as , , or API Gateways such as , you can configure it with a few simple lines of forward auth config. Your backend should read the returned headers to determine the identity of the user of the HTTP request.
See docs for auth_request
in NGINX for more details.
See the list of x-authgear-
headers in the specs:
Here is .
The auth_time
claim in an OIDC ID token represents the time when the user authentication occurred. Extract the auth_time
claim from the token, which should represent the time of the original authentication in seconds. If the difference between the current time and auth_time
exceeds your threshold (for example, 5 minutes), initiate the process.
See an example of how to verify the signature of the ID token, and then validate the claims auth_time
inside .
For Cookie-based authentication, JWT in cookies is not supported yet. .
Token-based
Cookie-based
Suitable for
mobile apps or single-page web applications
Websites in the same root domain (e.g. Server-side rendered applications)
Transport of session
Access Token in Authorization
header
Session ID in Cookies
Passkeys give users a simple and secure way to sign in to your apps and websites across platforms without passwords.
Passkeys replace passwords and other passwordless login methods. It is built on the WebAuthn standard (also known as FIDO Sign-in), which uses public key cryptography to authenticate the user. With 1 click, Authgear upgrades your app to support this cutting-edge auth technology.
Users can log in to their accounts using their biometrics easily. On Apple devices, Touch ID and Face ID authorize the use of the passkey which then authenticates the user on the app or website.
Authgear adds a passkey feature to your apps and websites instantly. To enable it:
In your project portal, go to Authentication > Login Methods.
In the Select Login Methods section, turn on the Enable passkey support for compatible devices. toggle.
Press "Save" and your app now supports passkey login!
See the list of Passkey support via Authgear on different platforms.
macOS 12: Passkey is supported on major browsers. However, the credentials are deleted when clearing browser data.
iOS 15.5: Passkey is supported on Safari and stored locally a the device. Credential will be deleted by "Settings > Safari > Clear History and Website Data"
iOS 16 Beta 3: Passkey is synced with iCloud Keychain. The individual credentials can be viewed and managed in "Settings > Passwords"
Android 9 (API level 28) or higher: Supported.
Allow users to log into your app via OTP with WhatsApp, as a secure alternative to SMS
Authgear let your users login passwordlessly with WhatsApp OTP.
To enable this feature from the Portal:
Go to Authentication > Login Methods, we are going make few changes on this page.
In the top section of Select Login Methods, select Mobile.
In Authentication of Select Login Methods, select Passwordless.
In the tabs section below, switch to the tab Verification and OTP.
In the dropdown Verify phone number by, select either WhatsApp or SMS or WhatsApp only.
Press Save on the top left corner.
When the user login with their phone number, a WhatsApp message with an OTP and the app name will be received. They can copy the code by tapping on the "Copy code" button and log in by the code.
If "Verify phone number by WhatsApp or SMS" is enabled, the user can switch to receive the OTP via SMS instead in the login page.
Passwordless login with email links
Email Login Links, also known as "magic link", is a passwordless authentication method that allows users to log into a website or application without using a traditional password. Instead, it relies on a unique link sent to the user's email address.
Here's how it works:
User initiates the login process by entering their email address on the login page.
Authgear generates a unique, time-limited login link associated with the user's email address.
The link is sent to the user's email inbox, with a button prompting them to click on it to log in.
The user clicks on the link, and approve the login
The user is securely logged in to the app or website.
Magic link login offers several advantages. It eliminates the need for users to remember and manage passwords, reducing the risk of weak or reused passwords. It also simplifies the login process and reduces friction, as users only need to access their email to authenticate.
To enable Email Login Links:
In the Authgear Portal, go to "Authentication" > "Login Methods"
Select "Email" or "Mobile/Email" as login methods
Go to the "Verification and OTP" tab
Under "Email", in the "Verify email by" field, select "Login Link"
Authgear supports enabling biometric login in the native mobile application. You will need to
Enable biometric login in your application via the portal.
In the mobile app, use the mobile SDK to enable biometric login for your users.
A pair of cryptographic keys will be generated upon registering biometric login. The private key will be stored securely in the device (using Keystore in Android and Keychain in iOS), while the public key is stored in the Authgear server. To authenticate the user, fingerprint or face is presented to unlock the private key, and a digital signed message is sent to the server to proof the authenticity of the user.
Fig 1.0. The following figure shows the sequence for enabling Biometric Login on a supported device:
The Client App that is already logged in to a user's account will check if biometrics is supported by the user's device. If the device supports biometric login, it is then enabled. The public key is sent to Authgear server and associated with the logged-in user's account.
The flow is then completed and biometric login is enabled for the user on the Client App.
Fig 2.0. The following figure shows the sequence for a user logging in with Biometric:
With biometric login already enabled for the user, the next time they need to log in they can initiate a biometric authentication flow which will follow the sequence shown in Fig 2.0 above. Once the biometric login is successful, Authgear server will return an access token and a refresh token. The client application can then use the access token to make authenticated requests.
Sounds overwhelming? Authgear's magic handles all these for you. Follow this guide to enable biometric login with a few lines of code in your app.
In the portal, go to Authentication > Biometric.
Turn on Enable biometric authentication.
Save the settings.
Biometric login is usually used when you want the user to re-login after a relatively short period of time. For sensitive applications such as financial apps, it's recommended to use a short refresh token lifetime and a short idle timeout.
In the Authgear Portal, go to Applications
Select the client application that represent the integration with the mobile app
Set a short Refresh Token Lifetime to say 3,600 seconds (1 hour)
Enable Expire after idling
Set a short Idle Timeout, to say 1,800 seconds (30 minutes)
By doing so, the end-user's session will be expired 1 hour after their login, or after 30 minutes of inactivity. The end-user will need to authenticate themself again with biometric, even if the app process has not yet been killed.
Apart from the short token lifetimes, it's also common for sensitive apps to ask the user to re-login by biometric after the app process is killed and relaunched.
The SDK should be configured to use TransientTokenStorage so the tokens are stored in memory, and will be cleared when the app is closed. So the end-users must authenticate with biometrics again.
In the following section, we will show you how to use biometric login in the SDK. In the SDK code snippet, authgear
is referring to the configured Authgear container.
In the SDKs, a set of biometric options is required to check the support or enable biometric on the device.
There are two options on iOS:
localizedReason
is the message string the user will see when FaceID or TouchID is presented
constraint
is an enum that constraint the access of key stored under different conditions:
biometryAny
: The key is still accessible by Touch ID if fingers are added or removed, or by Face ID if the user is re-enrolled
BiometricCurrentSet
: The key is invalidated if fingers are added or removed for Touch ID, or if the user re-enrolls for Face ID
policy
can be used to allow users to log in with only biometrics, or using biometrics and the device PIN/password as fallback when biometric verification fails. The following are the available options:
BiometricLAPolicy.deviceOwnerAuthenticationWithBiometrics
: When this policy is set, users can ONLY use a biometric method to complete the login. Users cannot log in with their device PIN/password after a failed biometric login attempt.
BiometricLAPolicy.deviceOwnerAuthentication
: enable this policy to allow users to log in with non-biometric local authentication methods like device PIN/password when biometric verification fails or is not enrolled on their device.
There are 6 options on Android:
title
is the Title of the biometric dialog presented to the users
subtitle
is the subtitle of the biometric dialog presented to the users
description
is the description of the biometric dialog presented to the users
negativeButtonText
is what the dismiss button says in the biometric dialog
Always check if the current device supports biometric login before calling any biometric API, including before enabling biometric login and before using biometrics to login.
Enable biometric login for logged in user
Before asking the user to log in with biometric, Check if biometric login has been enabled on the current device. I.e. Is the key pair exist on the device (Keystore in Android and Keychain in iOS).
This method will still return true even if all the fingerprint and facial data has been removed from the device. Before this method, you should use the "checkBiometricSupported" to check if biometry is supported in the device level.
If biometric is supported and enabled, you can use the Authenticate Biometric method to log the user in. If the key pair is invalidated due to changes in the biometry settings, e.g added fingerprint or re-enrolled face data, the biometricPrivateKeyNotFound
will be thrown. You should handle the error by the Disable Biometric method, and ask the user to register biometric login again.
In all methods related to biometric, the SDK may throw the following errors that describe the status of the biometry enrollment or the key pair stored on the device.
In some use cases, you may want to provide an alternative means for users to log in when biometric verification fails on their devices. For example, in a case where a user's finger is dirty (touch-based) or when the user's face is covered (Face ID).
In the biometric options, the parameters policy: BiometricLAPolicy.deviceOwnerAuthentication
(iOS) and constraint BiometricAccessConstraintAndroid.DeviceCredential
(Android) can be used to allow users to enter their device PIN/Password when biometric verification fails.
The biometric pop-up will look like this after a failed biometric log-in attempt with BiometricLAPolicy.deviceOwnerAuthentication
policy on iOS:
With the BiometricLAPolicy.deviceOwnerAuthenticationWithBiometrics
policy, the biometric login pop-up will not include the Enter Passcode button. An example is shown below:
Login with NFTs help developers build Web3 apps without blockchain knowledge
Sign In With Ethereum(also known as SIWE) introduces a new way of authenticating and identification of a user using their crypto-wallet addresses. Authgear saves you from all the complex setups and brings you the technology of the future with just a simple click.
To make this as simple as possible, the following mainstream consumer-facing web3 providers are selected to be the gateway connecting your application and users.
These providers are typically supported by browsers with WebExtensions API, namely Chrome, Firefox, Edge, and Brave.
To assist you in building the greatest NFT-gated application ever, Authgear adds extra information to the user info that indicates whether the user owns NFT/NFTs of your selected NFT collection.
At the current stage, the following token types are supported:
Here is an example of such user:
To enable "Sign In With Ethereum" to your apps and websites:
In your project portal, go to "Authentication > Ethereum & NFT"
Turn on the "Login With Ethereum" toggle
Select your favourite blockchain network from the "Network" dropdown below
To prevent Web2 and Web3 identities being mixed together, Authgear has made it so that enabling "Sign In With Ethereum" would disable all your previously enabled identities and primary authenticators.
To go back to using Web2 authentication methods, you will have to disable "Sign In With Ethereum" and reconfigure your identities and authenticators.
To populate user info with NFT tokens from the collections of your choice:
In your project portal, go to "Authentication > Ethereum & NFT"
Ensure "Login With Ethereum" toggle is checked
Select the blockchain network from the "Network" for where your NFT collection is based on
In the "NFT Collections" section, press "Add Collection", this will add an extra text field to the section
Enter the contract address of the NFT collections in the "Contract Address" text field
Select the token type of the contract address
In the case of an ERC-1155 being selected, you will be prompted with a token tracking dialog
Enter the desire token IDs and press "Continue"
Press "Add" and you will see your collection is now in the pending collection list
If an error is shown that states that your NFT collection is not supported, it is possible that the collection has an alternative implementation of the ERC-721 or ERC-1155 standard
The passkey standard is supported on the latest versions of Chrome, Safari, and Firefox browsers. On iOS 16 and macOS 13 (Ventura), to the iCloud Keychain service. Passkeys are also (API level 28) or higher. A passkey is synchronized and relayed with an iCloud account and can be used across a user's devices.
Besides the built-in support of all major desktop and mobile platforms, passkeys can also be stored in hardware security keys such as , which provide the highest security against attacks.
See reference in Apple Developers Doc on and .
constraint
is an array that defines the requirement of security level, which can be BIOMETRIC_STRONG
, BIOMETRIC_WEAK
, DEVICE_CREDENTIAL
. See reference in Android developers documentation on
invalidatedByBiometricEnrollment
is a boolean that controls if the key pair will be invalidated if a new biometric is enrolled, or when all existing biometrics are deleted. See reference in Android developers documentation on .
You can set the policy for iOS and constraint for Android in the of the Authgear SDK. The following is an example of a biometric options that allows users to use device's PIN/Password in iOS and Android:
The Sign In With Ethereum standard is built on the specification, which is typically performed on Web3 providers.
In the object of a user, the wallet address and the NFTs owned can be found.
Press "Save" then "Confirm" and now your app supports Sign in with Ethereum!
Press "Save" then "Confirm" and your app is now monitoring the NFT collection!
Allow guest users to use your apps and website and promote to regular users later.
You can use create an Anonymous User account for the guests in your apps, so they can carry out interactions just like a normal user. For example, guests can post comments and save preferences in your social platform before setting email and password. The user session will persist even if the app has been closed.
This improves the app experience because the user does not need to set up authenticators until further down the user journey, while still enjoying most of the app features. For app developers, the ability to create and assign Anonymous User also makes it easier to link the activities of an individual before and after sign-up.
In the portal, go to Authentication > Anonymous Users.
Turn on Enable anonymous users.
Save the settings.
This will create an Anonymous User for the session. Subsequent requests from the end-user in the session can be identified by the same sub
UserInfo
promoteAnonymousUser
function can be called to promote an anonymous user to a regular user with login ID (e.g. email, phone number) and authenticators (e.g. password). The end-user will be prompted a sign up page to complete the promotion. The sub
of an end-user will remain the same after promotion.
Step 1: Start the promotion flow
When the user clicks promote on your website, make a start promotion call to redirect them to the promotion page.
Step 2: Handle the promotion result
After the user promotes on the promotion page, the user will be redirected to the redirectURL
with a code
parameter in the URL query. In the redirectURI
of your application, make a finish promotion call to handle the promotion result.
On Mobile SDKs, creating an anonymous user will create a key-pair. The key-pair is stored in the native encrypted store on the mobile device. The end-user can always re-login to the same anonymous user with the key-pair. Such anonymous user will become inaccessible when the encrypted store is removed.
On the Web SDK, there will be no key-pair created. Therefore the end-user will not be able to login to the same Anonymous User after the their session become invalid. For cookie-based authentication, it is controlled by the "idle timeout" and "session lifetime" of the Cookie. For token-based authentication, it is controlled by the "idle timeout" and "token lifetime" of the Refresh Token.
In other words, The anonymous user account lifetime is the same as the logged-in session lifetime.
To adjust the lifetime settings, change the timeouts and lifetimes in Portal > Applications accordingly.
You should create anonymous users only when necessary in the user journey to prevent creating excessive orphan accounts in your tenant.
Reference on what the OAuth 2.0 parameter is and how to use it in Authgear SDK.
The authorization server (Authgear) will include the value of the state parameter when redirecting the user-agent back to the client application. As a result, the client application can retrieve the value of state
returned to verify that it is the origin of the authorization request.
In this post, we'll cover some possible usage of the state
parameter and how to include the state
parameter in an authorization request to the Authgear server.
The following are some use cases of the OAuth 2.0 state parameter.
Because the value for the state parameter passed at the beginning of an authorization request is returned unchanged after authorization, you can use this behavior to customize the post-login or sign-up user experience.
For example, you can show users some custom messages after they sign up or log in, using a special link that was sent to them via email or SMS. The "special" thing in the link would be the value of a query parameter that can be passed in the state
parameter.
Then, a client application can read the value of the state
parameter and based on that, determine when and how to display the custom message or user experience.
Another possible use of the state
parameter is analytics and tracking user behavior. You can use the state token to include a unique key that tracks your campaigns. This way, you can know the number of users who sign up or log in to your application from a particular campaign.
Cross-site Request Forgery or short CSRF is a type of web security vulnerability where the attacker uses malicious means to trick a user into performing undesired actions on sites they use and trust. This type of attack usually targets users who are signed in and attempts to compromise access to their protected resources.
In OAuth, an attacker can perform a Cross-site Request Forgery using the client application's redirect URI. The attacker can trick a user into using a redirect URI that contains their authorization code or access token. Hence the user will end up using the access token and protected resources of the attacker. When they save new data using this access token, the attacker can also view them (as they are the original owner of the protected resources).
The official Authgear SDKs have mechanisms for protecting your applications from CSRF built into them.
However, if you are not using the official SDK, you can secure your application by generating a random hard-to-guess value on the client application and passing it in the state
parameter. Your application should store this value securely on the user's client-side using session cookies or some other form of local storage. Then, verify the state
parameter in the redirect URI against the value stored locally to confirm that a user-agent is the origin of an authorization request before exchanging the authorization code for an access token.
The following URL shows an example of an authorization request URL:
As you can see from the above URL, state
is a query parameter in addition to other parameters like the client_id
and redirect_uri
.
If you're constructing the authorization URL manually, you can include the state parameter by simply appending "&state=random_state_value
" to the authorization URL.
Alternatively, if you're using any of the Authgear SDKs, you can use the built-in state
field to set a value.
The following code samples show the use of the state parameter with Authgear.
First, install the Authgear web SDK by running the following command:
Next, configure Authgear in your React Project's index.tsx file like this:
Set the state
field in your call to the startAuthentication()
method of the Authgear SDK to a random hard-to-guess value based on your use case.
Implement the component that handles your OAuth 2.0 redirect like this:
The above code will read the value of the state parameter returned in the redirect and compare it to the initial value.
For this example, when the initial value of the state
parameter before authorization is not the same as the value returned in the redirectURL, we halt the authentication process.
Next, configure your PHP to use Authgear like this:
The League OAuth 2.0 client we are using in this example helps us generate random strings for the state
parameter. In the above code, we store the value for the state generated in session on the line with $_SESSION['oauth2state'] = $provider->getState()
;.
Add an else block for the if (!isset($_GET['code']))
condition with the following code:
The above code will prevent your PHP application from exchanging an authorization code for an access token when the value of state
stored in the PHP session is not identical to the state returned in the redirect URI. The usage demonstrated above can prevent CSRF attacks.
Authgear provides an easy method to reauthenticate the end-users. You can use this as a security measure to protect sensitive operations.
Your sensitive operation server endpoint MUST require the ID token. When you receive the ID token, you MUST verify the signature of it. If the signature is valid, you can trust the claims inside the ID token.
The auth_time
claim in the ID token tells when was the end-user last authenticated. You should check the auth_time
claim to see if the end-user was authenticated recently enough.
The https://authgear.com/claims/user/can_reauthenticate
claim in the ID token tells whether the end-user can be reauthenticated. If the value of this claim is false
, then depending on your business needs, you can either allow the end-user to proceed, or forbid the end-user to perform sensitive operations. The flows are illustrated by the following diagrams.
The following code snippets illustrate the interaction between the SDK and Authgear.
If the end-users in your application often perform a series of sensitive operation, it is annoying that they have to reauthenticate themselves repeatedly before every operation. To allow the end-users to skip reauthentication if they have just reauthenticated themselves recently, the SDK allows you to inspect the last authentication time of the end-user.
Finally in your backend, you have to verify the signature of the ID token, and then validate the claims inside.
Learn how to add authentication to any web page without using Authgear's SDKs with IIFE(Immediately-invoked Function Expression) bundle
Start with making a new folder on your computer to keep the app’s source code (In the example, we call it authgear-spa-js-login
). Then, initialize a new NPM project by running the following command:
Next, we install two required packages:
Next, open the package.json
file and edit scripts entry to have start
and dev
commands like the below:
Now you can run the app in two modes: prod and dev.
For example, npm run dev
will run the application using nodemon
, monitoring for changes as we modify files.
Create a new file server.js
in the root of the project and populate it with the following code:
Create a index.html
file in the root of the project and add the following content to the created file:
Create a new folder called public
folder in the project root folder and create another folder called css
inside the public
folder. Add a new file in there called main.css
. This will be used to determine how the log-in and log-out button elements will be hidden on the main page depending on whether a user is authenticated or not.
Open the newly-created public/css/main.css
file and add the following CSS:
After creating an HTML file and applying CSS styles, see now how our page looks like by running npm run dev
and accessing it at http://localhost:3000.
To add some action to the page, we create a new directory in the public
folder called js
, and add a new file there called app.js
. Copy and paste the following JS code that reads authgear_config.json
file Authgear app-specific values (endpoint
and clientId
) from the endpoint using fetchAuthConfig
function. Also, it configures a new Authgear client, and defines login and logout logic:
Let’s breakdown down app.js
code in the previous section and understand how authentication is achieved with Authgear:
Configure the Authgear client
fetchAuthConfig
: Firstly, this function makes a request to the /authgear_config.json
the endpoint we exposed in server.js
to fetch Authgear app setting values from authgear_config.json
file.
configureClient
: Once we retrieve the configuration information for the Authgear client from the authgear_config.json
file and we set up the Authgear client with these settings. It also logs a message to the console, informing whether the configuration was successful or not.
Login flow
login
: The function is called by the Login button previously defined on the HTML page. It performs the login action by calling authgearClient.startAuthentication
Authgear’s function. It redirects the user to the Auhthgear login page. After the user logs in successfully, they will be redirected back to the same page we set in redirectURI
. Run the project and click the Login button. You should be taken to the Authgear Login Page configured for your application.
After authenticating successfully, you will be redirected to the page you were before.
Logout flow
Update the UI
window.onload
: This is a function that runs when the page loads. It configures the Authgear client and updates the UI. If the page's URL contains a "code=" it means the user is authenticated (code
the query will be received from the Authgear server), it updates the UI again and removes the "code=" from the URL.
Evaluate the authentication state
updateUI
: This function updates the status of the login and logout buttons based on whether the user is authenticated or not. In Authgear, you can check if the user has logged in or not with sessionState
the attribute. If the user is authenticated, we disable the login button and enable the logout button, and vice versa if the user is not authenticated.
How to pass the Apple Store review process if your app uses passwordless login.
However passwordless login via email/phone OTP cannot be used in the review because the reviewer do not have access to the email inbox or phone number of that demo account.
You can create a demo account with email/phone and password by turning password on temporarily. In the project portal:
Go to Authentication > Login Methods.
In Select Login Methods, select Custom.
In the tabs section below, select the tab Custom Login Methods.
In Custom Login Methods, activate Password.
Go to User Management, press Add User in the command bar.
Create the demo user by entering the email address and password
Go to where you were in Step 4, deactivate Password.
Now you can login as the demo user in your app with the email and password.
Submit your app for review with the credentials.
Guide on how to add Two-Factor Authentication to your application.
Authgear supports Two-Factor Authentication (2FA) or Multi-Factor Authentication (MFA) for additional layers of security in your application.
When you enable MFA on your application, Authgear will require your users to present two or more factors in order to log in. These factors could be their password and a One-time Password (OTP) that is sent to their registered email address or phone number. As a result, an attacker can not gain access to a user's account with only a compromised password.
In this post, you'll learn how to enable MFA or 2FA for your Authgear project and how to configure 2FA grace period.
An Authgear Project.
You can enable 2FA and configure other settings from the 2-Factor Authentication page in Authgear Portal.
To open the 2-Factor Authentication page, log in to Authgear Portal, select your project, then navigate to Authentication > 2FA.
Next, use the 2FA Requirements dropdown on the 2-Factor Authentication page to set when to require users to use 2-Factor Authentication to sign in.
The available options are:
Disabled: When this is selected, 2FA will not be required to log in for any user, including users who already have 2FA set up for their account.
Optional: This policy will only require 2FA to log in for users who already have 2FA set up for their account. Users who have not set up 2FA can continue to log in without it.
Toggle the Show "Do not ask again on this device" for 2FA switch on if you wish to require 2FA only the first time a user logs in from a specific device.
The Available 2-Factor sub-section on the 2-Factor Authentication page shows a list of supported second-factor authentication methods. The supported methods include:
Google Authenticator/Authy
Additional Password
OTP Code/Login Link via Email
OTP Code via Phone
Check the box for each 2FA method you wish to enable for your project.
Use the up and down allows on the right of each method to order the priority of the 2FA methods.
Once you're done, click on the Save button at the top-left of the 2-Factor Authentication page to keep your new settings.
The 2FA Grace Period feature grants your users some time to set up 2FA for their accounts. This is very helpful for the Mandatory enforcement of 2FA.
The following are the two types of 2FA grace periods you can set for your Authgear project:
Global Grace Period: When this type of grace period is enabled, all users who do not have 2FA set up for their account will be asked to set up 2FA the next time they log in. When the Global Grace Period is disabled, users who have not set up 2FA for their account cannot log in. Instead, they'll get an error message requesting them to contact an admin.
Individual Grace Period: This is a type of grace period that is set per user. It grants a user 10 days to set up 2FA for their account. This is ideal for allowing individual users to set up 2FA when the Global Grace Period is disabled.
The following steps show how to roll out Mandatory 2FA using grace periods:
Change 2FA requirement policy to Mandatory
Enable Global Grace Period so that all users who haven't set up 2FA are required to do so the next time they login.
Use your own channel to notify user's about the duration of the global grace period you've decided.
Disable the Global Grace Period once the date you notified users of has passed. After you do this, users that still haven't set up 2FA will be unable to log in.
To enable the Global Grace Period, navigate to Authentication > 2FA in the Authgear Portal. Then, set 2FA Requirements to Mandatory so that you can view the Enable global grace period switch.
Toggle the Enable global grace period switch on so that your users without 2FA will be required to set up 2FA the next time they log in. Or set Enable global grace period off, if you do not want users without 2FA to log in, or set up 2FA without contacting an admin.
When you set the 2FA requirement for your project to Mandatory and Global Grace Period is turned off, you can still use the individual grace period to grant a specific user a grace period to set up 2FA for their account.
To set individual grace period, navigate to User Management > User in Authgear Portal. Then, select the user you wish to set individual grace period for by clicking on the row with their ID in your project's users' list.
From the selected user's details page, click on the Account Security tab, then the Grant grace period to set up 2FA button. You will see a prompt to confim your action, click Confirm to continue.
The duration of the individual grace period is 10 days. However, you can extend or cancel it from the user's details page.
Authenticate incoming request by access token in the HTTP header.
By using Authgear, you can add the login feature to your mobile native app and single-page application easily. Authgear supports various authentication methods, that you can easily turn on and configure in the portal.
Your app server will receive a request with the access token
To verify the request in your app server, you can choose to Forward authentication to Authgear Resolver Endpoint or Verify JSON Web Token (JWT) in your app server.
The following tutorials show you how to add user login to your native mobile or single-page app using Authgear.
Choose your platform below:
Using Authgear as an OpenID Connect Provider for any OIDC compatible applications.
If your application supports logging in using an OpenID Connect provider, you can use Authgear as the provider.
Go to Applications on the left menu bar.
Click ⊕Add Application in the top tool bar.
Input the name and select the application type OIDC Client Application. Click "Save".
You will see a link to this guide that can help you for setting up, then click "Next".
In the URIs section, fill in the Authorized Redirect URIs with your application's redirect uri.
Obtain the OpenID Connect configuration:
You can obtain the Client ID and Client Secret from the Basic Info section.
You can obtain the OIDC Endpoints from the Endpoints section.
Provide the OpenID Connect configuration to your application.
🎉 Done! You should be able to use Authgear to log in to your application.
In this section, we are going to demonstrate how to use Authgear as the OIDC provider for WordPress login.
Go to Setting > OpenID Connect Client.
Fill in the form
Client ID: Obtain the Client ID from the Basic Info section.
Client Secret Key: Obtain the Client Secret from the Basic Info section.
OpenID Scope: Space separated list of scopes the plugin could access.
Example: openid offline_access https://authgear.com/scopes/full-userinfo
.
https://authgear.com/scopes/full-userinfo
is needed to obtain user's profile (e.g. email). Otherwise the plugin will be able to get the user id only.
Login Endpoint URL: Obtain Authorization Endpoint from the Endpoints section.
Example: https://{AUTHGEAR_APP_DOMAIN}/oauth2/authorize
.
Userinfo Endpoint URL: Obtain Userinfo Endpoint from the Endpoints section.
Example: https://{AUTHGEAR_APP_DOMAIN}/oauth2/userinfo
.
Token Validation Endpoint URL: Obtain Token Endpoint from the Endpoints section.
Example: https://{AUTHGEAR_APP_DOMAIN}/oauth2/token
.
End Session Endpoint URL: Keep it empty.
Identity Key: Where in the user claim to find the user's identification data.
Suggest to use sub
which is the user id in Authgear.
Setup the user claim keys based on your project login method setting.
If your project is using email to login
Nickname Key: Set it to email
.
Email Formatting: Set it to {email}
.
If your project is using phone to login
Nickname Key: Set it to phone_number
.
Email Formatting: Clear it.
If your project is using username to login
Nickname Key: Set it to preferred_username
.
Email Formatting: Clear it.
At the bottom of the plugin settings page, you will be able to obtain the Redirect URI. Go to Authgear portal, add the uri to the Authorized Redirect URIs.
Settings for requiring users to reset their password if they haven't logged in after specific number of days
You can set up your Authgear project such that a user's password expires after a specific number of days. When a user logs in after the password expiry date, they'll see a prompt to change their password before they're redirected back to your app.
In this post, you'll learn how to set the Password Expiry feature in the Authgear Portal.
To enable password expiry, first, log into the Authgear portal, select your project then navigate to Authentication > Login Methods. Next, select a Login method that supports password, then switch to the Passwords tab and scroll to the Password Expiry section. Toggle the "Force password change on next login if it has expired" button to enable password expiry.
You can use the text field labeled Force change since last update (days) to specify the number after which a user's password should expire. The value should be the number of days in the future from the last date the user set or updated their password. For example, setting the value to 90 means the user's password will expire 90 days later from the last date they set or updated their password.
Once you're done, click on the Save button at the top of the page to keep your changes.
If you are building token-based websites or mobile apps, you can enable the SSO feature via the SDK.
When SSO-enabled is ON, the end-user will need to enter their authentication credentials when they login to the first app. Later on, when they login to the second app, they will see a continue screen so that they can log in with just a click, without authenticating themselves again.
When the end-user logout the SSO-enabled app, all the apps will be logged out at the same time.
You can turn on this feature when you configure the SDK by setting the is sso enabled option to true
.
These type of SSO requires sharing the cookies between mobile apps and the system browsers on mobile, hence underlying it use ASWebAuthenticationSession
on iOS and Custom Tab
on Android, which will show a popup box like this:
Provide a seamless user experience across multiple applications with the single sign-on feature.
Single sign-on (SSO) is defined as login once, logged in all apps. If you have multiple mobile apps or websites that wants to streamline the user experiences. You can configure your apps to turn on the SSO feature, so the end-users only have to enter their authentication credentials once.
There are multiple ways to achieve Single Sign-on, with various pros-and-cons:
Setting up the local development environment for websites that use cookie-based authentication.
This guide is only for cookie-based authentication in local development setups. A typical scenario is developing websites. If you are developing mobile applications which use token-based authentication, you can just skip this guide and continue with it as usual.
Authgear sets a cookie in the browser inside the project domain. When running your application on localhost
, the browser will not see the cookies because the website is not in the subdomain of the domain in which the cookies are set. Therefore, the browser will not be able to authenticate itself.
For local development, it is highly recommended to create a new application on Authgear before continuing to the rest of the guide.
Go to the Application tab in your dashboard
Add your local application domain {SUBDOMAIN}.{PROJECT_NAME}.authgear.cloud
under the Allowed Origins list
Add an application, name it whatever you want. DO NOT check the Issue JWT as access token box because we are using cookie-based authorization.
Put your redirect URI for login and logout under the Redirect URIs list and Post Logout Redirect URIs list respectively.
hosts
To make the cookies visible to the browser, the local website domain has to be inside the domain where the cookies are set.
By adding the following line to the /etc/hosts
file on the local machine, we can point the application domain name to localhost.
The browser will be able to see the auth cookies if visiting the website via this domain.
Although you can see the cookies now, the cookies have the Secure attribute set. To include them in an HTTP request, the request has to be transmitted over a secure channel (HTTPS in most browsers). Therefore, we also need to establish HTTPS connections for our browser with the server.
A key file and a cert file will be generated. They will be used in the next part of the guide.
We will need an nginx server to serve the certificate and enable SSL.
Add the following config file to your nginx/conf.d
directory, or mount it to a volume together with the cert and key if you are using nginx in docker.
The examples below show the nginx config files for nginx in host and nginx in docker.
Now visit the website through https://<yourapp>.authgear.cloud
, and the browser will be able to send requests with the authorization cookies.
Learn how to configure different options for password reset/account recovery.
The Forgot/Reset Password settings tab allows you to configure the behavior of the account recovery process for your Authgear project to meet your specific needs. For example, you can use this feature to determine whether to deliver recovery code to users via SMS, WhatsApp, or email.
In this post, you'll learn the various configurations available via the Password Settings tab and how to navigate to the page.
To access the Password Settings page, log in to your Authgear account, select your project, and then navigate to Authentication > Login Methods.
Next, select your current Login Method (Email, Mobile, Mobile/Email, or Custom). The login method you select affects the options available for you to customize.
Scroll down to just below the Select Login Methods section and click on the Password tab to reveal the Password settings screen.
Note: Make sure the login method you select has password enabled (you can not view the password settings screen if you only enable Passwordless login).
When you enable password reset by phone number for your project, users will receive an OTP code that they can enter in the AuthUI to finish the account recovery flow.
To able this feature, first in the Password Settings tab, select a Login Method that supports Mobile (E.g Mobile or Mobile/Email methods) and has the password option enabled.
Next, click on the "Reset password with phone by" dropdown then select how you want to send the OTP from the available options. The available options include SMS, WhatsApp, and WhatsApp or SMS.
Once you're done save your changes to enable the new configuration.
The next time your users try to reset their password using their phone number as the login ID, they should see a screen like this to enter the OTP sent to their phone:
If you prefer your users receive an OTP that they can enter in the AuthUI instead of a recovery link that they would normally click, you can use this password recovery settings to enable that.
To enable this setting, click on the "Reset password with email by" dropdown in the Password Settings tab. Then, select the One-time Password (OTP) option. Save your changes to enable the feature.
Learn how to take users directly to an external OAuth provider's authorization page without opening AuthUI login page.
You can use Authgear's x_oauth_provider_alias
parameter to add social/enterprise login to your application without showing any AuthUI pages. To do this, you must enable the Social/Enterprise only login method for your project in Authgear Portal.
In this post, you'll learn how to use the x_oauth_provider_alias
parameter to skip AuthUI and take users directly to a social/enterprise login provider's authorization page.
In this post, we'll walk through the steps for adding only the social/enterprise login method to an Authgear application.
We'll use the Authgear SDK for React Native to set the x_oauth_provider_alias
parameter and show how to use x_oauth_provider_alias
without the SDK in an example Express app.
The sequence diagram above demonstrates the flow for using x_oauth_provider_alias
to skip AuthUI.
First, when the user clicks on the sign-in button, your application will call your Authgear project's authorize
endpoint with the x_oauth_provider_alias parameter appended.
Next, when Authgear server receives the call, it redirects to the third-party OAuth (Social/EnterpriseLogin) provider's authorization server. The user is then shown the OAuth provider's login/authorization page for them to grant authorization. Once that is done, the OAuth provider returns an authorization code to Authgear.
In the next step, Authgear exchanges the authorization code for an access token, refresh token, and ID token and then starts creating a new user or logging the existing user in.
The rest of the flow from there involves the usual sending of the authorization code to the client application and the client application exchanging the authorization code for an access token, refresh token, and ID token.
The first step is to add the Social/Enterprise login provider you wish to use to your Authgear project. For our example, we'll be adding Facebook.
To add a new provider, log in to Authgear Portal, select your project, then navigate to Authentication > Social/Enterprise Login.
Next, click on the Edit button, then enter the Client ID and Client Secret for the Social/Entreprise login provider then click Save. Also, note the value for Alias as you'll use it in a later step.
An important step for making Authgear to skip AuthUI is to enable the Social/Enterprise only login method. By doing this, Authgear will understand that the only login method your app will use is from a third-party OAuth provider. As a result, it's ok to skip showing AuthUI for login, registration, or login method selection and go to the OAuth provider's authorization page directly.
To enable Social/Enterprise only, navigate to Authentication > Login Methods. Next, select the Social/Enterprise only Login Method and click Save.
Now that you've set up everything to allow your application to use only Social/Enterprise Login, you can open Authgear's authorize
endpoint with the x_oauth_provider_alias
parameter to start an authorization request that will skip AuthUI.
We will show 2 ways to do this. The first is using the SDK and the second is by passing x_oauth_provider_alias
as a URL query parameter.
The following example shows how to add x_oauth_provider_alias
using the Authgear React Native SDK:
Note that the value for oauthProviderAlias
must be the Alias for the social/enterprise provider you configured in step 1.
You can manually add x_oauth_provider_alias
parameter to the Authgear authorization endpoint when you're not using the Authgear SDK.
The following example shows how to add x_oauth_provider_alias
to the Authgear authorization endpoint:
The above code will append &x_oauth_provider_alias=facebook
to the authorization URL.
Perform faster authentication flow via another app installed on the same device.
This may be familiar for users from UK, which many neobanks are using the app2app mechanism to authorize the money transfer from 1 bank app to another.
The App2App mechanism allows one app to authenticate the user using another apps connected to the auth server installed on the same device. This is achieved by universal links and the apps do not need to share the session via the system browser or the refresh tokens via the token storage.
The session cannot be shared via the browser cookies
The session cannot be shared via a common token storage
An app can start the authentication flow by opening a link to another app, instead of using the authorization endpoint. The app which handles the link should validate the authentication request, then could return a valid authorization code. The valid code is then transferred to the original app using universal link. The initiating app can use that authorization code to perform code exchange for tokens with Authgear.
Go to the Application detail page of the authorizing app, i.e. the app which handles the app2app authentication requests.
Scroll to the bottom and you will see the App2App config panel.
Migration mode offers a less secure mechanism which helps older user sessions to participate in App2App. DO NOT enable it unless there is migration problem.
Go to the Application detail page of the initiating app, i.e. the app which initiates the app2app authentication requests.
In the redirect URIs, a universal link that's capable of opening this app should be set.
Define and set up the universal links for both apps, for example:
https://a.example.com/authorize
should open the authorizing app (App A)
https://b.example.com/redirect
should open the initiating app (App B)
In App B, call startApp2AppAuthentication(options: App2AppAuthenticateOptions)
to initiate the app2app login
App2AppAuthenticateOptions.authorizationEndpoint
should be an url of an universal link pointing to App A, i.e. https://a.example.com/authorize
App2AppAuthenticateOptions.redirectUri
should be an URI for the authorizing app to return the authentication result. It must be an universal link which opens the current app. i.e. https://b.example.com/redirect
In App A, upon receiving the app2app login request
Call parseApp2AppAuthenticationRequest(url: URL): App2AppAuthenticateRequest?
The result will be null
if the url is not a valid app2app request.
You can approve or reject the app2app request in App A
Approve: approveApp2AppAuthenticationRequest(request: App2AppAuthenticateRequest)
Approves an app2app request returning the result through the redirect URI.
request
should be the return value of parseApp2AppAuthenticationRequest
.
This method must be called when then SDK session state is AUTHENTICATED
, and the current session supported app2app authentication by providing a device_key
, or else an error will be thrown.
Reject: rejectApp2AppAuthenticationRequest(request: App2AppAuthenticateRequest, error: Error)
Rejects an app2app request, returning an error through the redirect URI.
request
should be the return value of parseApp2AppAuthenticationRequest
.
error
is the reason to reject the request.
When it's back to App B, call handleApp2AppAuthenticationResult(url: URL)
This method should be called by the app which initiate the app2app authentication flow, and when received the result through the universal link, url
should be the URL of the universal link received.
After "signing up" as an anonymous user, you can and see the sub
of the end-user.
The includes an optional state
parameter. The value of the state
parameter can be any random string or number defined by a client application (e.g. a web or mobile that uses Authgear for user authentication) before making an authorization request. In fact, the state
parameter is added to the authorization URL as a URL query.
You can also use the value you specify in the state
parameter in an analytic tool (for example, as id
in the identify(id)
function) to track user's behavior pre-login and post-login.
To learn more about using the state parameter for tracking user behavior, see our detailed guide .
Create a new React project or use an existing project and configure the project to use Authgear. The following example is based on our .
This example uses the PHP package. Install the package using the following command:
Reauthentication in Authgear is built on top of the . The ID token is a JWT.
In this guide, you'll make a simple website server to host the SPA app using . We'll also use it to serve our HTML page and any assets it needs, like JavaScript, CSS, and so on. You can also view a on the GitHub repo.
Before we start, ensure you have Node.js installed in your system. If not, download and install it from the .
An Authgear account: You need an Authgear account to follow this guide. If you don't have one, you can on the Authgear website.
A Registered App: You need a registered application type (Single Page Application) in Authgear. Follow the guide and skip part. You will retrieve the Authgear Web SDK from Authgear's CDN using IIFE(Immediately-invoked Function Expression) bundle and reference a script in our HTML directly.
Also, install so that our server can be restarted automatically on any code changes in dev mode:
We do not use a package manager such as , we will retrieve the Authgear Web SDK from Authgear's CDN using IIFE(Immediately-invoked Function Expression) bundle. We can reference a script in our HTML directly:
You can install the Authgear Web SDK as a dependency of your application, it is useful if you are building React or React Native apps. See how to .
Go ahead and create a new user or log in using an email (we specified the Passwordless Email login method in the first part). When you try to log in with your email, you should receive a to your email box to confirm login operation.
logout
: This function logs the user out and redirects them back to the original page (at). It uses Authgear’s logout
function and logs a message to the console indicating the result of the operation.
When you try to publish a mobile app on the Apple AppStore, there will be an . You need provide a demo user account for the reviewers to access the features of the app.
An Authgear account. Create one for free .
And basic experience with Authgear.
Mandatory: Use the mandatory policy to require 2FA for all users. That means users who have not set up 2FA will not be able to log in if no grace period is set. To use this option, consider further actions like .
When users that could not set up their 2FA during the Global Grace Period contact you (the admin), enable individual grace period for them using the instructions in .
Follow the previous section () to setup an OIDC Client Application.
We are going to use plugin . Or you can use any other OIDC compatible plugin. Download and activate it in your WordPress site.
By default, password expiry is turned off for your Authgear project. shows that forcing users to change their password after some time can do more harm than good.
If you want to avoid the said popup box, you will need to use WKWebView
on iOS and WebKitWebView
on Android for UIImplementation
instead; And use for sharing login session between mobile apps, and between mobile and web instead.
is not trivial. This guide provides a simple way to bootstrap your local application that communicates with the production Authgear server.
You can learn more .
Log in and create a new project on
One quick simple way to do this is to use , you may follow the installation steps . After installing mkcert, generate a certificate with the following command:
In the above examples, nginx will also authenticate requests by creating sub-requests to the Authgear internal endpoint. You can learn more .
For implementing login and logout logic in your website, please refer to .
An Authgear account. Create one for free .
See our guide for instructions on how to get a Client ID and Client Secret for Facebook Login.
The key thing about using the above option is the presence of oauthProviderAlias: 'facebook'
in the authenticate()
method of the Authgear SDK. This parameter tells Authgear to redirect directly to an OAuth provider, given that the Social/Enterprise provider is configured properly as shown in . Also, the Social/Enterprise only Login method is enabled.
This is an Enterprise feature, please contact us for using the App2App flow in your project at
Please note that this is not the Single Sign-on feature, if your are offering multiple apps under the same brand and wish the users to use a shared login session among their apps in the device, you may want to use instead. App2app should be used when:
A detailed explanation on the technology can be found in .
This is an Enterprise feature, please contact us for enabling the App2App flow in your project at
Select Enable App2App login for this Application"
Add third-party identity providers to enable frictionless sign in for your users
Authgear supports the following social and enterprise identity providers. Please click the link below for setup instructions.
Guides on how to add social login providers like Facebook, Google, LinkedIn Apple
Use the pre-authenticated URLs feature to open a website from a native app in an authenticated state.
Pre-authenticated URLs is a feature that enables single sign-on (SSO) from a mobile application to a website. It allows users who are authenticated on a mobile application to open a website in an authenticated state.
An example use case for a pre-authenticated URL is opening a web application in a WebView.
To use pre-authenticated URLs, you must have the following:
An Authgear application of type Native app.
A second Authgear application that has pre-authentication URLs enabled.
First, ensure your mobile application uses an Authgear application with the Native App.
Your application must also enable SSO to allow pre-authenticated URLs to work. You can enable SSO by isSSOEnabled: true
in the configure()
method of Authgear SDK.
Next, add an allowed origin to the web application client in Authgear. Navigate to Applications in the Authgear Portal, select the web application client, and scroll to the Allowed Origins section. Then, add the origin you wish to use for Pre-authentication URLs. Note that the origin should be of the format "protocol (scheme) + domain + port". For example, if the mobile application wants to open https://www.mywebapp.com/home?key=value
, the origin must be https://www.mywebapp.com
.
The Pre-Authenticated URL is a link that the Authgear SDK can generate for a mobile client that has the Pre-Authenticated URLs feature enabled. Your mobile application can open the Pre-Authenticated URL in a web view for users to start browsing the origin in an authenticated state.
To generate the Pre-Authenticated URL, call the makePreAuthenticatedURL(
) method of the Authgear SDK as shown below:
The makePreAuthenticatedURL()
method accepts an object as a parameter. Inside the object, you should provide your web application's client ID and redirect URI.
The URL in YOUR_WEB_APP_URI
should be a page on the web application that calls the authenticate()
method of Authgear SDK with isSSOEnabled: true
(or a page that initiates an authorization request) .
After the makePreAuthenticatedURL()
return the URL, your mobile application should open the URL in a WebView. From there, users should be able to continue their current authenticated session (from the mobile app) on the web application.
The following code sample shows how to open the pre-authenticated URL using the Linking.openURL()
method of React Native.
The user will see a "Continue Screen" and will not need to enter their credentials again to log in.
Force Authgear to always show login page even if the user have already logged in.
When user login / signup to Authgear, it usually starts with your application making a request to the authorization endpoint, which leads to a login or signup screen.
If the user is already signed in on the browser, the Single Sign On feature will show a "Continue Screen" instead as follows.
If your application do not want to utilize the Single Sign On feature, and always show the login / sign up screen instead, you can force Authgear to show login page by using prompt="login"
at the authorize
endpoint.
The following code shows how to set prompt: "login"
in Authgear SDKs:
Guides on how to use Authgear as a SAML Identity Provider
SAML allows the Identity Provider and Service Provider to authenticate and authorize without exchanging a user's password.
The Service Provider (SP): In SAML, this is the service that trust the Identity Provider to handle the process of user authentication.
The Identity Provider (IdP): handles user authentication and notifies the Service Provider once the user is authenticated.
Authgear supports the SAML protocol. Hence, you can set up third-party services like Salesforce, Dropbox, Figma, etc. to trust Authgear with the user authentication process.
See the following guides for some popular service providers:
To set up SAML in Authgear, you need to create an Authgear client application with the Application Type: OIDC/SAML Client
. Then use the configuration for the Authgear client application to configure a SAML IdP on the Service Provider's platform.
The following steps show more details on how to set up an OIDC/SAML Client Application in Authgear Portal.
Log in to Authgear Portal, then click on Applications from the navigation menu.
Click on Add Application to create a new client application. Or select an existing client application with the OIDC/SAML Client
type.
Enter a Name for the application and select OIDC/SAML Client Application as the Application Type.
Click Save to proceed.
By default, the SAML 2.0 Configuration is disabled for the client application.
Click on the SAML 2.0 tab then toggle SAML 2.0 Support switch to enable SAML 2.0.
You'll be required to enter at least one Allowed Assertion Consumer Service URLs (ACS URLs) before you can save your changes. Hence, get an ACS URL from the Service Provider you plan to use.
Visit the portal for the Service Provider you plan to use and add Authgear as an Identity Provider using the SAML configuration from your Authgear client application.
Refer to the following instructions for a generic SP:
Configuration on SP:
Enter the Identity Provider Metadata URL provided by Authgear if it's supported by the SP. e.g. https://[AUTHGEAR_ENDPOINT]/saml2/metadata/[CLIENT_ID]
If the SP does not support uploading an IDP metadata file, you can manually enter the parameters into the SP. These values can be copied from the application settings page:
Issuer: urn:[AUTHGEAT_ENDPOINT]
Login URL: https://[AUTHGEAR_ENDPOINT]/saml2/login/[CLIENT_ID]
Logout URL: https://[AUTHGEAR_ENDPOINT]/saml2/logout/[CLIENT_ID]
Identity Provider Certificates in PEM format: Download from the application settings page
Configuration on Authgear
Upload the Metadata XML file provided by your client application into the Authgear Portal
You may also manually enter the parameters into the application settings page in the Portal:
NameID Format
urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified
, or
When the format is unspecified
, you can choose to use the User ID, Email, Phone, or Username as the attribute value
urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress
Allowed Assertion Consumer Service URLs (ACS URLs)
Response Destination (Optional)
Subject Recipient (Optional)
Assertion Audience (Optional)
Assertion Valid Duration (seconds), Default: 1200
Enable/Disable Single Logout (SLO)
SLO Callback URL
Callback Binding
urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect
, or
urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST
Enable/Disable message signature verification
Upload the SP's certificate in PEM format
You may find more detailed guides for adding IdP on the Service Provider's documentation.
Guide on how to use Authgear as a SAML IdP for Dropbox
Security Assertion Markup Language (SAML) is a standard that allows an Identity Provider (IdP) and a Service Provider (SP) to perform user authentication and authorization without exchanging a user's password.
In this post, you'll learn how to set up Authgear as an Identity Provider and Dropbox as a Service Provider.
An Authgear account. Sign up for free.
A Dropbox Business Advanced account.
You need an Authgear client application of type OIDC/SAML Client Application
to use Authgear as a SAML identity provider.
To create a new client application, log in to Authgear Portal, select your project then click on the Applications link from the navigation menu.
Next, click on Add Application to create a new client application. Alternatively, select an existing application of type OIDC/SAML Client Application
and skip to step 2.
On the New Application page, enter Name and select OIDC/SAML Client Application
as the Application Type.
Click Save to proceed.
By default, SAML 2.0 is not enabled for the client application.
To enable SAML for your client application, click on the SAML 2.0 tab then toggle the SAML 2.0 Support switch on.
Next, change NameID Format to urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress
.
Add the following URL (Dropbox post-back URL) in Allowed Assertion Consumer Service URLs (ACS URLs) field:
Click on Save to keep your changes.
Scroll down to the Configuration Parameters section of your Authgear client application's SAML 2.0 tab. Note the value for the login URL.
Also, download the Identity Provider Certificate for the client application to your computer.
You'll use the Login URL and certificate later in the Dropbox Admin console.
Log in to your Dropbox Business Advanced account then click on Admin console in the navigation menu.
In the Dropbox Admin console navigate to Settings > Single sign-on.
Now in the Dropbox Single sign-on settings page, set Single sign-on to Required. Then, configure the following:
Paste the value for your Authgear client application's Login URL
in the Identity provider sign-in URL
field.
Under X.509 certificate, click on the Certificate upload button, then upload the Identity Provider Certificate you downloaded from your Authgear client application in the previous step.
To test your SAML implementation, you need to add a new user to your Dropbox with an email address that is associated with a user account in your Authgear project.
To add a new user to your Dropbox, navigate to Admin console > People > Members > Invite member.
Accept the invite for the new user, and try to log in to Dropbox using the registered email address for the new user. You should be redirected to the Authgear SAML login page. On successful login to the Authgear account, you should be redirected and signed in to Dropbox.
A guide on how to use Authgear as a SAML Identity Provider IdP in Salesforce
The Service Provider (SP) trust the Identity Provider to handle the process of user authentication. The Identity Provider handles user authentication and notifies the Service Provider once the user is authenticated.
In this guide, you'll learn how to set up SAML with Authgear as an Identity Provider (IdP) and Salesforce as the Service Provider (SP) in SAML.
A Salesforce account.
An Authgear Client application is required to set up Authgear as a SAML Identity Provider. To create an Authgear application, login to the Authgear Portal and navigate to the Applications in your project.
Click on Add Application to create a new application. Or, select an existing application that is of type OIDC/SAML Client Application
and skip to step 2.
Now on the New Application page, enter a name for your application (e.g. My App) and set the Application Type to "OIDC/SAML Client Application".
Click Save to continue.
If prompted to view a tutorial, click Next to proceed to the application configuration page.
On the configuration page of your Authgear client application, switch to the SAML 2.0 tab. Toggle the SAML 2.0 Support switch on to enable SAML for the application.
Next, change NameID Format to urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress
.
Enter your Salesforce domain in the Allowed Assertion Consumer Service URLs (ACS URLs) field under SSO Settings. You can get value for your Salesforce domain from the My Domain page on the Salesforce Setup page.
Click on Save to keep your changes.
Still, on the SAML 2.0 tab, scroll to the Configuration Parameters section and click on the Download Metadata button to download the Identity Provider Metadata XML file for your Authgear application to your computer.
Next, scroll to the Identity Provider Certificates section and click Download Certificate to download the certificate to your computer.
You will use the downloaded metadata file and certificate in later steps.
To enable SAML in Salesforce, login to your Salesforce account, click on the Settings icon on the top right corner then select Setup. This will open the Salesforce Setup page.
On the Setup page, type "single sign-on" in the Quick find search box on the left. Select Single Sign-On from the result to open the Single Sign-On Settings page.
Next, click on the Edit button under Select Single Sign-On Settings then check the SAML Enabled box under Federated Single Sign-On Using SAML. Click Save to keep your changes.
To add Authgear as a SAML Identity Provider, return to the main page of Single Sign-On Settings.
On the next screen, you should see configurations for your new SAML IdP, including the details from the metadata file. Edit the Name field to Authgear SAML. The value for the Name field will be visible on your Salesforce login page.
Once you're done with the above configurations, click Save to finish.
In order to log in with a specific SAML IdP, you must first enable the provider in Salesforce.
To enable your new SAML IdP (Authgear SAML) search for "my domain" in Quick find. Click on My Domain from the result. On the My Domain page, scroll to Authentication Configuration then click on the Edit button.
You should find your Authgear SAMP IdP under Authentication Service. Check the box next to Authgear SAML to enable it. Click Save to keep changes.
Once you have enabled your SAML Identity provider in this step, it will be visible on your Salesforce login page the next time you attempt login.
Force you can log in to your Salesforce project using Authgear SAML, you need to create a user using an email address that is linked to a user account in your Authgear project.
To create a user in Salesforce, use type "users" in the Quick find search box, then select Users > Users from the result. This will take you to the All Users page.
From the All Users page, click on New User. Create a new user with an email address that's linked to an account on your Authgear project.
Now, to test your SAML implementation, log out of Salesforce and attempt logging in again. This time, you should see a Login with Authgear SAML button.
When you click on Login with Authgear SAML, you should be redirected to Authgear Login page. Login to the account on your Authgear project that has the same email address as the new user you created earlier in this step. You should be successfully logged in to your Salesforce project.
SSO between Websites with the same apex domain
Requires all of the websites with the same "root domain" (e.g. app1.example.com and app2.example.com)
SSO between Mobile Apps and Browsers
Requires the use of ASWebAuthentication
and Custom Tab
on iOS/Android respectively
SSO between two independent mobile apps
Based on OIDC App2App
SSO from a Mobile App to Website
Open a URL from Mobile App and pass the user session along, based on OIDC Token Exchange
SSO between Mobile Apps from the same publisher
Keychain Sharing / Android Account Manager ( if you need it)
Requires both apps published by the same publisher from App Store.
The prompt="login"
parameter which is defined in the can force AuthUI to show the login page. Authgear SDKs have a prompt
parameter that can be used to set prompt="login". Once the prompt
parameter is set to login
Authgear will always show the login screen when your application calls the SDK's authenticate method.
Security Assertion Markup Language or short is a standard for exchanging security information between businesses. In SAML, one party acts as the Identity Provider (IdP), and the other party is the Service Provider (SP).
Security Assertion Markup Language or short is a standard for exchanging security information between businesses. In SAML, one party acts as the Identity Provider (IdP) and the other party is the Service Provider (SP).
An Authgear account. for free.
Next, click on the New from Metadata File button. Then, click Choose file, and select the Metadata XML file you downloaded in . Click on Create to continue.
Next, click on the Choose file button next to Identity Provider Certificate then select the SAML IdP Certificate file you downloaded in from your computer.
Add Facebook Sign in to your apps in less than 5 minutes.
This guide shows how to connect your Authgear application to Facebook so users can log in using the Login with Facebook feature.
If you are using Authgear in your existing Facebook Apps, you may skip to the next step to set up the OAuth client.
On the next screen, select Other as your app use case then, click Next.
In the app type selection screen, pick the option that best meets your requirements. For our example, we'll select the Consumer app type.
Enter your app name on the next screen and finish the app creation process.
In the app panel, click Add Product next to Products in the sidebar.
Click the Set Up button in Facebook Login.
Go to Settings of Facebook Login.
Make sure Client OAuth Login and Web OAuth Login are enabled.
Add https://<YOUR_AUTHGEAR_ENDPOINT>/sso/oauth2/callback/facebook
to Valid OAuth Redirect URIs and save the changes.
After setting up the Facebook Login product, go to App settings > Basic in the sidebar.
You will need the App ID and App Secret to configure Facebook Login so, note them down.
In the portal, go to Authentication > Social / Enterprise Login.
Enable Login with Facebook.
Fill in the Client ID with the App ID obtained from the Facebook Developers portal in the previous step.
Save the settings.
🎉 Done! You have just added Facebook Login to your apps!
Add Google Sign in to your apps in less than 5 minutes.
To configure Google OAuth client for Authgear, you will need to create an OAuth client on Google Cloud Platform first.
Click Create Credentials -> OAuth client ID
Choose Web application in Application type and assign a name as reference. You should always choose Web application here regardless of the platform of the app you are creating. It is because this OAuth Client ID is used by your Authgear services, which is a web application in Google’s classification.
Add https://<YOUR_AUTHGEAR_ENDPOINT>/sso/oauth2/callback/google
to redirect URIs.
After creating a client ID, you will see the client ID under the OAuth 2.0 Client IDs section of the Credentials page.
After creating an OAuth client, click the name of OAuth client to view the details.
You will need the values of Client ID, Client secret to configure Google Sign In.
In the portal, go to Authentication > Social / Enterprise Login.
Enable Sign in with Google.
Fill in the Client ID and Client Secret with the values obtained from the previous step.
Save the settings.
🎉Done! You have just added Google Sign In to your apps!
In the "Products" section, choose "Sign In with LinkedIn"
In the details page of the created app, click the "Auth" tab
Take notes of "Client ID" and "Client Secret", add https://<YOUR_AUTHGEAR_ENDPOINT>/sso/oauth2/callback/linkedin
to "Redirect URLs" in "OAuth 2.0 settings" section
In the portal, go to Authentication > Social / Enterprise Login.
Enable Sign in with LinkedIn.
Fill in Client ID.
Fill in Client Secret.
Save the settings.
🎉 Done! You have just added Linkedin Login to your apps!
To configure "Sign in with Apple" for Authgear, you will need to fulfil the following:
Register an Apple Developer Account. Apple Enterprise Account does not support "Sign in with Apple"
Register your own domain.
Your domain must be able to send and receive emails.
Click "Configure" the Next to "Sign in with Apple". In "Primary App ID" field, select app ID created above.
Fill in and verify the domain created above, add https://<YOUR_AUTHGEAR_ENDPOINT>/sso/oauth2/callback/apple
to Return URLs
In the portal, go to Authentication > Social / Enterprise Login.
Enable Sign in with Apple.
Fill in the Client ID with the Service ID obtained above.
In Apple Developer Portal, view key information of the "Key" created above.
Jot down the Key ID and download the key text file (.p8
file).
Copy the content in the key text file to Client Secret text area in Authgear Portal..
Fill in Key ID field using the Key ID obtained from step 5.
In Apple Developer Portal, click username on the top right corner, click View Membership.
Find the Team ID from Membership Information, fill in Team ID field in Authgear portal.
Save the settings.
🎉Done! You have just added Sign in with Apple to your apps!
In "Authorization callback URL", use https://<YOUR_AUTHGEAR_ENDPOINT>/sso/oauth2/callback/github
.
After the creation, click "Generate a new client secret". Remember the client secret.
In the portal, go to Authentication > Social / Enterprise Login.
Enable Sign in with GitHub.
Fill in Client ID.
Fill in Client Secret.
Save the changes.
🎉 Done! You have just added GitHub integration to your apps!
You will need a Facebook developer Account. Register as one by clicking Get Started in the website.
To create a new app, go to the Facebook Developers panel then click the Click Create App button.
See for instructions on how to get the value for YOUR_AUTHGEAR_ENDPOINT
.
Your end-users can now sign in with Facebook on Authgear's pre-built Log In and Sign Up page. Existing end-users can connect their account to Facebook in the page.
Create a project on Google Cloud Platform through . If you are adding Authgear to your existing Google Cloud Platform projects, you may skip to the next step to create the OAuth client.
After creating a new project, you will need to configure the OAuth consent screen. Press the button on the top-left and go to APIs & Services -> OAuth consent screen and follow the instruction to create the consent screen.
Go to -> APIs & services -> Credentials
You can find more details in
Your end-users can now sign in with Google on Authgear pre-built Log In and Sign Up page. Existing end-users can connect their account to Google in the page.
Create an app in the .
Set up (SPF) for your domain.
Set up (DKIM) for your domain.
Create an "App ID" by adding a new "Identifier" , choose app IDs, enable "Sign in with Apple" enabled.
Create a "Services ID" by adding a new "Identifier" , choose service IDs, enable "Sign in with Apple".
Create a "Key" following with "Sign in with Apple" enabled. Click "Configure" next to "Sign in with Apple" and select "Primary App ID" with app ID created above. Keep the private key safe, you need to provide this later.
Follow the to create a OAuth App.
Setup your own AD FS server
Create an application in your AD FS Server, obtain "Client ID", "Client Secret" and "Discovery Document Endpoint". Discovery Document Endpoint typically ends with /.well-known/openid-configuration
. Configure your application with redirect uri https://<YOUR_AUTHGEAR_ENDPOINT>/sso/oauth2/callback/adfs
.
In the portal, go to Authentication > Social / Enterprise Login.
Enable Sign in with Microsoft AD FS.
Fill in Client ID, Client Secret and Discovery Document Endpoint.
Save the settings.
🎉 Done! You have just added Microsoft AD FS Login to your apps!
Guides on how to integrate identity providers to Authgear
Choose "Supported account type", the following options are supported:
Accounts in this organizational directory only (Contoso AD (dev) only - Single tenant)
Accounts in this organizational directory (Any Azure AD directory - Multitenant)
Accounts in this organizational directory (Any Azure AD directory - Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox)
"Personal Microsoft accounts only" is not supported yet. Remember the account type chosen as this affects the configuration on Authgear portal
Configure "Redirect URI" with https://<YOUR_AUTHGEAR_ENDPOINT>/sso/oauth2/callback/azureadv2
In the portal, go to Authentication > Social / Enterprise Login.
Enable Sign in with Microsoft
Fill in Client ID with Application (client) ID of your just created Azure AD application.
Fill in Client Secret" with the secret you get after creating a client secret for your Azure AD application.
For Tenant field:
If single tenant (first option) is chosen, fill in the Directory (tenant) ID of your Azure AD application.
If multi tenant (second option) is chosen, fill in the string literal organizations
.
If multi tenant and personal account (third option) is chosen, fill in the string literal common
.
Save the settings.
🎉 Done! You have just added Azure Active Directory (Azure AD) Login to your apps!
Configure "Redirect URI" with https://<YOUR_AUTHGEAR_ENDPOINT>/sso/oauth2/callback/azureadb2c
.
After creating the user flow, configure it
Open "Application Claims".
Make sure "Email Addresses" is checked.
If you have finished the above prerequisite, you should have the following information:
The Tenant Name, obtained in Step 2
The Application (Client) ID, obtained in Step 5
The Policy (User flow) Name, obtained in Step 7
Then in Authgear portal, do the following:
In the portal, go to Authentication > Social / Enterprise Login.
Enable Sign in with Microsoft Azure AD B2C.
Fill in Client ID with the Application (Client) ID above.
Fill in Client secret with the client secret you get when you create the app registration.
Fill in Tenant with the Azure AD B2C Tenant Name.
Fill in Policy with the Policy (User Flow) Name. Normally it starts with b2c_
.
Save the changes
🎉 Done! You have just added Azure AD B2C Login to your apps!
Use OIDC prompt parameter to force OAuth providers to show login screen.
In this post, you'll learn how to use prompt: "login"
in Authgear SDKs to force OIDC providers to always show your users their login screen. You can also use prompt: "login"
to allow users to switch accounts with a Social/Enterprise Login provider on the same device (or browser).
Authgear SDKs have a prompt
parameter that you can set in your application. The value of the prompt parameter will be passed to the Social/Enterprise Login provider. Hence, if you set prompt: "login"
in the SDK, your Social/Enterprise Login provider will receive a prompt="login"
parameter. The following code examples show how to use the prompt parameter in Authgear SDKs.
To create a website application in WeChat, you can choose to setup a website application and wait for approval or a sandbox account for testing.
Create Website Application (网站应用), fill in information and wait for approval (It may take few days).
View the application detail page, obtain the "AppID" and "AppSecret" on the top of the application page.
Go to Account Center > Basic information, to obtain the "原始ID".
Obtain the "appID", "appSecret" and "原始ID". The "原始ID" is the "微信号" in the top right corner.
Fill in 接口配置信息. The URL must be pointing at a publicly reachable server. The token is a string of your choice.
Implement the 接口配置信息 server. Here is an example written in Golang.
Fill in JS接口安全域名. The value is your Authgear domain name plus port, e.g. 192.168.2.88:3000
or myapp.authgear.cloud
Fill in 网页授权获取用户基本信息. The value is your Authgear domain name plus port, e.g. 192.168.2.88:3000
or myapp.authgear.cloud
Look for an QR code in the sandbox settings page. You must scan it with your Wechat app and follow the sandbox account.
In the portal, do the following:
In the portal, go to Authentication > Social / Enterprise Login.
Enable Sign in with WeChat (Web/网站应用).
Fill in Client ID with the AppID.
Fill in Client Secret with the AppSecret.
Fill in 原始 ID with the 原始 ID.
Check the checkbox Is Sandbox account if you are using sandbox account.
Save the settings.
Wechat integration is a bit more complicated then other social login, here are the overview of what needs to be done:
Register an account and create mobile application in WeChat Open Platform. Approval is needed in this process.
Enable and configure WeChat Login in Authgear portal.
Include Authgear SDK on your app.
Implement a delegate function to be triggered when user clicks the "Login with WeChat" button during authorization. You need to integrate WeChat SDK to open WeChat app to perform authentication in the delegate function (we have sample code below). After obtaining the authorization code from WeChat, call the Authgear callback with the auth code and complete the "Login With WeChat" process.
Here are the detailed steps for iOS, Android, React Native, and Flutter.
Create Mobile Application (移动应用), fill in information and wait for approval (It may take few days).
View the application detail page, obtain the AppID
and AppSecret
on the top of the page.
Go to Account Center > Basic information, to obtain the "原始ID".
Save those values, we will need them in the section below.
Setup Authgear iOS SDK.
After setting up the WechatOpenSDK
, universal link should be enabled in your application. We will need two links for the setup. One is for the WeChat SDK used, another is for the Authgear SDK to trigger delegate function when user click "Login with WeChat" button. Here are the suggestion of the links.
WECHAT_UNIVERICAL_LINK: https://{YOUR_DOMAIN}/wechat
WECHAT_REDIRECT_URI_FOR_AUTHGEAR: https://{YOUR_DOMAIN}/open_wechat_app
Login WeChat Open platform, open the application detail page, update the development information iOS section.
Fill in "Bundle ID" field with your app bundle id.
Fill in "Universal Links" with "WECHAT_UNIVERICAL_LINK" above.
Go to Authgear portal, do the following:
In the portal, go to Authentication > Social / Enterprise Login.
Enable Sign in with WeChat (Mobile/移动应用).
Fill in Client ID with the AppID.
Fill in Client Secret with the AppSecret.
Fill in 原始 ID with the 原始 ID.
Add WECHAT_REDIRECT_URI_FOR_AUTHGEAR above in WeChat redirect URIs.
Save the settings.
Update the code
Setup WeChat SDK when app launch
Setup Authgear delegate and call WeChat SDK when sendWechatAuthRequest
is triggered
Handle universal link
Provide wechatRedirectURI
when calling authenticate
and promoteAnonymousUser
in authgear sdk
Setup Authgear iOS SDK.
Login WeChat Open platform, open the application detail page, update the development information Android section.
Fill in application signature, you can obtain it with command keytool -list -v -keystore YOUR_KEYSTORE_FILE_PATH
. WeChat needs the certificate fingerprint in MD5, remove :
in the fingerprint. It should be string in length 32.
Fill in your package name
We will need to define a custom url for Authgear SDK to trigger delegate function when user click "Login with WeChat" button. Here is the example, you should update it with your own scheme.
"WECHAT_REDIRECT_URI_FOR_AUTHGEAR": com.myapp://host/open_wechat_app
Go to Authgear portal, do the following:
In the portal, go to Authentication > Social / Enterprise Login.
Enable Sign in with WeChat (Mobile/移动应用).
Fill in Client ID with the AppID.
Fill in Client Secret with the AppSecret.
Fill in 原始 ID with the 原始 ID.
Add WECHAT_REDIRECT_URI_FOR_AUTHGEAR above in WeChat redirect URIs.
Save the settings.
Update the code
Update application AndroidManifest.xml
Configure WeChat SDK
Setup Authgear delegate
Create wxapi directory in the directory named after your package name and create WXEntryActivity
activity. In WXEntryActivity
, pass the received intent and the object that implements IWXAPIEventHandler API to the handleIntent
method of the IWXAPI
API, as shown below:
You will be able to receive the authentication code and state in onResp
method, call Authgear wechatAuthCallback
with code
and state
.
Provide wechatRedirectURI
when calling authorize
and promoteAnonymousUser
in Authgear SDK.
Setup Authgear SDK
In iOS, after setting up the WechatOpenSDK, universal link should be enabled in your application. We will need two links for the setup. One is for the WeChat SDK used, another is for the Authgear SDK to trigger delegate function when user click "Login with WeChat" button. Here are the suggestion of the links.
IOS_WECHAT_UNIVERSAL_LINK: https://{YOUR_DOMAIN}/wechat
IOS_WECHAT_REDIRECT_URI_FOR_AUTHGEAR: https://{YOUR_DOMAIN}/open_wechat_app
In android, you need to sign your app to use WeChat SDK. Obtain your application signature by running command keytool -list -v -keystore YOUR_KEYSTORE_FILE_PATH
with your keystore file. WeChat needs the certificate fingerprint in MD5, remove :
in the fingerprint. It should be string in length 32.
Login WeChat Open platform, open the application detail page, update the development information iOS and Android sections.
In iOS
Fill in "Bundle ID" field with your app bundle id.
Fill in "Universal Links" with "IOS_WECHAT_UNIVERSAL_LINK" above.
In Android
Fill in application signature.
Fill in your package name
For android, we will need to define a custom url for Authgear SDK to trigger delegate function when user click "Login with WeChat" button. Here is the example, you should update it with your own scheme.
ANDROID_WECHAT_REDIRECT_URI_FOR_AUTHGEAR: com.myapp://host/open_wechat_app
Login Authgear portal, go to "Single-Sign On" page, then do the following:
Enable "Sign in with WeChat (Mobile/移动应用)"
Fill in "Client ID" with the WeChat "AppID".
Fill in "Client Secret" with the WeChat "AppSecret".
Fill in "原始 ID" with the WeChat "原始 ID".
Add "IOS_WECHAT_REDIRECT_URI_FOR_AUTHGEAR" and "ANDROID_WECHAT_REDIRECT_URI_FOR_AUTHGEAR" above into "WeChat redirect URIs"
Click save.
Update the code
In Android, Update application AndroidManifest.xml
.
In iOS, update your App Delegate
Provide wechatRedirectURI
when calling Authgear SDK authorize
and promoteAnonymousUser
in js
Setup Authgear delegate and open WeChat SDK when sendWechatAuthRequest is triggered
Setup Authgear SDK
In iOS, after setting up the WechatOpenSDK, universal link should be enabled in your application. We will need two links for the setup. One is for the WeChat SDK used, another is for the Authgear SDK to trigger delegate function when user click "Login with WeChat" button. Here are the suggestion of the links.
IOS_WECHAT_UNIVERSAL_LINK: https://{YOUR_DOMAIN}/wechat
IOS_WECHAT_REDIRECT_URI_FOR_AUTHGEAR: https://{YOUR_DOMAIN}/open_wechat_app
In android, you need to sign your app to use WeChat SDK. Obtain your application signature by running command keytool -list -v -keystore YOUR_KEYSTORE_FILE_PATH
with your keystore file. WeChat needs the certificate fingerprint in MD5, remove :
in the fingerprint. It should be string in length 32.
Login WeChat Open platform, open the application detail page, update the development information iOS and Android sections.
In iOS
Fill in "Bundle ID" field with your app bundle id.
Fill in "Universal Links" with "IOS_WECHAT_UNIVERSAL_LINK" above.
In Android
Fill in application signature.
Fill in your package name
For android, we will need to define a custom url for Authgear SDK to trigger delegate function when user click "Login with WeChat" button. Here is the example, you should update it with your own scheme.
ANDROID_WECHAT_REDIRECT_URI_FOR_AUTHGEAR: com.myapp://host/open_wechat_app
Login Authgear portal, go to "Single-Sign On" page, then do the following:
Enable "Sign in with WeChat (Mobile/移动应用)"
Fill in "Client ID" with the WeChat "AppID".
Fill in "Client Secret" with the WeChat "AppSecret".
Fill in "原始 ID" with the WeChat "原始 ID".
Add "IOS_WECHAT_REDIRECT_URI_FOR_AUTHGEAR" and "ANDROID_WECHAT_REDIRECT_URI_FOR_AUTHGEAR" above into "WeChat redirect URIs"
Click save.
Update the code
In Android, Update application AndroidManifest.xml
.
Provide wechatRedirectURI
.
Provide sendWechatAuthRequest
Authgear lets you customize your users’ entire authentication experience
Brand and customize login experience for your users where you can customize domain, email, and localize to handle different languages.
Microsoft AD FS supports the prompt=login
parameter. You can include this parameter in your request when you want users to re-authenticate. See our in Authgear SDKs to learn more.
Create an Azure Active Directory (Azure AD) account
Setup a tenant by completing
Register an application by completing
Follow section to add a client secret. Remember to record the secret value when you add the client secret, as it will not be displayed again. This will be needed for configure OAuth client in Authgear.
Azure Active Directory automatically logs in to the same account without requiring a username and password. To prevent this behaviour, you can use the prompt=login
parameter to force Azure Active Directory to show the login page. See our in Authgear SDKs to learn more.
Sign in .
Create a B2C tenant by following .
Enable self-service sign-up for the tenant by following
Go back the main page of and search for "Azure AD B2C"
Create a app registration for Authgear by following .
Follow to create a sign-up and sign-in user flow.
Azure AD B2C automatically logs in to the same account without requiring a username and password. To prevent this behaviour, you can use the prompt=login
parameter to force Azure AD B2C to show the login page. See our in Authgear SDKs to learn more.
The prompt="login"
parameter which is defined in the can prompt Social/Enterprise Login Providers to always show their login screen. As a result, you can use the prompt="login"
parameter to allow users to switch accounts when their previous authentication session on the provider is still stored.
Register an account in .
Use your WeChat app to login in .
Register an account in .
Follow to setup WeChat SDK. For the coding part, we will further explain in the below steps.
WechatOpenSDK
is Objective-C library. If you are using swift. You will need to create bridging header. To setup bridge header, please check . Here is the example WechatOpenSDK-Bridging-Header.h
.
Here is the completed .
Follow to setup Wechat SDK. For the coding part, we will further explain in the below steps.
Here is the completed .
Follow and to setup WeChat SDK. For the coding part, we will further explain in the below steps.
Implement the NativeModules to use WeChat SDK to open WeChat app for authorization. Here is the completed .
Follow and to setup WeChat SDK. For the coding part, we will further explain in the below steps.
Implement the platform specific code to use WeChat SDK to open WeChat app for authorization. Here is the completed .
Authgear provides a wide range of prebuilt frontend for the authentication related features of your apps
The end-user can perform the following actions on the setting page:
Change their password.
Add or change their email, phone number or username.
Connect or disconnect to identity providers.
Manage the signed in sessions.
Enable or disable 2-step verification.
and many more.
Use the open method to open the built-in settings page
If you are working on a mobile apps, you can open the settings page using the SDK. When the end-user has signed in, the SDK provides a method to open the settings page in a webview.
In web-based application, you may want to add the "Back to my app" button to the settings page so the user can navigate back to your website after changing the settings.
Go to Portal > UI Settings
Provide the URL in Back to Your App Link and click Save
You can add a privacy policy and a terms of service link to the sign up page.
These two links can be easily added in the project Portal
Go to UI Settings in the Portal
Fill in the Privacy Policy Link and Terms of Service Link in the Link Settings section
Save the settings.
The values will be used as the href
of <a>
HTML tag so they must be valid URL. If both of the links are left empty, the whole paragraph on the signup page will be hidden.
You can also add these links by including two special translation keys in translation.json.
The keys are terms-of-service-link
and privacy-policy-link
. The values will be used as the href
of <a>
HTML tag so they must be valid URL.
For example,
If you wish to hide the whole paragraph, set BOTH to empty string.
Let end-user to contact customer support in case they need help in the login process.
In the case of losing access to the MFA authenticators, the end-user can recover their account by using the emergency Recovery Codes. However they may have lost the codes and need customer support.
You can add a customer support link in the Portal.
Go to UI Settings in the Portal
Fill in the Customer Support Link in the Link Settings section
Save the settings.
The value will be used as the href
of <a>
HTML tag. It can be a URL or a mailto:
link.
You can also modify the text shown to the end-users by including two special translation keys in translation.json
.
You can use your own translation or change the default text in the AuthUI. To do this, you'll edit translation.json.
Custom Text enables the customization of specific UI texts in AuthUI for different languages.
Follow these steps to change any text in AuthUI.
Go to Portal > Branding > Custom Text
Customize the look and feel of Authgear to match your branding
Authgear makes it easy for you to customize the built-in AuthUI to meet the specific branding needs of your application. You can customize UI elements such as the logo, text input fields, and buttons.
In this guide, you'll learn how to use all the customization options available.
To open the new Authgear Design page, log in to the Authgear Portal and navigate to Branding > Design.
The Design page is divided into 2 columns. The left column shows a preview of your customizations in real time. The right column is the menu with all the customization options for different UI elements (e.g. Name, Logo, Favicon).
Use this option to set the application name you want to display in AuthUI (Login and Register pages).
The Theme options allow you to switch between Light Mode, Dark Mode, or Auto (User Preference) on the Design page and for your project. If you select a theme and click the Save button, that theme will be applied to your project.
When the Auto based on user preference theme option is selected, AuthUI will choose a theme based on a specific user's settings.
The logo option allows you to replace the default Authgear logo in AuthUI with your own brand logo. You can add a PNG, JPG, or GIF image smaller than 100 KB.
Use this option to add a custom favicon that will show in browser tabs. The size of the image you upload must be a multiple of 32px square, and be a PNG, JPG, or GIF file.
The card option allows you to set the Alignment of the AuthUI card. By default, the AuthUI card is aligned to the Center. You change the alignment to either Left, Right, or Center.
Use this option to change the background color of AuthUI pages. You can either use a background color (CSS hexadecimal color code) or upload a PNG, JPEG, or GIF image smaller than 1 MB.
The button customization option lets you customize multiple properties of the buttons in AuthUI. The following are the properties you can customize:
Primary button: Use this field to set the fill color of the buttons.
Primary button label: Use this field to set the color of the text inside a button.
Border radius style: Set the type of border-radius you want here. Available options include square edges, curved edges, and full-rounded ends.
Border radius: The curved edges Border radius style allows further customization for the actual size of the border radius in pixels. Use this option to set the level of curved edges.
Link color: Use this option to set the text color for links in AuthUI. The value should be a hexadecimal color code.
Link decoration: You can use this option to add the underline
text-decoration to links that are displayed in AuthUI.
Privacy Policy: Use this option to add a link to your privacy policy page.
Terms of Service: Use this option to set a custom link for your terms of service
Customer Support: Use this option to add a link to your support page.
Note that when any of the link properties is unset AuthUI will fall back to the primary language's default settings.
The Input field section contains options for styling text input fields in AuthUI. The following are the various properties you can set:
Border radius style: Use this option to set the type of border-radius you want. The available options are square edges, curved edges, and full-rounded ends.
Border radius: You can use this option to further customize the level of curve of the curved edges Border radius style.
You can use this toggle to remove Authgear branding in the AuthUI for your project.
Attributes of the default AuthUI dark mode and light mode can be customized. For example, you can change the default color of the dark background in dark mode.
To customize an attribute, select the theme (light or dark mode) you wish to customize, then navigate to the attribute you wish to customize and modify it. Or select Auto based on user preference to see customization options for both themes at the same time.
The following are attributes you can customize for each theme:
Override translation by adding the key-value pair or modifying the value of an existing key in the JSON object in the text box. See default translation.json for a list of available keys and their default values.
The Language drop-down on the top right corner allows you to customize AuthUI text such as Organisation Name, and (Privacy Policy, Terms of Service, and Customer Support) for specific languages.
You can also use the Design page to select a theme (Dark mode or Light mode) to further customize it. Skip to the to learn more
Under the Links section, you'll find options to set the text color for links in AuthUI and also options for configuring , and that are linked on AuthUI.
Use this option to add a button under the to navigate the user to your website.
(fill color and label color)
Learn about what the Authentication Flow API is and how to use it to implement your own custom user interface (UI) for authentication.
Build your own custom UI for login, signup, and more powered by the Authentication Flow API.
By default, when you set up an Authgear project, it makes use of the regular AuthUI offered by Authgear. Although AuthUI offers many customization options such as the ability to change the theme and color or add your brand logo to authentication pages, you might have more needs. With the Authentication Flow API, you can build your own authentication UI from the ground up, and using your preferred programming language and tool.
The Authentication Flow API is an REST HTTP API that you can use to create and run an authentication flow. You can use this API to create your own custom UI for pages like login, signup, account recovery, 2FA, and more.
To use the API on its own you make an HTTP request to one of the valid endpoints as shown below:
Endpoint: {your-authgear-project-domain}/api/v1/authentication_flows
Request method: POST
Request header:
All requests to the API should include the above header.
Request body:
The following is a sample of the response you would get from the Authentication Flow API for the above request:
The above response means you've successfully started a new login flow using the API.
To continue and finish the authentication flow, you can send the value for state_token
from the above response in your next HTTP request to the api/v1/authentication_flows/states/input
endpoint like the example shown below:
Endpoint: {your-authgear-project-domain}/api/v1/authentication_flows/states/input
Request method: POST
To help you understand the structure of the Authentication Flow API HTTP(S) request, here is an example of an actual request in Postman:
Request body:
In this second request (or second step of the authentication flow), we use the state_token
from the response to the previous request in the request body to continue the authentication flow. The request body includes the input
field that passes the type of identification
the user will provide (for example, email
) and the login_id
which is the actual value for the user's identification.
The response to the above request should look like this:
You may send more requests just like this second request depending on the number of steps required for your specific authentication flow. For example, to complete the login authentication flow, send another request with the the authenticator (password) like this:
To use the Authentication Flow API to build your custom UI, you need to configure a Custom UI URI in the Authgear portal. This URI should point to your custom authentication page.
The following flowchart shows the steps in a simple Authentication Flow API implementation:
When you use the authentication flow API to power your custom UI, the authentication flow for your app will start with your app sending an authorization request to Authgear's authorization server as shown in step 1 in the figure above.
If you have Authentication Flow API enabled and a Custom UI URI set for your Authgear App, the authorization server will redirect your users to the custom UI as shown in step 2 above.
In your custom UI, implement the code that interacts with the Authentication Flow API (using HTTP requests) as demonstrated in step 3 of the above figure.
In an authentication flow with multiple steps, the custom UI and Authgear's authentication server may perform steps 3 and 4 in the above figure multiple times. In such cases, only the final response at the end of the authentication flow will include a finish_redirect_url.
You must redirect your user to the finish_redirect_url to complete the authentication flow.
To dive deeper into how to use the Authentication Flow API to power your custom UI, check out the following tutorials for your preferred programming languages and frameworks.
This guide shows how to setup custom login and signup pages using Authentication flow API.
You can create your own login and signup page from the ground up, using the Authentication flow API. In this guide, we'll implement Authentication Flow API using PHP.
Before we dive into the step-by-step guide, here are some key things you should know about working with the Authentication Flow API.
URL Query: When any of the Authgear SDKs redirects users to your Custom UI URL, Authgear adds some additional queries to the URL. These queries are required in order to get the finish_redirect_uri
.
Endpoint: You can find your Authgear project domain from your application configuration page (usually under the Endpoint section) in Authgear Portal. The full endpoint is this Authgear domain followed by a valid path for an operation. For example, https://my-project.authgear.cloud/api/v1/authentication_flows
to start an authentication flow. The two valid paths the API supports are /api/v1/authentication_flows
and /api/v1/authentication_flows/states/input
(which is for passing input to an existing authentication flow).
State Token: The Authentication Flow API supports authentication with multi-step UI just like the default authentication flow in Auth UI. State tokens can be used to make this type of type of authentication flow work. You can pass information about a previous step to the next step by using the state token. For example, using the state token in the result of step A as input in step B to continue using the state of the previous step.
Inputs: You can pass values to Authentication Flow API using the input
or batch_input
parameters in your HTTP request body. Use the batch_input
to send multiple values as in an array and input
when you are passing only 1 value.
Finish Redirect URI: A URL that you can use to redirect back to your app at the end of the authentication flow.
To follow along with the example in this post, you should have the following:
PHP installed on your local machine.
A code editor like VS Code, Sublime, Atom, or any editor you use for PHP development.
Now that you understand basic concepts about the Authentication API and what you need to follow along with our example, let's look at how to create our first custom login and signup page from scratch.
In this section, you'll learn how to configure your Authgear project for the Authentication Flow API.
Navigate to Application > Add Application in Authgear Portal (or select an existing application then update the configuration).
Enter a name for your application and set the Application Type as OIDC Client Application. then click on the Save button.
Note: You can select any Application Type on the Portal depending on the nature of your client application that will be interacting with Authgear and your Custom UI.
In this step, you'll add redirect URIs to your application. An Authorized Redirect URI should be a valid page on your application that you want Authgear to redirect users to at the end of the authentication flow.
To add a new URI, scroll down to the URIs section on the configuration page for the application you created in the previous step. Next, click on the Add URI button then enter a valid URL for your application. For this example, enter http://localhost:8081/
as a redirect URI.
Once you're done, save the changes to continue.
The value for the Custom UI URI should be a link (absolute URL) to your custom login page. Authgear will redirect users to this page when they start an authentication request. Also, during redirect, Authgear will automatically include the URL query we mentioned earlier.
Now, still within the configuration page for your application, scroll down to the Custom UI section and add a link to your custom login page.
If you're testing your custom UI on a browser on the same device that you'll be using to serve the PHP code, you can enter your localhost
URL in Custom UI URI. For example, you can use the following URL if you will run the PHP code on your local machine using port 8081 :
With that, we're done with the required configuration on the Authgear Portal. In the next part, we'll design some custom UI and implement the Authentication Flow API.
For our example app in this tutorial, users will be using their email and password to log in. Hence, you are required to enable this option in the Authgear Portal.
To do that, enable the "Email + Password" option under Authentication > Login Methods.
Also, disable 2FA (if enabled) so that the authentication flow does not include an extra step which our demo app will not cover. You can disable 2FA Requirements in Authentication > 2FA in the Authgear Portal.
Now that your Authgear project is set to use the Authentication Flow API, let's walk through the steps for creating a custom login and signup page. Our example app for this part of the guide uses PHP.
The application you'll build in this part is the same application your Custom UI URI should point to.
Step 1: Set up Authgear PHP Example App
Create a new folder on your computer for your PHP project using the following command or a file explore:
Change your current directory to the new folder using by running the following command:
For this example, we'll be using the oauth2-client package to interact with Authgear. Install the package using the following command:
Create the following files in and add the corresponding code to the files:
config.php:
Add the correct values for $clientID
, $clientSecret
, and $redirectUri
from your Authgear application configuration page. The value for $appUrl
should be your application endpoint.
index.php:
The above page will serve as a landing page for our example application. After a user clicks on the login link, they'll be redirected to your custom login page.
startLogin.php:
The code in startLogin.php initiates a regular Authgear authentication flow by redirecting the user to the authorization URL. In the case of our example, this authorization URL will point to our custom login page instead.
Still, in your PHP project folder, create a new login.php file and add the following code to it:
The above code creates a basic login page with email and password fields and a submit button.
On the first line of the code, the value for the URL Query that Authgear adds to your custom UI URI is read and stored in the $url_params
variable. This value is required to finish the authentication flow.
Also in the above code, the form action points to a form.php with $url_params
appended to the path. It is this form.php file that will process the form data and complete the login flow. We'll implement the file in a later step.
The following screenshot shows the output of the custom login page on a browser:
This is the part where you start to make interactions with the actual Authentication Flow API.
In this first interaction, we'll be making an HTTP request to the API endpoint to log a user into our application.
In the request, we'll send the email and password the user enters in the login.php page to the API endpoint to complete the authentication flow in a single step. What this means is that we'll initiate and finish the login flow using a single HTTP request. Unlike what we'll do in later steps for signup and OTP flows.
Now create a new form.php file and the following code to it:
Here are the key things the PHP code in form.php does at this point:
First, it reads the URL query from the form action and appends it to the API endpoint.
Then it makes a POST HTTP request to the endpoint with both Content-Type
and Accept
header values set to application/json
. These header values are required for sending requests to the endpoint.
Next, the user input (email and password) from the form is sent in the body of the HTTP request. Also in the request body is type
and name
parameters that specify the type of authentication flow (login) and the name of the flow (default) respectively.
And finally, the value for finish_redirect_uri
is read from the response of the HTTP request. This value is then used to redirect the user to the "finish redirect URI" to complete the login flow.
The HTTP response from the above request will look like this:
To your application, start your PHP server and try visiting the index.php from a web browser. If you have PHP installed on your local machine and the environment path set, you can start a PHP server for your project by running:
Now test the login flow by clicking on the login link on the landing page. You should be redirected to the custom login instead of the default AuthUI Authgear provides.
Enter a valid email and password combination and click the Login button like a normal user would test your implementation. The user should be redirected back to the application at the end of the authentication flow.
For this signup flow example, we'll be making two requests to the Authentication Flow API. In this step, we'll implement the first request which will only initialize the signup flow.
Create a new signup.php file inside your project folder and add the following code to it:
As you can see from the code snippet above, for this authentication flow, the type is "signup".
The initSignUp()
method handles the step that starts the authentication flow for the specified type and returns a state_token
that you can use to continue the flow.
In this step, we'll create a sign-up page. The login page already contains a link that points to the sign-up page and also includes the URL Query.
To create the UI for the signup page, add the following code to the signup.php file just below the closing "?>"
PHP embedded closing tag:
The above code implements a signup form that includes fields for users to enter their email and password and a submit button. The value for the <input type="hidden">
is the state_token
returned from the previous. You need this state_token
to proceed with the flow.
Open form.php and add a new conditional block for when action=="signup"
using the following code:
The above code sends the state_token
from the previous step as part of the request body.
It also sends the email and password the user entered in the form.
On successful response, the code will redirect the user to the finish_redirect_url
.
Test your implementation again using your frontend application and you should be able to register a new account using the custom UI.
Beyond login and sign-up, there's more you can do with the Authentication Flow API. However, the focus of this post has been to provide a guide for getting started with your first implementation of Authentication Flow API.
To learn more about supported flows, endpoints, their inputs, and responses, check out the official API Reference for Authentication Flow API.
For more details about the Authentication Flow API endpoints, inputs, response, and more visit the .
installed on your computer.
An Authgear account. You can create one for free .
Enable Custom UI for your Authgear Project. to enable custom UI.
Alternatively, can use to get a public URL for your PHP application that's running locally. Then, enter the public URL from CloudFlare as your Custom UI URI.
We'll use the package to make HTTP requests to the Authentication Flow API. Hence, run the following command in the root folder of your project to install it:
Integrate Authgear with your product
Cut down on implementation time by utilizing integrations that have been developed by Authgear. The Authgear platform is designed to be flexible, allowing you to meet your specific needs by customizing identity processes with your own code and easily integrating with other external applications and tools.
This set of how-to guides provides you with detailed instructions, code snippets, and configuration examples for each type of integration.
This guide shows how to use Custom Login/Signup pages UI in Native Apps
Implementing custom login and signup screens in any native application (Flutter, React Native, Kotlin, or iOS) doesn't require much change to the code for your existing native apps that use Authgear.
At the moment, we don't support direct interaction between your native code and the Authentication Flow API that powers custom UIs. That means you'll need to use the platform-specific SDKs we already provide and call the authenticate method to start the authentication flow.
In this guide, we'll teach you how to implement custom authentication UIs in a Flutter app using the Flutter SDK and Authentication Flow API.
The main factor that enables custom UI in your Authgear application is specifying a custom UI URL in Authgear. Once this value is set, calling the authenticate method in any of the native SDKs will open the custom login/signup UI in a Web View instead of the default Auth UI.
If you do not already have an Authgear application, login to Authgear Portal and navigate to Application > Add Application to create an application.
Enter your application name and select Native App as Application Type then click the Save button to continue.
In this step, you'll add a URI that Authgear will use to return your application to the front of the screen when authentication is complete.
For our example Flutter app, this URI will start with the package name for our app followed by ://host/path
.
To set the Redirect URI, scroll down to the Authorized Redirect URI under the URIs section of your application configuration page. Enter the correct URI for your application then click Save.
Note: You can find the package name for your Flutter app in android/app/build.gradle
under android > namespace
.
Setting a value for Custom UI URI in Authgear Portal will redirect users of your application to your custom authentication UI instead of the default Auth UI. Hence, this is the most important step in adding custom login and signup UIs to your native application.
To set the Custom UI URI, scroll down to the Custom UI section on your application configuration page in the Authgear Portal. Then, add the URL to your custom login/signup page in the Custom UI URI text field.
If you have an existing Flutter app that implements the default AuthUI, it may not require any change to make use of the Custom UI URI you've set in the previous step.
But if you're creating a new application, follow these steps:
Run the following command to create a new Flutter application:
Now install the Authgear Flutter SDK by running the following command from your project directory:
You can also find similar guides for other native platforms below:
To test your application, run the following command:
Tap on the Authenticate button when your app runs on a physical device or emulator. You should see the custom UI instead of the default Auth UI.
A very important to remember from the above guide is that when using custom authentication UI with a native application you can set up your app as you usually would with the default Auth UI. However, the main difference is that you should provide a link to your custom UI in the Authgear portal.
Use the Account Management API to link OAuth provider.
The Management API provides a way to perform actions that you usually will do from the default /settings
page using your own custom UI.
The account management API for OAuth providers allows developers to write their own custom code for linking a social or enterprise (OAuth) provider to user accounts on their Authgear provider. Developers can use this API to create a custom UI that their users can use to link one or more social login providers to their accounts.
The account management API for OAuth Provider has 2 endpoints that your code must make HTTP(s) POST requests to. A detailed description of the endpoints is given below:
Use this endpoint to initiate the flow of linking an OAuth provider to an account. The endpoint requires a valid access token for the current user in the Bearer Authorization header.
Request Method:
POST
Request Header:
Request Body:
identification
: Required. It must be the value oauth
.
alias
: Required. The alias of the OAuth provider you want the current account to associate with.
redirect_uri
: Required. You have to specify your own redirect URI to your app or your website to receive the OAuth callback.
exclude_state_in_authorization_url
: Optional. The default is false
. When it is false
, the authorization_url
has a state
parameter included, the token is bound to this state
parameter. When it is true
, the authorization_url
has no state
parameter included, the token is NOT bound to state
. If you wish to use your own state, you must set this field to true
.
Response:
token
: You store this token. You need to supply it after the end-user returns to your app.
authorization_url
: You MUST redirect the end-user to this URL to continue the authorization code flow. If exclude_state_in_authorization_url
is false, it has the state
parameter included.
Call this endpoint from your redirect URI to finish the process of linking an OAuth provider.
Request Method:
POST
Request Header:
Request Body:
query
: The query of the redirect URI.
Response:
In this example, we'll link Google as the OAuth provider.
The account manage API requires a user's valid access token to work. Hence, you must first authenticate the user using another identity first.
Set up your application to allow users to log in using Authgear and obtain an access token.
Now that your application can obtain a valid access token for a user, you'll make an HTTP(s) request to the /api/v1/account/identification
endpoint to initiate the OAuth provider linking flow.
Use the following code to send the HTTP(s) request:
In the code above, the body of the HTTP(S) request includes the identification
type which is oauth
because we're trying to add a new OAuth Provider as an identity for a user's account. The value of alias
is google
because the OAuth provider to be added is Google.
The link in redirect_uri
is a page on the example application that will handle the callback from the OAuth provider. We will implement this page in the next step.
The response from the /api/v1/account/identification
endpoint should look like this:
The response for the HTTP(s) request in Step 2 includes an authorization_url field. That field contains the OAuth provider's authorization URL. Your application can redirect users to authorization_url
for them to grant authorization on the OAuth provider's website.
Replace the line with // TODO
in Step 2 with the following code to use the value of authorization_url
in a hyperlink that users can click:
The final step for linking an OAuth provider is to implement the callback URL that the OAuth provider will be redirecting users back to after authorization. This is where your application will be making an HTTP(S) request to the second endpoint (/api/v1/account/identification/oauth
).
For this example, we'll create a "/linkcallback
" route to handle the redirect using the following code:
The above code sends the token
(returned in the response to the previous HTTP(S) request) and the query
parameters added to the redirect URI by the OAuth provider in an HTTP(S) request to the finish endpoint. Both parameters are required.
The following will be the response of the endpoint when the OAuth provider is linked successfully:
This post provides a simple guide for implementing a custom email + password login and signup pages using Authentication Flow API and Express.
With the Authentication Flow API, you can replace the default Auth UI provided by Authgear with your own custom UI built from the ground up.
In this post, we'll walk you through an example of building your own custom login and signup pages using Express and the Authentication Flow API.
Before we continue, it's important for you to familiarize yourself with the following concepts about the Authentication Flow API:
URL Query: This is an additional set of URL query parameters that Authgear adds to your Custom UI URI during the initialization of the authentication flow. The initial request to the Authentication Flow API must include this URL query in order to return get value for finish_redirect_uri
at the end of the flow.
Endpoint: Your Authgear project's domain is visible on your application configuration page in Authgear Portal, under the Endpoint section. Your full endpoint is your Authgear domain followed by a valid path for an operation (such as starting a new authentication flow, or sending input to an existing flow. For example, https://my-project.authgear.cloud/api/v1/authentication_flows
to start an authentication flow and https://my-project.authgear.cloud/api/v1/authentication_flows/states/input
to send input to an existing flow.
State Token: The Authentication Flow API supports authentication with multi-step UI just like the default authentication flow in Auth UI. State tokens can be used to make this type of type of authentication flow work. You can pass information about a previous step to the next step by using the state token. For example, using the state token in the result of step A as input in step B to continue using the state of the previous step.
Inputs: You can pass values to Authentication Flow API using the input
or batch_input
parameters in your HTTP request body. Use the batch_input
to send multiple values as in an array and input
when you are passing only 1 value.
Finish Redirect URI: This is a URL that you can use to redirect back to your app at the end of the authentication flow.
Note: In order to follow this tutorial and implement the example app, you need to enable a login method that supports "Email and Password" under Authentication > Login Methods in Authgear Portal. Also, disable 2FA Requirements from Authentication > 2FA in Authgear Portal.
In order to follow along with the example in this post, you should have the following:
Node.js installed on your local machine.
A code editor such as VS Code, Sublime, Atom, etc.
Be familiar with CLI tools like npm.
Next, set up your Authgear project to use custom authentication UI by following the steps below.
An important part of getting your application ready to use custom authentication UI is to configure your Authgear project in Portal. In this section, we'll cover the configuration required for the example app.
Login to the Authgear Portal and navigate to the Application section. Select an existing application and modify it or click on the Add Application button to create a new application.
Configure your application using the following details:
Application name: My app <or any name of your choice>
Application type: OIDC Client Application
Once you're done, click on the Save button to continue.
Note: You can select any Application Type on the Portal depending on the nature of your client application that will be interacting with Authgear and your Custom UI.
To follow this example, select OIDC Client Application as your Application type.
An Authorized Redirect URI is a page on your application that you want Authgear to redirect users to at the end of an authentication flow.
To add an Authorized Redirect URI, scroll to the URIs section on your Authgear application configuration page. Click on the Add URI button then enter a valid URI for your application.
For our example, the redirect URI will be:
Once you're done, click on the Save button to keep your changes.
To use your custom authentication UI with Authgear, you need to specify the URI for your custom UI in the Authgear portal using the custom UI URI field. This will cause your application to show the custom UI instead of the default Auth UI during login/sign. The custom UI URI is basically a link to your custom login page.
Since we'll be testing the example app on a browser that runs on the same computer as the Express server, you can use the following value for the Custom UI URI:
To set the custom UI URI, scroll to the Custom UI section on your application configuration page and paste the URL (e.g the unique public URL from CloudFlare Tunnel) in the Custom UI URI text box.
Note: For our example app, you must include the /login
path in the URL so that the user is redirected straight to our login route.
That concludes all the configuration requirements in the Authgear portal for this example.
For our example app in this tutorial, users will be using their email and password to log in. Hence, you are required to enable this option in the Authgear Portal.
To do that, enable the "Email + Password" option under Authentication > Login Methods.
Also, disable 2FA (if enabled) so that the authentication flow does not include an extra step which our demo app will not cover. You can disable 2FA Requirements in Authentication > 2FA in the Authgear Portal.
In this part of the guide, we'll implement custom login and signup pages using Express and the Authentication Flow API.
The application you'll build in this part is the same application your Custom UI URI should point to.
Create a basic Express application for your Authgear project.
To do that, first run the following commands on your computer to create a new project folder and install all the necessary dependencies:
Create project folder/directory:
Change your working directory to the new folder by running the following command:
Install Express:
For our example application, we'll be using the Axios node package to make HTTP requests. Run the following command to install Axios in your project:
Install dotenv. We'll use this package to enable the use of .env file to store project configuration:
After installing the above dependencies, create a new app.js file in the project directory you created earlier. Add the following code to the file:
Create a .env
file then add the following code to it:
Add the correct values from your Authgear application configuration page in the .env file.
At the end of this step, you should have an Express application that can connect to Authgear. However, we are yet to implement the custom login/signup page. In the next steps, we'll implement both pages.
Add the following code to your app.js file just below the app.get('/startLogin',...)
route:
The above code sets up a basic email + password login page using Express.
The rawURLQuery()
function extracts the URL query we mentioned earlier from the URL of the login page. The code includes the query as the value for an <input type="hidden">
so that we can include the value in the request we'll make to the Authentication Flow API later.
The following screenshot shows the output of the login page in a browser:
Now your application needs to make an HTTP request to the Authentication Flow API with the user inputs to authenticate them.
First, we'll create a userLogin()
function that sends the HTTP request. To do that, add the following code to your app.js just above the declaration of the rawURLQuery()
function:
Here are a few key things to note about the above code:
The code initiates an Authentication Flow API request of type login
and finishes the entire login flow in a single step (one HTTP request).
As we mentioned earlier, the URL query from Authgear is added to the API endpoint for the initial request.
The user inputs (email and password) are sent in the request body using the batch_input
parameter.
The structure of the HTTP response will look like this:
Now add the following code after the app.get('/login',...)
route to create a new route that handles the action of submitting the login form:
Once the login flow is complete and a finish_redirect_uri
is returned, we redirect the user to this URL for Authgear to finish the authentication process and redirect the user back to your application.
To test your progress so far, start your Express app by running the following command:
Now open your app in a web browser by visiting localhost:3000
. Once the page loads, click on the Login link. You should be redirected to the custom login page instead of the default Auth UI by Authgear.
Enter a valid email and password and click the Submit button. You should be redirected back to your application on successful login.
This step includes an example of using the Authentication Flow API for user signup. Unlike in the previous login flow example, this time we'll use the API to perform a signup flow using 2 steps(also 2 HTTP requests).
The first step is to initialize the signup flow. To do that, create an initSignUp()
function just after the userLogin()
function in app.js using the following code:
Here is a breakdown of what the above code does:
First, in the code, the value for the URL query is added to the Authentication Flow API endpoint so as to meet the requirement for getting the finish_redirect_uri
at the end of the flow.
The type of authentication flow is also specified as signup
in the input
variable that's passed in the HTTP request body.
The function returns the value of state_token
from the HTTP request response. This value is required in the next step (request) to continue the signup flow.
To create the actual page with a signup, add the following code just after the app.post('/login',...)
route in app.js:
The above code contains the HTML code for rendering a simple email and password signup page. It also calls the initSignUp()
to start the authorization flow and add the state token in an <input type="hidden">
.
To complete the signup flow, first create a submitSignUpData()
function by adding the following code just after the initSignUp()
function in app.js:
The above code implements the second step of the signup flow. It takes the state token from the first step and sends it in the second HTTP request so that the flow can continue.
Next, add the following code just after the app.get('/signup',...)
route:
The above code calls the submitSignUpData()
function which initiates the second step of the signup flow and submits the user inputs. At the end, the user is redirected to the finish_redirect_uri
again to complete the authentication process.
Just like we've implemented custom UI for email and password authentication in this example, you can design custom UIs for other authentication flows that Authgear supports. For example, OTP and TOTP.
To learn more about all the endpoints the Authentication Flow API supports, and their inputs and outputs, you should check out the API reference page for Authentication Flow API.
Resources about setting up your own custom User Interface for Login, Signup, Account recovery and more.
You can build your own custom UI powered by the new Authentication Flow API. Here are some resources for getting started:
Guide on how to implement your own account recovery UI powered by the Authentication Flow API
In this guide, you'll learn how to implement your own custom account recovery page that is powered by the Authentication Flow API.
Before we continue, here's an overview of our objectives for this post:
At the end of this guide we'll build a custom account recovery UI using Express.js that will do the following:
Allow users to enter the phone number associated with their account as login ID.
Send an account recovery code to the phone number.
Provide a UI for the user to enter and verify the recovery code.
Finally, a UI for the user to set a new password for their account.
To follow this guide, you should have the following:
A code editor like VS Code, Sublime, Atom, or any editor you already use for JavaScript development.
Be comfortable working with CLI tools like NPM.
Using custom UI in your Authgear application requires setting the value for Custom UI URI to where your custom UI is hosted.
To set this value, log in to the Authgear Portal and navigate to Applications then select your application. Next, in your application's configuration page, scroll down to the Custom UI section and enter the URL for your custom UI.
For the example in this post, we'll be using CloudFlare Tunnel to expose the custom UI we'll be building so that we can have a public URL to enter in the Custom UI URI field in our Authgear application configuration.
If you're new to the Authentication Flow API, check this getting started post [HERE(LINK)] to learn more about configuring your project for the API.
Now let's create the Express project that we'll be using to implement the account recovery Custom UI.
To create a new Express project create a new folder with the name "custom-recovery" on your computer using a file explorer or using the following command in PowerShell or Terminal:
This folder will serve as your Express project folder.
Next, install the Express package by running the following command:
Finally, create a new JavaScript file with the name "app.js" in the new folder you created earlier. This is the file where we'll implement our application logic.
Add the following code to the new app.js file:
At this point, test your work so far by running the following command from the root of your Express project folder:
Here we'll create the UI for the first page of the recovery flow. This will be a basic webpage with an input field for the user to enter their phone (login id) and a submit button.
Open app.js in your code editor and update the content of the app.get('/recovery')
route to the following:
The above code refers to a rawURLQuery()
and initRecovery()
functions that we've not implemented yet. We'll implement the first function in this step and the second in the next step.
The form we created using the above code looks like this:
Look for the following line of code in your app.js file:
Then add the following code on a new line just below it:
The above code implements the rawURLQuery()
function we mentioned earlier. This function is a helper that helps us extract URL Query from the current request. We need a special URL Query from Authgear in order to get the finish redirect URI at the end of our recovery flow. You can learn more about the URL Query [HERE(LINK)].
In this step, we'll initialize a new authentication flow of type account_recovery
.
For this step and other steps that follow, we'll be making HTTP request to the Authentication Flow API using the Axios node package. Install Axios by running the following command:
Import Axios to your project by adding the following code to the top of app,js:
Next, again, look for the following line in your app.js file:
Add the following code on a new line just below it:
The above code implements the initRecovery()
function. The function sends the HTTP request that initializes a new account recovery flow and returns a state_token
. We'll use this state_token to continue to the next step of the flow. Hence we are passing the value for state_token to the next step using <input type="hidden">
.
The response to the HTTP request looks like this:
In this step, we'll implement the code that will send the recovery code to the user's phone after they enter their phone number on the form and click submit.
Add a new beginRecovery()
function to app.js (just below the initRecovery()
function) using the following code:
The above code sends a request with the user's phone number (login_id
) and the position of the channel (index
) to which the code should be sent.
To enable Express to process form data correctly, add the following code on a new line to the top of app.js (just below const app = express();
):
Now create a POST route that will call the beginRecovery()
function by adding the following code just below the app.get('/recovery')
route:
The above code will redirect the user to a verifyRecovery
page if a recovery code was sent successfully. We'll implement this page in the next step.
The above code uses express-session, so install the package by running the following command:
Then import express-session to your app.js by adding this code to the top of the file:
Finally, enable express-session as a middle-ware by adding for following code on a new line at the top of app.js (just below const app = express();
):
Now let us implement the page where the user can enter the recovery code they got for verification.
Add a new route to app.js to create the UI for the verification page:
Here is what the verify recovery code page looks like:
Next, add a new verifyRecoveryCode()
function to app.js using the following code:
The above code will send the request to the Authentication Flow API with the account recovery code a user enters.
To finish up the recovery code verification process, add a new route that will handle the form submission using the following code:
The code sample above will redirect the user to a setPassword
page after successful verification of the recovery code they entered. In the next step, we'll implement the page where the user can set a new password.
The final step of the account recovery process is for the user to set a new password for their account. In this step, we'll implement the UI for that.
First, add a new route to your app.js to create the UI using the following code:
The above code will implement a page that looks like this:
Add a new recoverySetPassword()
function to app.js using the following code:
Next, create the route that will handle the submission of the set new password form using the following:
If the new password is set successfully, the above code will return control to Authgear to complete the rest of the authentication flow and return to your application. This is done by redirecting the client to the finish_redirect_uri
.
And there you have it, you've successfully implemented your own custom password recovery UI powered by the Authentication Flow API.
For our example application, we used the phone number as login_id
and the channel for receiving the recovery code. In a real app, you may use another channel such as email instead or even support both depending on what is available for the user.
Learn how to track a user that signs up from a particular source or campaign.
In this guide, you'll learn how to track users from a particular source before and after they sign up. For example, knowing how many people sign up for your application through a signup link that you have included in a blog post or an email campaign.
To follow this guide, you need to have the following:
A free Authgear account.
An application in the Authgear Portal and note down the configuration of the application.
A client application that is written in your preferred language or framework.
For this guide, we'll build a demo Express application that has the following features:
Read a source
URL parameter defined by you (the developer).
Send the value of the source
parameter to the Authgear authorization server using the OAuth 2.0 state
parameter.
Read the value of state
returned after user authorization (sign up) and log the value in a database or analytics system like Mixpanel.
The authorization server (Authgear) will include the same state parameter value when redirecting the user-agent back to the client application. As a result, the client application can retrieve the value of state
returned to verify that it is the origin of the authorization request.
We will use the above behavior of the authorization process to track a user before and after they sign up.
The following steps show the steps for building a simple application that is capable of tracking users before and after they sign up.
1. Express:
2. Axios:
Next, inside the project directory, create a new app.js file then add the following code to the file:
You can get the correct configuration values (CLIENT_ID, CLIENT_SECRET, REDIRECT_URL, and AUTHGEAR_ENDPOINT) from the Applications section of the Authgear Portal.
In this step, we'll implement a /login
route in the demo application. This route will support a source
query parameter, for example, /login?source=002
.
Add the following code to the end of app.js to implement the /login
route:
The above code will check if the source parameter is included in the HTTP request to the /login
route. If there is a source
parameter, the value of the source will be added to the authorization URL's state parameter.
The following is an example of a login URL that includes the source parameter:
As described earlier, Authgear will return whatever value you put in the state
parameter of the authorization URL. In the last step, we will read the value of the source
parameter from the /login
route and pass it to the state
parameter. In this step, we'll read the state
parameter that Authgear returns in the redirect URI for the initial value we passed (source
).
To do this, we'll add a /
route to resolve our redirect URI. Add the following code to the end of app.js to implement the route:
The sourceFromState
constant holds the value for the state parameter in the redirect URI. You can save this value to a database to track that the user has successfully signed up using the link with the source value in your original campaign link. You may also send this link to an analytic tool like Mixpanel to track the user and source.
To run the demo app, run the following command in the terminal:
Then, open http://localhost:3000/login?source=002
on a browser. You can change 002 to any random string that you wish to use for tracking a source or campaign. Also, be sure to add http://localhost:3000
as a redirect URL for your application in the Authgear Portal.
Learn how to add custom attributes to a JWT Access Token using Authgear
JWTs (JSON Web Tokens) are a common method for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. With Authgear, it is straightforward to add custom fields to your JWT access tokens.
Make sure the option Issue JWT as access token is enabled in your Application settings in the Portal.
Navigate to the Applications tab and choose the existing App.
On the App Configuration dashboard, locate the "Access token" section.
Make the toggle Issue JWT as access token switch on.
Navigate to your Authgear Dashboard's Advanced->Hooks section.
Add a new Blocking Event.
Choose the Block Hook Type as the TypeScript and set the Event option to JWT access token pre-create. You will write a new Typescript function from scratch.
Click on Edit Script under the Config option.
Copy and paste the following into the editor:
Click on Finish Editing.
Back to the Hooks page from the navigation bar and click on the Save button at the top of the page.
There are two ways to test it:
If you created the application type OIDC Client Application, you need to follow the steps below. Expand it to see instructions.
This URL is a publicly accessible link on the web that hosts the code that implements your custom UI and does the actual interaction with the Authentication Flow API. Check out our examples for implementing custom login and signup UI pages using and to learn more.
Make sure you have your local machine set up for Flutter development before you run the above command. See the official guide for setting up Flutter . Once you're down, open the new project folder in your preferred code editor (VS Code or Android Studio).
To implement Authgear in your Flutter app use the SDK, please follow these instructions on the .
To learn more about using Authgear in your Flutter app, check out this page about the .
token
: The token you received in the response of the endpoint.
See our section for a detailed guide for your preferred programming language or framework.
An Authgear account. You can create one for free .
Enable Custom UI for your Authgear Project. to enable custom UI.
Alternatively, you can get a public URL for our local Express app with CloudFlare Tunnel. See more instructions on how to set up CloudFlare tunnel on your local machine .
You can find the complete code for the example application in this post in our .
installed on your local machine.
Last but not least, an Authgear account. Sign up for free .
Then go to your preferred web browser and visit .
The includes an optional state
parameter. The value of the state
parameter can be any random string or number defined by a client application (e.g a web or mobile that uses Authgear for user authentication) before the client makes an authorization request. In simple terms, the state
parameter is added to the authorization URL as a URL query.
First, create a new project directory and open it. The demo application for this guide is a simple application that use Axios to make HTTP requests. Hence, install both packages using the following commands:
This how-to guide will walk you through the process of adding custom fields such as attributes to a JWT access token payload using Authgear and Javascript .
Here's an example of the and an explanation of their values.
You can also to on the Authegear Portal.
An Authgear account: You need an Authgear account to follow this guide. If you don't have one, you can on the Authgear website.
A Registered App: You need a (client) in Authgear.
Log into your .
With the use of Hooks, Authgear provides flexibility for adding custom logic to your authentication pipeline. You can create a Hook which is triggered any of these about to occur. For example, oidc.jwt.pre_create
the event happens just before issuing the JWT access token and it can be used to put extra information into the token.
In the above code, we are importing the necessary modules such as HookResponse
and EventOIDCJWTPreCreate
which are types from the Authgear hook . We modify the JWT payload by adding (e.payload.user.standard_attributes
) and (e.payload.user.custom_attributes
) of the user.
You can do this by on your application server side using a JWT decoder and inspecting the payload.
Finally, we can debug the access token using the to see if the custom field and value we added previously are there inside the JWT payload.
Monitor your Authgear implementation
You can monitor the Authgear app, and see and retrieve log event data.
The Admin API & Portal tab in the Audit Log page allows you to analyze and monitor changes and activities that occur on Admin API and the Authgear Portal of your project.
The data under this tab can be handy for securing your Authgear project. For example, whenever an admin on your project downloads the Admin API key, the event is registered under the Admin API & Portal tab.
Activity logs for Admin API and Portal are part of the data the auditLogs query returns.
For example, the following query will return any recent events from Admin API and Portal that have been logged:
Note: The above request will also include events triggered by users.
The following is a list of the activity types that are logged:
PROJECT_APP_SECRET_VIEWED
An admin downloaded the Admin API key
PROJECT_APP_UPDATED
Project configurations updated
PROJECT_BILLING_CHECKOUT_CREATED
An admin attempted to subscribe to one of the billing plans
PROJECT_BILLING_SUBSCRIPTION_CANCELLED
Billing subscription was canceled
PROJECT_BILLING_SUBSCRIPTION_STATUS_UPDATED
Account billing status is updated
PROJECT_BILLING_SUBSCRIPTION_UPDATED
Billing details updated
PROJECT_COLLABORATOR_DELETED
An admin is removed
PROJECT_COLLABORATOR_INVITATION_ACCEPTED
A user accepted an invitation to become an admin
PROJECT_COLLABORATOR_INVITATION_CREATED
Invitation to add new admin sent
PROJECT_COLLABORATOR_INVITATION_DELETED
A previously sent admin invitation was canceled
PROJECT_DOMAIN_CREATED
A new custom domain name added
PROJECT_DOMAIN_DELETED
A custom domain name was removed
PROJECT_DOMAIN_VERIFIED
A domain name was successfully verified
ADMIN_API_MUTATION_SET_DISABLED_STATUS_EXECUTED
Admin disabled/enabled a user account
ADMIN_API_MUTATION_CREATE_SESSION_EXECUTED
A new session is created
ADMIN_API_MUTATION_ANONYMIZE_USER_EXECUTED
An admin initiated the process to annonymize a normal user. This command will delete all user data like email, full name and phone number
ADMIN_API_MUTATION_CREATE_IDENTITY_EXECUTED
New Identity was created by an admin
ADMIN_API_MUTATION_CREATE_USER_EXECUTED
An admin created a new user
ADMIN_API_MUTATION_DELETE_AUTHENTICATOR_EXECUTED
An authenticator was removed
ADMIN_API_MUTATION_DELETE_AUTHORIZATION_EXECUTED
An authorization was removed
ADMIN_API_MUTATION_DELETE_IDENTITY_EXECUTED
Identity deleted
ADMIN_API_MUTATION_DELETE_USER_EXECUTED
An admin deleted a user
ADMIN_API_MUTATION_GENERATE_OOB_OTP_CODE_EXECUTED
New OTP code generated
ADMIN_API_MUTATION_RESET_PASSWORD_EXECUTED
Password was reset by an admin
ADMIN_API_MUTATION_REVOKE_ALL_SESSIONS_EXECUTED
All sessions revoked
ADMIN_API_MUTATION_REVOKE_SESSION_EXECUTED
A users session is revoked
ADMIN_API_MUTATION_SCHEDULE_ACCOUNT_ANONYMIZATION_EXECUTED
An admin scheduled the anonymization of a user account
ADMIN_API_MUTATION_SCHEDULE_ACCOUNT_DELETION_EXECUTED
An admin scheduled the deletion of a user
ADMIN_API_MUTATION_SEND_RESET_PASSWORD_MESSAGE_EXECUTED
Password reset message was sent
ADMIN_API_MUTATION_SET_VERIFIED_STATUS_EXECUTED
Verified status for a user is updated
ADMIN_API_MUTATION_UNSCHEDULE_ACCOUNT_ANONYMIZATION_EXECUTED
A previously scheduled user anonymization request was canceled
ADMIN_API_MUTATION_UNSCHEDULE_ACCOUNT_DELETION_EXECUTED
A previously scheduled user deletion request was canceled
ADMIN_API_MUTATION_UPDATE_IDENTITY_EXECUTED
Identity updated by admin
ADMIN_API_MUTATION_UPDATE_USER_EXECUTED
An admin updated details like a user's name, gender and more
Optimize for email deliverability by using your own SMTP server to send Authgear Emails (such as forgot password, verifications) in your own domains.
To send Authgear emails to end-users with your own domain, e.g. support@myapp.com
. You will need to configure the external SMTP provider.
Authgear currently supports SendGrid and other custom SMTP Providers.
The sender address can be configured by changing the value of theemail.default.sender
key in the localization JSON. Go to Portal > Branding > Custom Text and add/change the value of email.default.sender
to your own email address, for example no-replay@myapp.com
, and Save the settings. The value can be set separately for each locale.
Before adding the email service provider to Authgear, make sure the sender domain is verified and authenticated on the email service. For example, your domain myapp.com
should be configured in your SendGrid account so Authgear can use the account to send emails with no-reply@myapp.com
.
Follow the instructions from the email service provider for setting up your domain:
The external SMTP provider can be set up in Portal > Advanced > Custom Email Provider. Enable the Use my own provider toggle to see the fields.
Log in to your SendGrid account
Create API Key in Settings > API Keys
Set the API Key Name for your reference the choose Restricted Access under API Key Permissions
Under Access Details, expand Mail Send and give Full Access to the Mail Send permission
Click Create & View. Copy the API key created and save it somewhere safe
In Authgear Portal, navigate to Custom Email Provider
Enable Use my own provider.
Choose SendGrid and paste the API key you copied, and Save
You can send a test email to check the configuration
Other SMTP providers can be set manually by providing the Host, Port, Username, and Password. They can be obtained from the documentation or instructions from your email service provider.
Set up a custom domain to let your users access the Authgear pages with your unique, brand-centric domain name. You can use a custom domain (e.g. auth.yourdomain.com
) instead of the Authgear generated domain (e.g. <YOUR_APP>.authgear.cloud
).
Go to Branding > Custom Domains in your project portal.
Enter the custom domain name that you would like to connect to Authgear, and click Add.
Your custom domain will appear on the list, click Verify to start the verification process.
Go to your domain provider's site, and add DNS records based on the values shown on the portal page.
Click Verify after adding the DNS records, you may need to wait for the propagation of your updated DNS records.
You will return to the custom domain list after verifying your custom domain. Click Activate to use your custom domain.
Now you can access Authgear pages with your custom domain, your default Authgear generated domain (e.g. <YOUR_APP>.authgear.cloud
) cannot be used anymore. Update your SDK endpoint to use the new custom domain.
The certificate of your custom domain is managed by Authgear, you may need to wait for a while for certificate provisioning.
Users can access the login and logout pages directly in your Authgear project when you're using a custom domain. As a result, the post-login and post-logout links are available to help you determine where users are redirected when they access the above pages without an OAuth flow.
To configure these values, in Authgear Portal navigate to Branding > Custom Domains. Then scroll down to the Default Redirect URLs section.
Use this field to set the page where users will be redirected after login if they visit the login page directly instead of going through an OAuth flow.
The URL you enter as a post-logout link is where users will be redirected after logout when they visit the logout page directly.
Authgear provides the event logs for you to analyze security issues and monitor the business.
The portal provides an interface for you to look up the log by event and date range.
The Users Activities tab on the Audit Log page filters the log to only show activities performed by a normal user or by an admin on a user's profile.
When using the Admin API, you can filter the Audit Log by an attribute like activityTypes to omit records you're not interested in.
The following is an example that includes filters.
The above query will only return events with activity types USER_AUTHENTICATED
and USER_DELETED
.
Here is the list of activity types that are logged:
AUTHENTICATION_IDENTITY_ANONYMOUS_FAILED
Anonymous user authentication failed
AUTHENTICATION_IDENTITY_BIOMETRIC_FAILED
Authentication with biometric failed
AUTHENTICATION_IDENTITY_LOGIN_ID_FAILED
A user's login attempt failed because the email or user ID provided is not found
AUTHENTICATION_PRIMARY_OOB_OTP_EMAIL_FAILED
Authentication using the OTP sent via email failed
AUTHENTICATION_PRIMARY_OOB_OTP_SMS_FAILED
Authentication using the OTP sent via SMS failed
AUTHENTICATION_PRIMARY_PASSWORD_FAILED
A user entered an invalid password during a login attempt
AUTHENTICATION_SECONDARY_OOB_OTP_EMAIL_FAILED
2FA via email failed
AUTHENTICATION_SECONDARY_OOB_OTP_SMS_FAILED
2FA via SMS failed
AUTHENTICATION_SECONDARY_PASSWORD_FAILED
Secondary authentication using password failed
AUTHENTICATION_SECONDARY_RECOVERY_CODE_FAILED
Recovery code verification failed
AUTHENTICATION_SECONDARY_TOTP_FAILED
A 2FA attempt failed
IDENTITY_BIOMETRIC_DISABLED
Biometric login is disabled by a user or an admin
IDENTITY_BIOMETRIC_ENABLED
User enabled biometric login
IDENTITY_EMAIL_ADDED
A user or admin added a new email to an existing user
IDENTITY_EMAIL_REMOVED
An email address was removed from an existing user's profile
IDENTITY_EMAIL_UPDATED
A user updated their email address
IDENTITY_OAUTH_CONNECTED
A profile is linked to OAuth
IDENTITY_OAUTH_DISCONNECTED
A profile is unlinked from OAuth
IDENTITY_PHONE_ADDED
A user or admin added a new phone number to an existing user
IDENTITY_PHONE_REMOVED
A phone number was removed from an existing user's profile
IDENTITY_PHONE_UPDATED
A user updated their phone number
IDENTITY_USERNAME_ADDED
A user or admin added a new username to an existing user
IDENTITY_USERNAME_REMOVED
A user or admin removed the username for a user
IDENTITY_USERNAME_UPDATED
The username for a user was updated
USER_ANONYMOUS_PROMOTED
This event is triggered when an anonymous user is promoted to a normal user
USER_AUTHENTICATED
Successful user sign-in
USER_CREATED
A new user successfully registered
USER_DELETED
A user account is deleted
USER_DELETION_SCHEDULED
A user account deletion is scheduled
USER_DELETION_UNSCHEDULED
A previously scheduled user deletion is unscheduled
USER_DISABLED
User account disabled. An admin disabling a users account can trigger this event
USER_PROFILE_UPDATED
A user updated details like their profile name, gender and more
USER_REENABLED
A user account that was previously disabled is enabled
USER_SESSION_TERMINATED
An active user session is terminated
USER_SIGNED_OUT
A user that was signed in logged out
WHATSAPP_OTP_VERIFIED
User completed a verification process using WhatsApp to receive OTP
SMS_SENT
An SMS notification like OTP was sent to a user
EMAIL_SENT
An email notice like verification code was sent to a user
Each audit log event contains the following attributes in their data
id
Unique identifier of the event
seq
Sequence number of the event
type
Activity type
context
The who, when and where of the event triggered. e.g. IP address, user agent, user ID, timestamp
payload
Relevant data according to the event type:
Messaging (SMS, Email OTP): the phone number/email address of the receiver
Authentication/Identity/User actions: a snapshot of the related session and user attributes
Learn how to integrate popular analytics and tracking tools into your Authgear project using Google Tag Manager
Authgear allows you to add third-party user analytics tools to your project using Google Tag Manager.
Google Tag Manager (GTM) is a tag management tool from Google that makes it easy to add marketing tags to your website without modifying the site's source code.
Tags can help you track traffic and user behavior on your website or application.
In this guide, we will show you how to add Google Tag Manager to your Authgear project and send data to Google Analytics. You can also configure Google Tag Manager to send data from your Authgear project to other marketing tags from providers like Facebook.
In order to setup Google Tag Manager and Google Analytics with Authgear, you need to have the following:
Authgear account
Google Tag Manager Account
Google Analytics Account
The process for connecting your GTM account to Authgear is simple and can be done in these two steps.
Google Tag Manager lets you create containers that hold marketing tags. Each container has a unique ID and you'll need this container ID to connect your GTM container to Authgear.
If you don't have a container for your Authgear project yet, click on Create Account to create a new container. Enter your domain name for your Authgear project as the container name and select a target platform. For this example, we'll select Web as the target platform.
First, log in to the Authgear Portal, then select your project and navigate to Integrations.
Click on the Connect button next to the Google Tag Manager addon to open the configuration page.
Paste the GTM container ID you got from the previous step then click the Save button. And with that, you've successfully connected your GTM container to Authgear. In the next steps, we'll show you how to create tracking tags and send data to Google Analytics.
Google Analytics is one of the marketing tags we can manage from GTM. In this part of the guide, we'll set up some tags to track page views and user events like clicking on a link or button. The tags will send these data to Google Analytics.
In order to create tags that send data to Google Analytics, you need to have an active data stream on Google Analytics. GTM requires the details for this stream while creating new tags for Google Analytics.
To create a stream, log in to Google Analytics then navigate to the Admin settings page.
Create a new Google Analytics property for your Authgear project or select an existing one. Click on the Data Streams item under the property to view all streams and add a new web stream for your Authgear project.
Note down the Measurement ID for your stream as we'll be using it later to create new tags.
Before we start sending data to Google Analytics, let's create a new variable in Google Tag Manager.
Go back to GTM and select the correct container for your project.
Next, click on the Variables item on the left side navigation bar and create a new user variable with the following details:
Variable type: Data Layer Variable
Data Layer Variable Name: gtm.element.dataset.authgearEvent
Once you're done save the variable as "gtm.element.dataset.authgearEvent" and continue to the next step.
Navigate to Triggers from the sidebar and create a new trigger with the following details:
Trigger type: Click > All Elements
This trigger fires on: Some Clicks
Authgear's implementation of GTM is declarative. The primary button on each page has data-authgear-event
attribute. We'll be setting a condition for the "Some Clicks" using that attribute. Configure Some "Click" as shown below:
Next, save the trigger as "Authgear-btn-click" and continue.
Navigate to Tags from the sidebar and create a new tag with the following configurations:
Tag type: Google Analytics > Google Tag
Tag ID: <Your Tag ID is the unique Measurement ID for your stream in Google Analytics (See part 2 step 1 for more details)>
Next, expand the Advanced Settings section and set Tag firing options to Once per page.
Now, scroll down to the Trigger section of the new tag and select All Pages (page view) as the trigger.
Save this new tag as "Auth-gear-pageview" and continue.
In this step, create another tag with the following configuration:
Tag type: Google Analytics > Google Analytics: GA4 Event
Measurement ID: <Your Google Analytics stream measurement ID>
Event Name: gtm.element.dataset.authgearEvent
Next, set the trigger for this tag to the "Authgear-btn-click" trigger we created earlier.
Save the tag as "Authgear-event-tag" and continue to preview the entire setup or publish to go live.
After you publish your changes in Google Tag Manager when users generate hits or click buttons with the data-authgear-event
attribute on your project you should see data on Google Analytics.
The following is a list of values for the data-authgear-event
attribute:
authgear.button.change_password
authgear.button.change_additional_password
authgear.button.create_password
authgear.button.change_login_id
authgear.button.remove_login_id
authgear.button.resend_oob_otp
authgear.button.enter_oob_otp
authgear.button.enter_password
authgear.button.enter_recovery_code
authgear.button.enter_totp
authgear.button.send_reset_password_code
authgear.button.sign_in
authgear.button.sign_up
authgear.button.sign_out
authgear.button.oauth
authgear.button.reset_password
authgear.button.continue_with_current_account
authgear.button.use_another_account
authgear.button.remove_biometric
authgear.button.schedule_account_deletion
authgear.button.connect_oauth
authgear.button.disconnect_oauth
authgear.button.resend_verification_code
authgear.button.update_profile
authgear.button.regenerate_recovery_code
authgear.button.download_recovery_code
authgear.button.remove_totp
authgear.button.remove_oob_otp
authgear.button.setup_oob_otp
authgear.button.setup_totp
authgear.button.enter_verification_code
authgear.button.revoke_session
authgear.button.revoke_session_group
authgear.button.revoke_all_sessions
See information about the total number users and active users on your Authgear project
The Analytics section on the Authgear portal provides reports on your project activities. For example, the report shows the total number of users that sign up and active users over a specific time interval.
In this guide, you'll get detailed information about the information provided on the Authgear Analytics page and how to interpret it.
The Analytics page shows two activity bar charts that show a weekly or monthly summary of user activities on your Authgear project.
The first chart shows the total active users per week or month. Active users are users who sign up, log in, or access their accounts within a specific time.
The second bar chat in the Activities section shows the total number of users your Authgear project has over a specific time interval. That is the total number of accounts created minus deleted users.
The signup conversion piechart shows how many users visited your signup page (unique pageviews) and how many went ahead to complete the signup process. This report also shows a percentage of the signup conversion (unique pageviews vs. total signups).
This section shows how many users you have per signup method in a pie chart.
Note: The data on the Analytics page may take 24 hours to be updated.
Allow end-users to initiate account deletion within the apps.
Enable this button in the Advanced -> Account Deletion page in the Portal
Note that if you enable this feature, you have to prepare for encountering invalid session every time your users close User Settings in your mobile apps. If your users unfortunately decided to delete their account in User Settings, all their sessions will become invalid immediately.
You must verify the validity of the session every time the User Settings is closed. The open
method in the SDK is blocking. You can verify if the user session is still valid when the method resolves. Here is an example with the React Native SDK:
You can now open the account deletion directly from Authgear SDKs. The account deletion page will be opened in a WebView.
The following code examples show how to open the account deletion page from Authgear SDKs:
When the end-user has initiated the account deletion, their account will be deactivated and scheduled for deletion after the grace period.
Deactivated users are always disabled. They will not be able to complete the authentication process. The is_deactivated
status signal that the is_disabled
status was turned true
by the end-user themselves rather than the admin.
You can set the grace period for how long the user account will be deactivated before deleted from the system. The default value is 30 days, you can choose between 1 to 180 days.
An end-user account can also be deleted using the Portal. In the User Management page, click the Remove User button to remove them immediately or schedule the deletion.
Alternatively, if you did not enable the "Delete Account" button in User Settings, you can implement the button in your app by yourself. You can schedule a deletion or delete immediately.
Here is an example:
GraphQL
Here is an example:
GraphQL
You may listen to the following events to integrate the deletion behavior to your apps.
Non-blocking events
user.disabled
user.reenabled
user.deletion_scheduled
user.deletion_unscheduled
user.deleted
Blocking event
user.pre_schedule_deletion
Define and manage roles and groups that you can apply to your users
The following case is an example of how you can use roles to deliver unique features and interfaces to different categories of users of your application. Let's say you have an application XYZ that powers a transportation business. The app has roles for admin
, driver
and passenger
. You can use the value Authgear returns in UserInfo or JWT access token to enable features for managing drivers to a user with admin
role only. Similarly, you can allow only users with driver
role view features to manage their vehicle, passengers, and trip. Finally, you can restrict users with the passenger
role to only view their ticket and trip details.
In this post, you'll learn how to create roles and groups for your Authgear project and how to manage them.
You can create a group in your Authgear project and add one or more roles to the group. Both groups and roles can be applied to a user. For instance, if your Authgear project, has the following roles:
management
department_lead
team_member
And a managers
group, you can add the management
and department_lead
roles to the group. Then, adding a user to the managers
group will grant them both management
and department_lead
roles.
The following figure shows the core relationship with Groups, Roles, and Users in Authgear.
Each role or group has three properties that describe it. These include a required key
, and optional name
and description
.
The key
property serves as the identifier for the role or group. The value for key
is what AUthgear will include in the UserInfo and JWT access token of a user. A valid key must meet the following conditions:
The value of key
can not be empty.
A key must be between 1 and 40 characters long.
The valid characters are [a-zA-Z0-9:_]
.
The prefix authgear:
is reserved for Authgear internal use.
The following are some examples of valid keys:
reader
app:editor
store_manager
Name is an optional label for a role or group. The value for the name property is what will be displayed in Authgear portal. It has less strict constrict for allowed characters. For example, you can use white spaces here.
The description property is also optional. You can use it to give more details about a role or group.
In the next section of this post, we'll show you how to create roles and groups for your project.
The. following JSON document shows how roles are returned when your application requests for UserInfo:
The value of the https://authgear.com/claims/user/roles
attribute is an array that contains the roles of the current user.
Follow these steps to create new roles in your Authgear project via the Portal.
First, log in to Authgear Portal, select your project then navigate to User Management > Roles to open the Roles page.
Click the Create Role button in the middle of the Roles page (or the top right corner if you have existing roles) to start creating a new role.
Enter the Name, Role Key, and Description of your new role in their respective fields. Click on the Create button at the bottom of the form to finish creating your new role.
Repeat the above steps to add more roles.
As mentioned earlier in this post, you can also create new roles using the Admin API. In this section, we'll walk you through the steps for doing that.
Run the following mutation to create a new role:
Just like roles, you are responsible for creating groups for your Authgear project. You can also create new groups either via Authgear Portal or using the Admin API.
The steps for creating a new group from the Portal are similar to that of roles. The steps are as follows:
First, log in to Authgear Portal, select your project then navigate to User Management > Groups to open the Groups page.
Click the Create Group button in the middle of the screen (or in the top right corner if you already have some groups) to access the Create Group form.
Enter the Name, Group Key and Description in the group creation form then click the Create button to finish.
It's possible to create a new group using the Admin API GraphQL. The following guide shows the steps for doing that.
Execute the following GraphQL mutation to create a new group:
You can manage the roles you've created via the Portal or using the Admin API. In this section, we'll cover how to manage roles.
To add a role to a user, first, in the Authgear Portal, navigate to User Management > Users. From this page, you can view a list of all the users who have signed up on your Authgear project. You can also search users by their current roles there.
Next, click on the user you wish to add a new role to. This will open their User Details page. From that page, navigate to the Roles tab
To remove an existing role from a user, click on the Remove button next to the role in the user's Roles tab.
Adding a group to a role is a way of connecting a role and a group from the role management side.
To do this in Authgear Portal, first navigate to User Management > Roles, then click on the role you wish add a group to.
Next, in the details page for the selected role, go to the Groups tab, then click the Add to Group button. Select the group you wish to add from the drop-down then click Add. If there's no groups in the dropdown, try creating some new groups first.
To update the properties of an existing role such as the name, description or key, navigate to User User Management > Roles in Authgear Portal. Click on the role you wish to modify to open the Settings tab, then change the value for the property you wish to update in the form. Once you're done, click on the Save button.
To delete a role, click on the Delete button once you open the role's Settings tab.
To add a group to a user's profile in the Portal, first navigate to User Management > Users and select a user.
In the User Details page, switch to the Groups tab then click on Add to Group.
Select the group you wish to add the user to from the drop-down then click on Add.
To add a role to a group, navigate to User Management > Groups then click on the group you wish to add roles to.
In the group details page, switch to the Roles tab, then click on the Add Role button.
Select the roles you wish to add to the group from the drop-down then click on the Add button.
To update an existing group, go to User Management > Groups and click on the group you wish to update. Modify the property you wish to update using the form in the group's Setting tab. Once you're done, click on Save to keep your changes.
To delete an existing group, click on the Delete Group button once you're in the Settings tab for that group.
Use the user import API to bulk import users from external systems to your Authgear project
Some ways to add users to your Authgear project include; using the Add User UI in Authgear Portal, using the createUser() mutation in Admin API, and last but not least, having the user accounts created using sign-up page on AuthUI.
A common downside of all the above-listed methods is that they do not support batch import of users. Meaning, that you have to add users one by one. This isn't ideal for importing multiple users from existing legacy systems to Authgear. For adding bulk users, there is the User Import API.
In this post, you'll learn what the User Import API is and see examples of how to import bulk users to an Authgear project.
The following are the endpoints for the User Import API.
Use this endpoint to start a new user import task.
Use this endpoint to verify the status of an existing user import task.
In this section, you can find code for a simple example of using the User Import API to add multiple users to an Authgear project.
To follow this example and be able to run the code on your local machine, you must have the following:
Install Express.js by running the following command from your project directory: npm install express
.
As mentioned earlier in this post, the User Import API requires the Admin API JWT to access. In this step, we'll generate an Admin API JWT using Node.js.
First, install JsonWebToken (a Node package for generating JWT) by running the following command:
The following code shows how to get the token:
To import users to your Authgear project using the User Import API, make a POST HTTP(S) request to the Initiate Import endpoint (/_api/admin/users/import
).
In the following steps, we'll use the node-fetch package to make HTTP requests to the User Import API. Hence, install node-fetch by running the following command:
The following code sample demonstrates how to import 2 users from a JSON document that's stored in a simple constant (const data
):
If the user import was initiated successfully, you'll get a response that looks like this:
In the next step, we'll use the value of the id
field from the above response to query the status of the import task.
In this step, we'll make a GET HTTP(S) request to the Check Status endpoint (/_api/admin/users/import/{ID}
) to get the status of the user import task we initiated in the last step. You'll need to replace {ID}
in the URL with the value of id
in the previous response.
To do this, add a new route to the Express app that accepts the task id
as a parameter and uses that id
to query the status of the task. Here's the code for the route:
The response to the request to query the status of the import task will look like this:
From the response, you can see the status
of the entire task (import was completed
), including a summary ( { "total": 2, "inserted": 2, "updated": 0, "skipped": 0, "failed": 0 }
).
The details
field contains an array of details such as the outcome
for each user in the original JSON document.
Export users from your project into a CSV or JSON file
In this guide, you'll learn how to use the User Export API.
The User Export API allows developers to bulk export users into a file.
The export process is asynchronous. That is, the process runs in the background. Hence, you will need to initiate an export task in one endpoint call and then, make an additional call to another endpoint to get the status of the export task.
The following are the two endpoints for the User Export API:
POST
/_api/admin/users/export
Use this endpoint to create a new user export task.
Headers
Body
The Initiate Export endpoint accepts JSON input via an HTTP(S) request body. The following is an example of the input:
The format
field is where you specify the format of the export file. The value can be csv
or ndjson
.
csv
: use this field when format
is set to csv
. The value is an object with a fields
property.
csv.fields
: you can use this field to list all the user attributes you want to include as fields in the CSV file. The value should be an array and each item in the array is an object with a pointer
and an optional field_name
property that describe a user attribute.
GET
/_api/admin/users/export/{Task ID}
Use this endpoint to query the status of an existing export task. Replace {Task ID}
with the task id
returned in the response body of the initiate export endpoint.
Headers
The following example shows how to use the User Export API in a Node.js application.
First, you need to get the Admin API JWT that will be used to authenticate requests to the endpoints.
To do that, install JsonWebToken (a Node package for generating JWT) by running the following command:
Now, create a generateJWT()
function in your Express app to generate the JWT:
Make an HTTP(S) POST request to the initiate export endpoint to initiate a new user export task.
To do that, first, install the node-fetch package in your app using this command:
Then add the following code to your application:
The response to the HTTP(S) request in this step should look like this:
Response
id
: the value of id is the task ID that can be used in the check status endpoint to query the task and get the download URL for the export file.
In this step, we'll check the status of the export task we initiated by making an HTTP(S) request to the Check Status endpoint (/_api/admin/users/export/{Task ID}
). Replace {Task ID}
in the URL with the task ID for the export task in the previous task.
Add the following route to your app to check the status of an export task using the task ID:
When the status task is completed, the HTTP(S) response body will look like this:
Response
download_url
: open the URL in the value of download_url
to download the exported users file.
Note: The result from a completed export task will expire after 24 hours. Hence, after 24 hours, you can no longer use the task ID associated with the task to generate a new download link.
You can view the audit log in the Portal, or retrieve logs using the .
The API schema can be found in the . For example:
To get the container ID, log in to and navigate to the dashboard's homepage. You should find a list of all your containers and their ID. Note down the ID for the container you wish to connect to Authgear.
In Oct 2021, that all apps allowing users to create accounts should also provide ways for them to initiate account deletion within the apps, starting from January 31, 2022. It is also a good design to give your end-users more control over their data.
On Jan 22, 2022 to extend the deadline to June 30 2022.
In the pre-built page, you can show a button for the end-users to initiate account deletion.
Your backend server can invoke the mutation scheduleAccountDeletion
with the to initiate the account deletion.
Your backend server can invoke the mutation scheduleAccountDeletion
with the to initiate the account deletion.
See the event details in .
Roles and Groups can extend access management on your application that Authgear powers. Authgear includes a user's roles in the response from the and in the JWT access token.
It is up to you to create roles for your Authgear project based on your unique need and use case. You can create new roles using the Authgear Portal or the (using GraphQL).
Set up your custom code with the GraphQL endpoint. Or use the GraphiQL Explorer provided by Authgear (Navigate to Advanced > Admin API > GraphiQL Explorer in Authgear Portal to access).
Implement your own custom code that has . Alternatively, you can use the GraphiQL Explorer in Authgear Portal (Navigate to Advanced > Admin API > GraphiQL Explorer).
Then, click the Add Roles button, select a role from the drop-down menu, and click Add. If the drop-down is empty, it is possible that you have not created any roles yet. See .
The User Import API is an API that supports the bulk import of users from another system to an Authgear project. This API is not part of the Admin API GraphQL. However, a valid is required to access the endpoints of the User Import API.
To learn more detailed information about the User Import API (such as endpoints, inputs, and responses), see the .
An Authgear account. Sign up for free .
installation on your local computer.
See our post on for a more detailed guide (and examples for other programming languages/frameworks) on how to get your key ID, and private key and generate Admin API JWT.
The user data you wish to import must be provided as a JSON input in the HTTP(S) request body as specified in the .
The Export User API offers a means for exporting user data such as user ID, email, phone number, etc from your Authgear project into a or file.
To make HTTP(S) requests to Export User API endpoints, your application must be authenticated using an in the Bearer Authorization header. The API will return a "403 Forbidden" error if an invalid JWT is used.
See the for more details about the endpoints, inputs, and pointers.
See for a more detailed guide on how to get your key ID, and private key and generate Admin API JWT using different programming languages.
Content-Type
application/json
Authorization
Bearer <Admin API JWT Token>
Host
<Your Authgear Project domain>
Authorization
Bearer <Admin API JWT Token>
Host
<Your Authgear Project domain>