Web SDK
Integrate Authgear to your website with the Web SDK

Setup Application in Authgear

Signup for an account in https://portal.authgearapps.com/ and create a Project. Or you can use your self-deployed Authgear.
Continue to Portal to create a new Application in the Project
After that, we will need to create an Application in the Project Portal.
Portal
authgear.yaml (self-deployed)
Step 1: Create an application in the Portal
  1. 1.
    Go to Applications in your project portal.
  2. 2.
    Click Add Application in the top right corner.
  3. 3.
    Input the name of your application. This is for reference only.
  4. 4.
    Decide a path in your website that users will be redirected to after they have authenticated with Authgear. Add the URI to Redirect URIs. e.g.https://yourdomain.com/auth-redirect
  5. 5.
    If you are using cookie-based authentication, you can decide the path that the user redirects to after logout. Add the URI to Post Logout Redirect URIs.
  6. 6.
    Click "Save" and keep the Client ID. You can also obtain it from the Applications list later.
If you want to validate JWT access token in your server, select Issue JWT as access token. If you will forward incoming requests to Authgear Resolver Endpoint for authentication, leave this unchecked. See comparisons in Backend Integration.
Step 2: Add your website to allowed origins
  1. 1.
    Go to Applications > Allowed Origins.
  2. 2.
    Add your website origin to the allowed origins. e.g. yourdomain.com or localhost:4000 for local development.
  3. 3.
    Click "Save".
Step 3: Setup a custom domain (Required for Cookie-based authentication)
  1. 1.
    Go to Custom Domains
  2. 2.
    Add your custom domain in Input New Domain
  3. 3.
    Follow the instructions to verify and configure the custom domain.
  4. 4.
    Click "Activate" to change the domain status to "Active". The custom domain will be your new Authgear endpoint.
For cookie-based authentication, users will log in via the custom domain e.g. "auth.yourdomain.com" . So that a session cookie of your domain is set for the client and all your websites under "*.yourdomain.com" would share the same session cookies automatically.
1
http:
2
allowed_origins:
3
- "yourdomain.com"
4
- "loclhost:4000" # example for local development
5
oauth:
6
clients:
7
- name: mywebsite
8
client_id: a_random_generated_string
9
redirect_uris:
10
- "https://yourdomain.com/auth-redirect"
11
grant_types:
12
- authorization_code
13
- refresh_token
14
response_types:
15
- code
16
- none
Copied!

Install the Authgear Web SDK

The Web JS SDK is available as an npm package.
1
npm install --save --save-exact @authgear/web
Copied!

Initialize the Authgear SDK

The SDK must be properly configured before use.
1
import authgear from "@authgear/web";
2
3
authgear
4
.configure({
5
// custom domain endpoint or default endpoint
6
// default domain should be something like: https://<yourapp>.authgearapps.com
7
endpoint: "<your_app_endpoint>",
8
// Client ID of your application
9
clientID: "<your_api_key>",
10
// sessionType can be "refresh_token" or "cookie", default "refresh_token"
11
sessionType: "refresh_token",
12
})
13
.then(
14
() => {
15
// configure successfully.
16
},
17
(err) => {
18
// failed to configure.
19
}
20
);
21
Copied!
The SDK should be configured according to the authentication approach of your choice
  • Cookie-based authentication
    • endpoint must be a custom domain endpoint
    • sessionType should be set to cookie
  • Token-based authentication
    • sessionType should be set to refresh_token

Login to the application

When the user clicks login/signup on your website, make a start authorization call to redirect them to the login/signup page.
1
import authgear from "@authgear/web";
2
3
authgear
4
.startAuthorization({
5
// configure redirectURI which users will be redirected to
6
// after they have authenticated with Authgear
7
// you can use any path in your website
8
// make sure it is in the "Redirect URIs" list of the Application
9
redirectURI: "https://yourdomain.com/auth-redirect",
10
prompt: "login",
11
})
12
.then(
13
() => {
14
// started authorization, user should be redirected to Authgear
15
},
16
(err) => {
17
// failed to start authorization
18
}
19
);
20
Copied!
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 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. The UserInfo is resolved from the promise.
Once authorization succeed, the application should redirect the user to other URL such as the user's home page and remove the query parameters.
1
import authgear from "@authgear/web";
2
3
authgear.finishAuthorization().then(
4
(userInfo) => {
5
// authorized successfully
6
// you should redirect the user to another path
7
},
8
(err) => {
9
// failed to finish authorization
10
},
11
);
Copied!
Now, your user is now logged in!

Get the Logged In State

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.
1
// value can be NO_SESSION or AUTHENTICATED
2
// After authgear.configure, it only reflect SDK local state.
3
let sessionState = authgear.sessionState;
4
5
if (sessionState === "AUTHENTICATED") {
6
authgear
7
.fetchUserInfo()
8
.then((userInfo) => {
9
// sessionState is now up to date
10
})
11
.catch((e) => {
12
// sessionState is now up to date
13
// it will change to NO_SESSION if the session is invalid
14
});
15
}
Copied!
The UserInfo object provides the unique identifier of the user from your Authgear project. See more details here.

Log the user out

If you are using Token-based authentication, the logout API will revoke the user app session only. The promise will be resolved after logout and no redirection will occur.
If you are using Cookie-based authentication , the user will be redirected to your Authgear endpoint to log out their session. You should provide the redirectURI to which user will be redirected after logout.
1
import authgear from "@authgear/web";
2
3
authgear
4
.logout({
5
// redirectURI is useful only when sessionType is cookie
6
// to which users will be redirected after logout
7
// make sure it is in the "Post Logout Redirect URIs" in the application portal
8
// redirectURI: "https://yourdomain.com",
9
})
10
.then(
11
() => {
12
// logged out successfully
13
},
14
(err) => {
15
// failed to logout
16
}
17
);
Copied!

Calling an API

If you are using cookies, all requests from your applications under *.yourdomain.com to your application server will include the session cookie automatically. You can skip this section and see the next step: Backend Integration

Token-based authentication

To include the access token to the HTTP requests to your application server, there are two ways to achieve this.

Option 1: Using fetch function provided by Authgear SDK

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 fetch.
1
authgear
2
.fetch("YOUR_SERVER_URL")
3
.then(response => response.json())
4
.then(data => console.log(data));
Copied!

Option 2: Add the access token to the HTTP request header

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.
1
authgear
2
.refreshAccessTokenIfNeeded()
3
.then(() => {
4
// access token is ready to use
5
// accessToken can be string or undefined
6
// it will be empty if user is not logged in or session is invalid
7
const accessToken = authgear.accessToken;
8
9
// include Authorization header in your application request
10
const headers = {
11
Authorization: `Bearer ${accessToken}`
12
};
13
});
Copied!

Next steps

To protect your application server from unauthorized access. You will need to integrate Authgear to your backend.
Last modified 5mo ago