@asgardeo/auth-react 1.1.19 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +127 -934
- package/dist/main.js +2 -914
- package/dist/main.js.LICENSE.txt +946 -0
- package/dist/src/api.d.ts +6 -0
- package/dist/src/api.d.ts.map +1 -1
- package/dist/src/authenticate.d.ts.map +1 -1
- package/dist/src/models.d.ts +2 -1
- package/dist/src/models.d.ts.map +1 -1
- package/dist/src/secure-route.d.ts.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -2358
- package/package.json +34 -33
- package/src/api.ts +9 -0
- package/src/authenticate.tsx +6 -1
- package/src/models.ts +1 -0
- package/src/secure-route.tsx +1 -2
- package/webpack.config.js +2 -13
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|

|
|
4
4
|
[](https://stackoverflow.com/questions/tagged/wso2is)
|
|
5
|
-
[](https://discord.gg/wso2)
|
|
6
6
|
[](https://github.com/wso2/product-is/blob/master/LICENSE)
|
|
7
7
|
[](https://twitter.com/intent/follow?screen_name=wso2)
|
|
8
8
|
|
|
@@ -13,1043 +13,236 @@
|
|
|
13
13
|
- [Introduction](#introduction)
|
|
14
14
|
- [Prerequisite](#prerequisite)
|
|
15
15
|
- [Getting Started](#getting-started)
|
|
16
|
-
- [
|
|
17
|
-
-
|
|
18
|
-
-
|
|
19
|
-
-
|
|
20
|
-
-
|
|
21
|
-
-
|
|
22
|
-
-
|
|
23
|
-
|
|
24
|
-
- [trySignInSilently](#trysigninsilently)
|
|
25
|
-
- [signOut](#signout)
|
|
26
|
-
- [httpRequest](#httprequest)
|
|
27
|
-
- [httpRequestAll](#httprequestall)
|
|
28
|
-
- [requestCustomGrant](#requestcustomgrant)
|
|
29
|
-
- [revokeAccessToken](#revokeaccesstoken)
|
|
30
|
-
- [getOIDCServiceEndpoints](#getoidcserviceendpoints)
|
|
31
|
-
- [getDecodedIDToken](#getdecodedidtoken)
|
|
32
|
-
- [getIDToken](#getidtoken)
|
|
33
|
-
- [getAccessToken](#getaccesstoken)
|
|
34
|
-
- [refreshAccessToken](#refreshaccesstoken)
|
|
35
|
-
- [on](#on)
|
|
36
|
-
- [isAuthenticated](#isauthenticated)
|
|
37
|
-
- [enableHttpHandler](#enablehttphandler)
|
|
38
|
-
- [disableHttpHandler](#disablehttphandler)
|
|
39
|
-
- [updateConfig](#updateconfig)
|
|
40
|
-
- [getHttpClient](#gethttpclient)
|
|
41
|
-
- [Using the `form_post` Response Mode](#using-the-form_post-response-mode)
|
|
42
|
-
- [Storage](#storage)
|
|
43
|
-
- [Models](#models)
|
|
44
|
-
- [AuthStateInterface](#authstateinterface)
|
|
45
|
-
- [AuthReactConfig>](#authreactconfig)
|
|
46
|
-
- [BasicUserInfo](#basicuserinfo)
|
|
47
|
-
- [SignInConfig](#signinconfig)
|
|
48
|
-
- [OIDCEndpoints](#oidcendpoints)
|
|
49
|
-
- [CustomGrantConfig](#customgrantconfig)
|
|
50
|
-
- [Custom Grant Template Tags](#custom-grant-template-tags)
|
|
51
|
-
- [DecodedIDTokenPayload](#decodedidtokenpayload)
|
|
52
|
-
- [HttpRequestConfig](#httprequestconfig)
|
|
16
|
+
- [Using APIs](#using-apis)
|
|
17
|
+
- [Best practices when using APIs](#best-practices-when-using-apis)
|
|
18
|
+
- [`useAuthContext()` hook](#useauthcontext-hook)
|
|
19
|
+
- [Add a Login/Logout Button](#add-a-loginlogout-button)
|
|
20
|
+
- [Show Authenticated User's Information](#show-authenticated-users-information)
|
|
21
|
+
- [Add Routing](#add-routing)
|
|
22
|
+
- [API Documentation](#api-documentation)
|
|
23
|
+
- [Sample Apps](#sample-apps)
|
|
53
24
|
- [Develop](#develop)
|
|
54
|
-
- [Prerequisites](#prerequisites)
|
|
55
|
-
- [Installing Dependencies](#installing-dependencies)
|
|
56
25
|
- [Contribute](#contribute)
|
|
57
26
|
- [License](#license)
|
|
58
27
|
|
|
59
28
|
## Introduction
|
|
60
29
|
|
|
61
|
-
Asgardeo Auth React SDK
|
|
30
|
+
Asgardeo Auth React SDK allows React applications to use [OpenID Connect - OIDC](https://openid.net/specs/openid-connect-core-1_0.html) authentication with [Asgardeo](https://wso2.com/asgardeo) as the Consumer Identity and Access Management(CIAM) Provider. The SDK supports following capabilities
|
|
31
|
+
- [Authenticate users](#add-a-loginlogout-button)
|
|
32
|
+
- [Show Authenticated User's Information](#show-authenticated-users-information)
|
|
33
|
+
- [Retrieve Additional User Information](/API.md#getbasicuserinfo)
|
|
34
|
+
- [Secure Routes](/API.md#1-secureroute)
|
|
35
|
+
- [Secure Components](/API.md#3-authenticatedcomponent)
|
|
36
|
+
- [Send HTTP Requests to Asgardeo](/API.md#httprequest)
|
|
62
37
|
|
|
63
|
-
|
|
38
|
+
## Prerequisite - Register your application in Asgardeo
|
|
64
39
|
|
|
65
|
-
|
|
40
|
+
1. Register to [Asgardeo](https://wso2.com/asgardeo) and create an organization if you don't already have one. The organization name you choose will be referred to as `<org_name>` throughout this document.
|
|
41
|
+
2. [Register a Single Page Application in Asgardeo](https://wso2.com/asgardeo/docs/guides/applications/register-single-page-app/#register-the-app) to obtain necessory keys to integrate your application with Asgardeo. You will obtain a `client_ID` from Asgardeo for your application which will need to embed later in your application for the integration.
|
|
66
42
|
|
|
67
|
-
Create an organization in Asgardeo if you don't already have one. The organization name you choose will be referred to as `<org_name>` throughout this document.
|
|
68
43
|
|
|
69
|
-
##
|
|
70
|
-
|
|
71
|
-
### 1. Create an Application in Asgardeo
|
|
72
|
-
|
|
73
|
-
Before trying out the sample apps, you need to create an application in **Asgardeo**.
|
|
74
|
-
|
|
75
|
-
1. Navigate to [**Asgardeo Console**](https://console.asgardeo.io/login) and click on **Applications** under **Develop** tab
|
|
76
|
-
|
|
77
|
-
2. Click on **New Application** and then **Single Page Application**.
|
|
78
|
-
|
|
79
|
-
3. Enter **Sample** as the name of the app and add the redirect URL(s). You can find the relevant redirect URL(s) of each sample app in the [Running the sample apps](#2-running-the-sample-apps) section.
|
|
80
|
-
|
|
81
|
-
4. Click on Register. You will be navigated to management page of the **sample** application.
|
|
82
|
-
|
|
83
|
-
5. Add `https://localhost:3000` (or whichever the URL your app is hosted on) to **Allowed Origins** under **Access** tab and check **Public client** option.
|
|
84
|
-
|
|
85
|
-
6. Click on **Update** at the bottom.
|
|
86
|
-
|
|
87
|
-
7. Copy the configuration from the Asgardeo React Quickstart guide to your React application as shown in the above code snippet.
|
|
88
|
-
|
|
89
|
-
### 2. Running the sample apps
|
|
90
|
-
|
|
91
|
-
1. Download the sample from the given link in the Asgardeo Console.
|
|
92
|
-
|
|
93
|
-
2. Update configuration file `src/config.json` with your registered app details.
|
|
94
|
-
|
|
95
|
-
**Note:** You will only have to paste in the `clientID`(**OAuth Client Key**) generated for the application you registered.
|
|
96
|
-
|
|
97
|
-
Read more about the SDK configurations [here](#configuration) .
|
|
44
|
+
## Getting Started
|
|
98
45
|
|
|
99
|
-
|
|
100
|
-
{
|
|
101
|
-
"clientID": "",
|
|
102
|
-
"baseUrl": "https://api.asgardeo.io/t/<org_name>",
|
|
103
|
-
"signInRedirectURL": "https://localhost:3000",
|
|
104
|
-
"signOutRedirectURL": "https://localhost:3000"
|
|
105
|
-
}
|
|
106
|
-
```
|
|
46
|
+
Follow this guide to integrate Asgardeo to your own React Application. To try out the sample apps, use [this guide](/SAMPLE_APPS.md).
|
|
107
47
|
|
|
108
|
-
|
|
48
|
+
### 1. Installing the Package
|
|
109
49
|
|
|
50
|
+
Run the following command to install `@asgardeo/auth-react` & `react-router-dom` from the npm registry.
|
|
110
51
|
```bash
|
|
111
|
-
npm install
|
|
52
|
+
npm install @asgardeo/auth-react react-router-dom --save
|
|
112
53
|
```
|
|
54
|
+
> **Note**
|
|
55
|
+
> The `react-router-dom` package is a peer-dependency of the SDK and it is required to be installed for the SDK to work. We are working on making it optional.
|
|
113
56
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
#### Basic React Sample
|
|
117
|
-
|
|
118
|
-
- Download the Sample: [samples/asgardeo-react-app](https://github.com/asgardeo/asgardeo-auth-react-sdk/releases/latest/download/asgardeo-react-app.zip)
|
|
119
|
-
|
|
120
|
-
- Find More Info: [README](/samples/asgardeo-react-app/README.md)
|
|
121
|
-
|
|
122
|
-
- **Redirect URL(s):**
|
|
123
|
-
- `https://localhost:3000`
|
|
57
|
+
### 2. Import `AuthProvider` and Provide Configuration Parameters
|
|
124
58
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
### 1. Installing the Package
|
|
59
|
+
Asgardeo React SDK exposes the `AuthProvider` component, which helps you easily integrate Asgardeo to your application.
|
|
128
60
|
|
|
129
|
-
|
|
61
|
+
First, import the `AuthProvider` component from `@asgardeo/auth-react.` where you applications root component is defined.
|
|
62
|
+
> **Note**
|
|
63
|
+
> Typically the root component of a react app is defined in the index.* file.
|
|
130
64
|
|
|
65
|
+
```TypeScript
|
|
66
|
+
import { AuthProvider } from "@asgardeo/auth-react";
|
|
131
67
|
```
|
|
132
|
-
|
|
133
|
-
```
|
|
68
|
+
Then, wrap your root component with the `AuthProvider`.
|
|
134
69
|
|
|
135
|
-
### 2. Import `AuthProvider`, `useAuthContext` and Provide Configuration Parameters
|
|
136
70
|
|
|
137
71
|
```TypeScript
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
// `useAuthContext` is a React hook that provides you with authentication methods such as `signIn`.
|
|
141
|
-
import { AuthProvider, useAuthContext } from "@asgardeo/auth-react";
|
|
72
|
+
import React from "react";
|
|
73
|
+
import { AuthProvider } from "@asgardeo/auth-react";
|
|
142
74
|
|
|
143
|
-
// The config data.
|
|
144
75
|
const config = {
|
|
145
76
|
signInRedirectURL: "https://localhost:3000/sign-in",
|
|
146
77
|
signOutRedirectURL: "https://localhost:3000/dashboard",
|
|
147
|
-
clientID: "
|
|
148
|
-
baseUrl: "https://api.asgardeo.io/t/<org_name>"
|
|
78
|
+
clientID: "<client_ID>",
|
|
79
|
+
baseUrl: "https://api.asgardeo.io/t/<org_name>",
|
|
80
|
+
scope: [ "openid","profile" ]
|
|
149
81
|
};
|
|
150
82
|
|
|
151
|
-
// Encapsulate your components with the `AuthProvider`.
|
|
152
83
|
export const MyApp = (): ReactElement => {
|
|
153
84
|
return (
|
|
154
85
|
<AuthProvider config={ config }>
|
|
155
|
-
<
|
|
86
|
+
<App />
|
|
156
87
|
</AuthProvider>
|
|
157
88
|
)
|
|
158
89
|
}
|
|
159
|
-
|
|
160
|
-
const Dashboard = (): ReactElement => {
|
|
161
|
-
const { signIn } = useAuthContext();
|
|
162
|
-
const [ signedIn, setSignedIn ] = useState(false);
|
|
163
|
-
|
|
164
|
-
const handleClick = (): void => {
|
|
165
|
-
signIn(() => {
|
|
166
|
-
setSignedIn(true);
|
|
167
|
-
});
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
return (
|
|
171
|
-
<div>
|
|
172
|
-
{ signedIn && <div>You have signed in!</div> }
|
|
173
|
-
<button onClick={handleClick}> Sign In </button>
|
|
174
|
-
</div>
|
|
175
|
-
);
|
|
176
|
-
}
|
|
177
90
|
```
|
|
178
91
|
|
|
179
|
-
[
|
|
92
|
+
Once the root component is wrapped with AuthProvider, [`useAuthContext()` hook](#useauthcontext-hook) can be used anywhere within the application to implement user authentication capabilities in the application.
|
|
180
93
|
|
|
181
|
-
<!-- ## Browser Compatibility
|
|
182
94
|
|
|
183
|
-
|
|
95
|
+
## Using APIs
|
|
184
96
|
|
|
185
|
-
|
|
97
|
+
### Best practices when using APIs
|
|
186
98
|
|
|
187
|
-
|
|
188
|
-
<script src="https://unpkg.com/@asgardeo/auth-spa@0.1.26/dist/polyfilled/asgardeo-spa.production.min.js.js"></script>
|
|
189
|
-
```
|
|
190
|
-
|
|
191
|
-
You can also import a polyfilled module into your modular app. Asgardeo provides two different modules each supporting UMD and ESM.
|
|
192
|
-
You can specify the preferred module type by appending the type to the module name as follows.
|
|
193
|
-
|
|
194
|
-
To import a polyfilled ESM module:
|
|
99
|
+
Asgardeo Auth React SDK is built on top of [Asgardeo Auth SPA SDK](https://github.com/asgardeo/asgardeo-auth-spa-sdk), a base library. Hence, almost all the usable APIs from Auth SPA SDK are re-exported from Asgardeo Auth React SDK and you don't need to import dependencies from the base library to your application.
|
|
195
100
|
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
```
|
|
101
|
+
- The only SDK that should be listed in the app dependencies is `@asgardeo/auth-react`.
|
|
102
|
+
- Always import APIs from `@asgardeo/auth-react`.
|
|
199
103
|
|
|
200
|
-
|
|
104
|
+
>**Warning**
|
|
105
|
+
>IDE or Editor auto import may sometimes import certain APIs from `@asgardeo/auth-spa`, change them back manually.
|
|
201
106
|
|
|
107
|
+
<details><summary><strong>Click here for Tips:</strong> Do's When importing a component from Asgardeo React SDK</summary>
|
|
108
|
+
<p>
|
|
109
|
+
|
|
110
|
+
##### DO ✅
|
|
202
111
|
```TypeScript
|
|
203
|
-
import { AsgardeoSPAClient } from "@asgardeo/auth-
|
|
112
|
+
import { AsgardeoSPAClient } from "@asgardeo/auth-react";
|
|
204
113
|
```
|
|
205
114
|
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
**_A Web Worker cannot be used as a storage option in Internet Explorer as the browser doesn't fully support some of the modern features of web workers._**
|
|
209
|
-
-->
|
|
210
|
-
|
|
211
|
-
## APIs
|
|
212
|
-
|
|
213
|
-
### AuthProvider
|
|
214
|
-
|
|
215
|
-
This is a React Context Provider that provides the session state that contains information such as the authenticated user's display name, email address, etc., and the methods that are required to implement authentication in the React app.
|
|
216
|
-
Like every other provider, the `AuthProvider` also encapsulates the components that would need the data provided by the provider.
|
|
217
|
-
|
|
218
|
-
The provider takes a prop called `config` that accepts a config object of type [`AuthClientConfig<Config>`](#AuthClientConfig<Config>). This config object contains attributes that provide the configurations necessary for authentication. To learn more about what attributes the object takes, refer to the [`AuthClientConfig<Config>`](#AuthClientConfig<Config>) section.
|
|
219
|
-
|
|
220
|
-
In addition, the `fallback` prop is used to specify a fallback component that will be rendered when the user is not authenticated.
|
|
115
|
+
#### When including React SDK as a dependency:
|
|
221
116
|
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
If the response mode is set to `form_post`, then you will have your own ways of retrieving the authorization code and session state from your backend. In that case, you can use the `getAuthParams()` prop method to pass an async callback function that would return the `authorizationCode` and `sessionState` in a Promise. This way, the `AuthProvider` will use the authorization code returned by this method to automatically request for an access token.
|
|
227
|
-
|
|
228
|
-
#### Example
|
|
229
|
-
|
|
230
|
-
```TypeScript
|
|
231
|
-
export const MyApp = (): ReactElement => {
|
|
232
|
-
return (
|
|
233
|
-
<AuthProvider config={ config } fallback={ <div>Initializing...</div> }>
|
|
234
|
-
<Dashboard />
|
|
235
|
-
</AuthProvider>
|
|
236
|
-
)
|
|
237
|
-
}
|
|
238
|
-
```
|
|
239
|
-
|
|
240
|
-
#### Example with an external Auth SPA plugin
|
|
241
|
-
|
|
242
|
-
```TypeScript
|
|
243
|
-
import { TokenExchangePlugin } from "@asgardeo/token-exchange-plugin";
|
|
117
|
+
##### DO ✅
|
|
118
|
+
```json
|
|
119
|
+
// In package.json
|
|
244
120
|
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
<AuthProvider config={ config } plugin={ TokenExchangePlugin.getInstance() }>
|
|
248
|
-
<Dashboard />
|
|
249
|
-
</AuthProvider>
|
|
250
|
-
)
|
|
121
|
+
dependencies: {
|
|
122
|
+
"@asgardeo/auth-react": "1.1.18"
|
|
251
123
|
}
|
|
252
124
|
```
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
The SDK also provides a component called `SecureRoute` that wraps the `Route` component provided by `react-router`dom`. This allows you to secure your routes using the SDK. Only authenticated users will be taken to the route. The component let's you pass a callback function that would be fired if the user is not authenticated.
|
|
256
|
-
|
|
257
|
-
This component takes three props. The `path` and `component` props just relay the prop values directly to the `Route` component. The `callback` prop takes a callback function that is fired when an unauthenticated user access teh route. Developers can use this callback function to either to redirect the user to the login page of the app to call the [`signIn`](#signIn) method.
|
|
258
|
-
#### Example
|
|
259
|
-
```TypeScript
|
|
260
|
-
<SecureRoute path={ "/secure-page" } component={ <SecureComponent /> } callback={ callback } />
|
|
261
|
-
```
|
|
262
|
-
|
|
263
|
-
---
|
|
264
|
-
|
|
265
|
-
### SecureApp
|
|
266
|
-
This is a component that can be used to secure a React app. This component wraps a React component and renders it only
|
|
267
|
-
if the user is signed in. Otherwise, it renders the `fallback` prop. If the user is not signed in, this component automatically
|
|
268
|
-
initiates the sign-in flow.
|
|
269
|
-
|
|
270
|
-
The component takes three props, namely `fallback`, `onSignIn`, and `overrideSignIn`. The `fallback` prop
|
|
271
|
-
is used to render a fallback component during sign in. The `onSignIn` prop is used to pass a callback function that will be called after signing in. The `overrideSignIn` prop is used to specify a function that will be called to initiate the sign-in flow. By default, the `signIn` method is used to initiate the sign-in flow.
|
|
272
|
-
|
|
273
|
-
#### Example
|
|
274
|
-
```TypeScript
|
|
275
|
-
<SecureApp fallback={ <Loader /> } onSignIn{ ()=> { history.push("/home") } } >
|
|
276
|
-
<App />
|
|
277
|
-
</SecureApp>
|
|
278
|
-
```
|
|
279
|
-
---
|
|
280
|
-
### AuthenticatedComponent
|
|
281
|
-
|
|
282
|
-
This component is used to wrap the components that need authentication. If the user is authenticated, the component renders the wrapped component. If the user is not authenticated, the component renders the `fallback` prop.
|
|
283
|
-
#### Example
|
|
284
|
-
```TypeScript
|
|
285
|
-
<AuthenticatedComponent fallback={ <div>Sign in to view this section.</div> } >
|
|
286
|
-
<SecureComponent />
|
|
287
|
-
</AuthenticatedComponent>
|
|
288
|
-
```
|
|
289
|
-
### useAuthContext
|
|
290
|
-
|
|
291
|
-
This is a React hook that returns the session state that contains information such as the email address of the authenticated user and the methods that are required for implementing authentication.
|
|
292
|
-
|
|
293
|
-
#### Example
|
|
294
|
-
|
|
295
|
-
```TypeScript
|
|
296
|
-
const { signIn } = useAuthContext();
|
|
297
|
-
```
|
|
298
|
-
|
|
299
|
-
The object returned by the `useAuthContext` has a `state` attribute the value of which is an object of type [`AuthStateInterface`](#AuthStateInterface). You can refer the link to know more about what data is contained by the `state` object.
|
|
300
|
-
|
|
301
|
-
In addition to the `state` object, the hook also returns the following methods.
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
### getBasicUserInfo
|
|
305
|
-
|
|
306
|
-
```typescript
|
|
307
|
-
getBasicUserInfo(): Promise<BasicUserInfo>;
|
|
308
|
-
```
|
|
309
|
-
|
|
310
|
-
#### Returns
|
|
311
|
-
|
|
312
|
-
A Promise that resolves with [`BasicUserInfo`](#BasicUserInfo).
|
|
313
|
-
|
|
314
|
-
#### Description
|
|
315
|
-
|
|
316
|
-
This method returns a promise that resolves with the information about the authenticated user obtained from the id token as an object. To learn more what information this object contains, refer to the [`BasicUserInfo`](#BasicUserInfo) section.
|
|
317
|
-
|
|
318
|
-
#### Example
|
|
319
|
-
|
|
320
|
-
```TypeScript
|
|
321
|
-
getBasicUserInfo().then((response) => {
|
|
322
|
-
// console.log(response);
|
|
323
|
-
}).catch((error) => {
|
|
324
|
-
// console.error(error);
|
|
325
|
-
});
|
|
326
|
-
```
|
|
327
|
-
|
|
328
|
-
---
|
|
329
|
-
|
|
330
|
-
### signIn
|
|
331
|
-
|
|
332
|
-
```typescript
|
|
333
|
-
signIn(config?: SignInConfig, authorizationCode?: string, sessionState?: string, authState?: string, callback?: (response: BasicUserInfo) => void);
|
|
334
|
-
```
|
|
335
|
-
|
|
336
|
-
#### Arguments
|
|
337
|
-
|
|
338
|
-
1. config?: [`SignInConfig`](#SignInConfig) (optional)
|
|
339
|
-
An object that contains attributes that allows you to configure sign in. The `forceInit` attribute of this object, allows you to force a request to the `.well-known` endpoint even if a request has previously been sent. You can also pass key-value pairs that you want to be appended as path parameters to the authorization URL to this object. To learn more, refer to [`SignInConfig`](#SignInConfig). This object is needed only during the authorization-url-generation phase.
|
|
340
|
-
|
|
341
|
-
2. authorizationCode?: `string` (optional)
|
|
342
|
-
The `signIn` method can be passed the authorization code as an argument, which will be used to obtain the token during the token-request phase of the method. This allows developers to use different response modes such as `form_post`. To learn more about the `form_post` method refer to the [Using the `form_post` response mode](#Using-the-form_post-response-mode) section. If you're using the `query` method, then the `signIn` method automatically obtains the authorization code from the URL.
|
|
343
|
-
3. sessionState?: `string` (optional)
|
|
344
|
-
The `signIn` method can be passed the session state as an argument, which will be used to obtain the token during the token-request phase of the method. This allows developers to use different response modes such as `form_post`. To learn more about the `form_post` method refer to the [Using the `form_post` response mode](#Using-the-form_post-response-mode) section. If you're using the `query` method, then the `signIn` method automatically obtains the session state from the URL.
|
|
345
|
-
4. authState?: `string` (optional)
|
|
346
|
-
The `signIn` method can be passed the state parameter as an argument, which will be used to obtain the token during the token-request phase of the method.
|
|
347
|
-
5. callback?: (response: [`BasicUserInfo`](#BasicUserInfo)) => `void`
|
|
348
|
-
A callback function that fires when sign-in is successful. The callback function takes an object of type [`BasicUserInfo`](#BasicUserInfo) as an argument.
|
|
349
|
-
#### Description
|
|
350
|
-
|
|
351
|
-
As the name implies, this method is used to sign-in users. This method will have to be called twice to implement the two phases of the authentication process. The first phase generates the authorization URl and takes the user to the single-sign-on page of the identity server, while second phase triggers the token request to complete the authentication process. So, this method should be called when initiating authentication and when the user is redirected back to the app after authentication themselves with the server.
|
|
352
|
-
|
|
353
|
-
The `sign-in` hook is used to fire a callback function after signing in is successful. Check the [on()](#on) section for more information.
|
|
354
|
-
|
|
355
|
-
#### Example
|
|
356
|
-
|
|
357
|
-
```TypeScript
|
|
358
|
-
signIn();
|
|
359
|
-
```
|
|
360
|
-
---
|
|
361
|
-
### trySignInSilently
|
|
362
|
-
|
|
363
|
-
```typescript
|
|
364
|
-
trySignInSilently();
|
|
365
|
-
```
|
|
366
|
-
|
|
367
|
-
#### Description
|
|
368
|
-
|
|
369
|
-
This method attempts to sign a user in silently by sending an authorization request with the `prompt` query parameter set to `none`.
|
|
370
|
-
This will be useful when you want to sign a user in automatically while avoiding the browser redirects.
|
|
371
|
-
|
|
372
|
-
This uses an iFrame to check if there is an active user session in the identity server by sending an authorization request. If the request returns an authorization code, then the token request is dispatched and the returned token is stored effectively signing the user in.
|
|
373
|
-
|
|
374
|
-
To dispatch a token request, the `[signIn()](#signIn)` or this `trySignInSilently()` method should be called by the page/component rendered by the redirect URL.
|
|
375
|
-
|
|
376
|
-
This returns a promise that resolves with a `[BasicUserInfo](#BasicUserInfo)` object following a successful sign in. If the user is not signed into the Asgardeo, then the promise resolves with the boolean value of `false`.
|
|
377
|
-
|
|
378
|
-
The `sign-in` hook is used to fire a callback function after signing in is successful. Check the [on()](#on) section for more information.
|
|
379
|
-
|
|
380
|
-
> :warning: ***Since this method uses an iFrame, this method will not work if third-party cookies are blocked in the browser.***
|
|
381
|
-
|
|
382
|
-
#### Example
|
|
383
|
-
|
|
384
|
-
```typescript
|
|
385
|
-
trySignInSilently().then((response)=>{
|
|
386
|
-
if(response) {
|
|
387
|
-
// The user is signed in.
|
|
388
|
-
// handle basic user info
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
// The user is not signed in.
|
|
392
|
-
});
|
|
393
|
-
```
|
|
394
|
-
|
|
395
|
-
---
|
|
396
|
-
|
|
397
|
-
### signOut
|
|
398
|
-
|
|
399
|
-
```typescript
|
|
400
|
-
signOut();
|
|
401
|
-
```
|
|
402
|
-
|
|
403
|
-
#### Description
|
|
404
|
-
|
|
405
|
-
This method ends the user session at the identity server and logs the user out.
|
|
406
|
-
|
|
407
|
-
The `sign-out` hook is used to fire a callback function after signing out is successful. Check the [on()](#on) section for more information.
|
|
408
|
-
|
|
409
|
-
#### Example
|
|
410
|
-
|
|
411
|
-
```TypeScript
|
|
412
|
-
signOut();
|
|
413
|
-
```
|
|
414
|
-
|
|
415
|
-
---
|
|
416
|
-
|
|
417
|
-
### httpRequest
|
|
418
|
-
|
|
419
|
-
```typescript
|
|
420
|
-
httpRequest(config: `HttpRequestConfig`): Promise<HttpResponse>;
|
|
421
|
-
```
|
|
422
|
-
|
|
423
|
-
#### Arguments
|
|
424
|
-
|
|
425
|
-
1. config: `[HttpRequestConfig](#httpRequestConfig)`
|
|
426
|
-
A config object with the settings necessary to send http requests. This object is similar to the `AxiosRequestConfig` but provides these additional attributes:
|
|
427
|
-
|
|
428
|
-
|Attribute|Type|Default|Description|
|
|
429
|
-
|--|--|--|--|
|
|
430
|
-
|`attachToken`|`boolean`|`true`|If set to `true`, the token will be attached to the request header.|
|
|
431
|
-
|`shouldEncodeToFormData`|`boolean`|`false`|If set to `true`, the request body will be encoded to `FormData`. The body (specified by the `data` attribute) should be a Javascript object. |
|
|
432
|
-
|`shouldAttachIDPAccessToken`|`boolean`|`false`| If set to `true`, the IDP access token will be attached to the the request `Authorization` header. |
|
|
433
|
-
|
|
434
|
-
#### Returns
|
|
435
|
-
|
|
436
|
-
A Promise that resolves with the response.
|
|
437
|
-
|
|
438
|
-
#### Description
|
|
439
|
-
|
|
440
|
-
This method is used to send http requests to the identity server. The developer doesn't need to manually attach the access token since this method does it automatically.
|
|
441
|
-
|
|
442
|
-
If the `storage` type is set to `sessionStorage` or `localStorage`, the developer may choose to implement their own ways of sending http requests by obtaining the access token from the relevant storage medium and attaching it to the header. However, if the `storage` is set to `webWorker`, this is the _ONLY_ way http requests can be sent.
|
|
443
|
-
|
|
444
|
-
This method accepts a config object which is of type `AxiosRequestConfig`. If you have used `axios` before, you can use the `httpRequest` in the exact same way.
|
|
445
|
-
|
|
446
|
-
For example, to get the user profile details after signing in, you can query the `me` endpoint as follows:
|
|
447
|
-
|
|
448
|
-
#### Example
|
|
449
|
-
|
|
450
|
-
```TypeScript
|
|
451
|
-
const auth = AsgardeoSPAClient.getInstance();
|
|
452
|
-
|
|
453
|
-
const requestConfig = {
|
|
454
|
-
headers: {
|
|
455
|
-
"Accept": "application/json",
|
|
456
|
-
"Content-Type": "application/scim+json"
|
|
457
|
-
},
|
|
458
|
-
method: "GET",
|
|
459
|
-
url: "https://api.asgardeo.io/scim2/me"
|
|
460
|
-
};
|
|
461
|
-
|
|
462
|
-
return httpRequest(requestConfig)
|
|
463
|
-
.then((response) => {
|
|
464
|
-
// console.log(response);
|
|
465
|
-
})
|
|
466
|
-
.catch((error) => {
|
|
467
|
-
// console.error(error);
|
|
468
|
-
});
|
|
469
|
-
```
|
|
470
|
-
|
|
471
|
-
---
|
|
472
|
-
|
|
473
|
-
### httpRequestAll
|
|
474
|
-
|
|
475
|
-
```typescript
|
|
476
|
-
httpRequestAll(config[]: ): Promise<[]>;
|
|
477
|
-
```
|
|
478
|
-
|
|
479
|
-
#### Arguments
|
|
480
|
-
|
|
481
|
-
1. config[]: `HttpRequestConfig[]`
|
|
482
|
-
An array config objects with the settings necessary to send http requests. This object is similar to the `AxiosRequestConfig`.
|
|
483
|
-
|
|
484
|
-
#### Returns
|
|
485
|
-
|
|
486
|
-
A Promise that resolves with the responses.
|
|
487
|
-
|
|
488
|
-
#### Description
|
|
489
|
-
|
|
490
|
-
This method is used to send multiple http requests at the same time. This works similar to `axios.all()`. An array of config objects need to be passed as the argument and an array of responses will be returned in a `Promise` in the order in which the configs were passed.
|
|
491
|
-
|
|
492
|
-
#### Example
|
|
493
|
-
|
|
494
|
-
```TypeScript
|
|
495
|
-
httpRequestAll(configs).then((responses) => {
|
|
496
|
-
response.forEach((response) => {
|
|
497
|
-
// console.log(response);
|
|
498
|
-
});
|
|
499
|
-
}).catch((error) => {
|
|
500
|
-
// console.error(error);
|
|
501
|
-
});
|
|
502
|
-
```
|
|
125
|
+
</p>
|
|
126
|
+
</details>
|
|
503
127
|
|
|
504
128
|
---
|
|
129
|
+
### `useAuthContext()` hook
|
|
505
130
|
|
|
506
|
-
|
|
131
|
+
The `useAuthContext()` hook provided by the SDK could be used to implement the necessary authentication functionalities and access the session state that contains information such as a unique identifier for the authenticated user.
|
|
507
132
|
|
|
508
|
-
|
|
509
|
-
|
|
133
|
+
Import the `useAuthContext()` hook from `@asgardeo/auth-react`.
|
|
134
|
+
```Typescript
|
|
135
|
+
import { useAuthContext } from "@asgardeo/auth-react";
|
|
510
136
|
```
|
|
511
137
|
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
A config object to configure the custom-grant request. To learn more about the different attributes that can be used with config object, see the [`CustomGrantConfig`](#CustomGrantConfig) section.
|
|
516
|
-
2. callback?: (response: [`BasicUserInfo`](#BasicUserInfo) | `HttpResponse`<any>) => void
|
|
517
|
-
A callback function that takes an object of type [`BasicUserInfo`](#BasicUserInfo) or `HttpResponse` (depending on the `config`) as an argument and is fired when the request is successful.
|
|
518
|
-
|
|
519
|
-
#### Returns
|
|
520
|
-
|
|
521
|
-
A Promise that resolves either with the response or the [`BasicUserInfo`](#BasicUserInfo).
|
|
522
|
-
|
|
523
|
-
#### Description
|
|
524
|
-
|
|
525
|
-
This method allows developers to use custom grants provided by their Identity Providers. This method accepts an object that has the following attributes as the argument.
|
|
526
|
-
|
|
527
|
-
The `custom-grant` hook is used to fire a callback function after a custom grant request is successful. Check the [on()](#on) section for more information.
|
|
528
|
-
|
|
529
|
-
```TypeScript
|
|
530
|
-
const config = {
|
|
531
|
-
attachToken: false,
|
|
532
|
-
data: {
|
|
533
|
-
client_id: "{{clientID}}",
|
|
534
|
-
grant_type: "account_switch",
|
|
535
|
-
scope: "{{scope}}",
|
|
536
|
-
token: "{{token}}",
|
|
537
|
-
},
|
|
538
|
-
id: "account-switch",
|
|
539
|
-
returnResponse: true,
|
|
540
|
-
returnsSession: true,
|
|
541
|
-
signInRequired: true
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
requestCustomGrant(config).then((response)=>{
|
|
545
|
-
console.log(response);
|
|
546
|
-
}).catch((error)=>{
|
|
547
|
-
console.error(error);
|
|
548
|
-
});
|
|
549
|
-
```
|
|
550
|
-
|
|
551
|
-
---
|
|
552
|
-
|
|
553
|
-
### revokeAccessToken
|
|
554
|
-
|
|
555
|
-
```typescript
|
|
556
|
-
revokeAccessToken();
|
|
138
|
+
And then inside your components, you can access the context as follows
|
|
139
|
+
```Typescript
|
|
140
|
+
const { state, signIn, signOut } = useAuthContext();
|
|
557
141
|
```
|
|
558
142
|
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
143
|
+
Few common methods that you will require when implementing authentication capabilities in your application.
|
|
144
|
+
- [`signIn`](API.md#signin) - Initiate a login request to Asgardeo, process the response to obtain authentication response.
|
|
145
|
+
- [`signOut`](API.md#signout) - Logout the user from Asgardeo and clear any authentication data from the SDK storage.
|
|
146
|
+
- [`isAuthenticated`](API.md#isauthenticated) - Check whether there is an authenticated user session. Based on the result you can decide to change the application view/behaviour.
|
|
147
|
+
- [`getBasicUserInfo`](API.md#getbasicuserinfo) - Get authenticated user's basic information from the authentication response.
|
|
148
|
+
- [`getDecodedIDToken`](API.md#getdecodedidtoken) - Get the decoded `id_token` obtained in the authentication response. From there you can derive more information such as additional user-attributes.
|
|
149
|
+
- [`getIDToken`](API.md#getidtoken) - Get the `id_token` (JWT) obtained in the authentication response.
|
|
150
|
+
- [`getAccessToken`](API.md#getaccesstoken) - Get the `access_token` obtained in the authentication response.
|
|
151
|
+
- [`refreshAccessToken`](API.md#refreshaccesstoken) - Get the `refresh_token` obtained in the authentication response.
|
|
152
|
+
- [`getHttpClient`](API.md#gethttpclient) - Get an HttpClient instance so that the you can make RESTful calls to the backend, where the client will attach the necessary Authorization headers to the request.
|
|
562
153
|
|
|
563
|
-
The `
|
|
154
|
+
The [`state`](API.md##authstateinterface) object will contain attributes such as whether a user is currently logged in, the username of the currently logged-in user etc.
|
|
564
155
|
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
```TypeScript
|
|
568
|
-
revokeAccessToken();
|
|
569
|
-
```
|
|
156
|
+
>**Note**
|
|
157
|
+
>You can refer to the [detailed API documentation here](/API.md)
|
|
570
158
|
|
|
571
159
|
---
|
|
160
|
+
### Add a Login/Logout Button
|
|
572
161
|
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
getOIDCServiceEndpoints(): Promise<OIDCEndpoints>
|
|
577
|
-
```
|
|
578
|
-
|
|
579
|
-
#### Returns
|
|
580
|
-
|
|
581
|
-
A Promise that resolves with an object containing the endpoints. To learn more about what endpoints are returned, refer to the [`OIDCEndpoints`](#OIDCEndpoints) section.
|
|
582
|
-
|
|
583
|
-
#### Description
|
|
584
|
-
|
|
585
|
-
This method returns a promise that resolves with an object containing the OIDC endpoints obtained from the `.well-known` endpoint. The object contains the following attributes.
|
|
586
|
-
|
|
587
|
-
| Attribute | Description |
|
|
588
|
-
| --------------------- | ---------------------------------------------------------------------------------- |
|
|
589
|
-
| `"authorize"` | The endpoint to which the authorization request should be sent. |
|
|
590
|
-
| `"jwks"` | The endpoint from which JSON Web Key Set can be obtained. |
|
|
591
|
-
| `"oidcSessionIFrame"` | The URL of the page that should be loaded in an IFrame to get session information. |
|
|
592
|
-
| `"revoke"` | The endpoint to which the revoke-token request should be sent. |
|
|
593
|
-
| `"token"` | The endpoint to which the token request should be sent. |
|
|
594
|
-
| `"wellKnown"` | The well-known endpoint from which OpenID endpoints of the server can be obtained. |
|
|
595
|
-
|
|
596
|
-
#### Example
|
|
597
|
-
|
|
598
|
-
```TypeScript
|
|
599
|
-
getOIDCServiceEndpoints().then((endpoints) => {
|
|
600
|
-
// console.log(endpoints);
|
|
601
|
-
}).error((error) => {
|
|
602
|
-
// console.error(error);
|
|
603
|
-
});
|
|
162
|
+
You can use the `signIn()` method from `useAuthContext()` to easily implement a **login button**.
|
|
163
|
+
```Typescript
|
|
164
|
+
<button onClick={ () => signIn() }>Login</button>
|
|
604
165
|
```
|
|
605
166
|
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
```typescript
|
|
611
|
-
getDecodedIDToken(): Promise<DecodedIDTokenPayload>
|
|
167
|
+
Similarly to the above step, we can use the `signOut()` method from `useAuthContext()` to implement a **logout button**.
|
|
168
|
+
```Typescript
|
|
169
|
+
<button onClick={() => signOut()}>Logout</button>
|
|
612
170
|
```
|
|
171
|
+
Clicking on **Login button** will take the user to Asgardeo login page. Upon successful `signIn()`, the user will be redirected to the app (based on the specified `signInRedirectURL`) and the `state.isAuthenticated` will be set to `true`.
|
|
613
172
|
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
A promise that returns with the [`DecodedIDTokenPayload`](#DecodedIDTokenPayload) object.
|
|
617
|
-
|
|
618
|
-
#### Description
|
|
173
|
+
Clicking on **Logout button** will sign out the user and will be redirected to `signOutRedirectURL` and the `state.isAuthenticated` will be set to `false`.
|
|
619
174
|
|
|
620
|
-
|
|
175
|
+
> **Note**
|
|
176
|
+
> Instead of buttons you can use the `signIn()` & `signOut()` methods from the SDK to implement any preffered user-experience in your application
|
|
621
177
|
|
|
622
|
-
|
|
178
|
+
You can use the `state.isAuthenticated` attribute to check the authenticated status of the user.
|
|
623
179
|
|
|
624
|
-
```TypeScript
|
|
625
|
-
getDecodedIDToken().then((idToken) => {
|
|
626
|
-
// console.log(idToken);
|
|
627
|
-
}).error((error) => {
|
|
628
|
-
// console.error(error);
|
|
629
|
-
});
|
|
630
|
-
```
|
|
631
180
|
---
|
|
181
|
+
### Show Authenticated User's Information
|
|
632
182
|
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
```
|
|
638
|
-
|
|
639
|
-
#### Returns
|
|
640
|
-
|
|
641
|
-
A promise that returns with the IDP [`DecodedIDTokenPayload`](#DecodedIDTokenPayload) object.
|
|
642
|
-
|
|
643
|
-
#### Description
|
|
644
|
-
|
|
645
|
-
This method returns a promise that resolves with the decoded payload of the JWT ID token provided by the IDP.
|
|
646
|
-
|
|
647
|
-
#### Example
|
|
648
|
-
|
|
649
|
-
```TypeScript
|
|
650
|
-
getDecodedIDPIDToken().then((idToken) => {
|
|
651
|
-
// console.log(idToken);
|
|
652
|
-
}).error((error) => {
|
|
653
|
-
// console.error(error);
|
|
654
|
-
});
|
|
655
|
-
```
|
|
656
|
-
---
|
|
657
|
-
|
|
658
|
-
### getIDToken
|
|
659
|
-
|
|
660
|
-
```TypeScript
|
|
661
|
-
getIDToken(): Promise<string>
|
|
662
|
-
```
|
|
663
|
-
|
|
664
|
-
#### Returns
|
|
665
|
-
|
|
666
|
-
idToken: `Promise<string>`
|
|
667
|
-
The id token.
|
|
668
|
-
|
|
669
|
-
#### Description
|
|
670
|
-
|
|
671
|
-
This method returns the id token.
|
|
672
|
-
|
|
673
|
-
#### Example
|
|
674
|
-
|
|
675
|
-
```TypeScript
|
|
676
|
-
const idToken = await getIDToken();
|
|
677
|
-
```
|
|
678
|
-
---
|
|
679
|
-
|
|
680
|
-
### getAccessToken
|
|
681
|
-
|
|
682
|
-
```typescript
|
|
683
|
-
getAccessToken(): Promise<string>;
|
|
684
|
-
```
|
|
685
|
-
|
|
686
|
-
#### Returns
|
|
687
|
-
|
|
688
|
-
A Promise that resolves with the access token.
|
|
689
|
-
|
|
690
|
-
#### Description
|
|
691
|
-
|
|
692
|
-
This returns a promise that resolves with the access token. The promise resolves successfully only if the storage type is set to a type other than `webWorker`. Otherwise, an error is thrown.
|
|
693
|
-
|
|
694
|
-
#### Example
|
|
695
|
-
|
|
696
|
-
```TypeScript
|
|
697
|
-
getAccessToken().then((token) => {
|
|
698
|
-
// console.log(token);
|
|
699
|
-
}).error((error) => {
|
|
700
|
-
// console.error(error);
|
|
701
|
-
});
|
|
702
|
-
```
|
|
703
|
-
|
|
704
|
-
### refreshAccessToken
|
|
705
|
-
|
|
706
|
-
```typescript
|
|
707
|
-
refreshAccessToken(): Promise<BasicUserInfo>;
|
|
708
|
-
```
|
|
709
|
-
|
|
710
|
-
#### Returns
|
|
711
|
-
|
|
712
|
-
A Promise that resolves with the [`BasicUserInfo`](#BasicUserInfo) object.
|
|
713
|
-
|
|
714
|
-
#### Description
|
|
715
|
-
|
|
716
|
-
This refreshes the access token and stores the refreshed session information in either the session or local storage as per your configuration. Note that this method is not required to be used when the storage type is set to `webWorker` since the web worker automatically refreshes the token and there is no need for the developer to do it.
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
#### Example
|
|
720
|
-
|
|
721
|
-
```TypeScript
|
|
722
|
-
refreshAccessToken().then((response)=>{
|
|
723
|
-
// console.log(response);
|
|
724
|
-
}).catch((error)=>{
|
|
725
|
-
// console.error(error);
|
|
726
|
-
});
|
|
727
|
-
```
|
|
728
|
-
|
|
729
|
-
### on
|
|
730
|
-
|
|
731
|
-
```typescript
|
|
732
|
-
on(hook: string, callback: () => void, id?: string): void
|
|
733
|
-
```
|
|
734
|
-
|
|
735
|
-
#### Arguments
|
|
736
|
-
|
|
737
|
-
1. hook: `string`
|
|
738
|
-
The name of the hook.
|
|
739
|
-
2. callback: `() => void`
|
|
740
|
-
The callback function that should be fired.
|
|
741
|
-
3. id?: `string`
|
|
742
|
-
An id for the method. This is required only when the hook type is `custom-grant`.
|
|
183
|
+
The following code snippet demonstrates the usage of the `state` object, together with `signIn()` and `signOut()` methods from the context.
|
|
184
|
+
```Typescript
|
|
185
|
+
import React from "react";
|
|
186
|
+
import { useAuthContext } from "@asgardeo/auth-react";
|
|
743
187
|
|
|
744
|
-
|
|
188
|
+
function App() {
|
|
745
189
|
|
|
746
|
-
|
|
190
|
+
const { state, signIn, signOut } = useAuthContext();
|
|
747
191
|
|
|
748
|
-
|
|
192
|
+
return (
|
|
193
|
+
<div className="App">
|
|
194
|
+
{
|
|
195
|
+
state.isAuthenticated
|
|
196
|
+
? (
|
|
197
|
+
<div>
|
|
198
|
+
<ul>
|
|
199
|
+
<li>{state.username}</li>
|
|
200
|
+
</ul>
|
|
749
201
|
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
| `"http-request-success"` | `httpRequest()` (Called when an http requests returns a response successfully) |
|
|
759
|
-
| `"end-user-session"` | `endUserSession()` | A boolean value indicating if the process was successful or not |
|
|
760
|
-
| `"custom-grant"` | `customGrant()` | Returns the response from the custom grant request. |
|
|
761
|
-
|
|
762
|
-
**When the user signs out, the user is taken to the identity server's logout page and then redirected back to the SPA on successful logout. Hence, developers should ensure that the `"sign-out"` hook is called when the page the user is redirected to loads.**
|
|
763
|
-
|
|
764
|
-
#### Example
|
|
765
|
-
|
|
766
|
-
```TypeScript
|
|
767
|
-
on("sign-in", () => {
|
|
768
|
-
//called after signing in.
|
|
769
|
-
});
|
|
770
|
-
```
|
|
771
|
-
|
|
772
|
-
---
|
|
773
|
-
|
|
774
|
-
### isAuthenticated
|
|
775
|
-
|
|
776
|
-
```TypeScript
|
|
777
|
-
isAuthenticated(): boolean
|
|
778
|
-
```
|
|
779
|
-
|
|
780
|
-
#### Returns
|
|
781
|
-
|
|
782
|
-
isAuth: `boolean`
|
|
783
|
-
A boolean value that indicates of the user is authenticated or not.
|
|
784
|
-
|
|
785
|
-
#### Description
|
|
786
|
-
|
|
787
|
-
This method returns a boolean value indicating if the user is authenticated or not.
|
|
788
|
-
|
|
789
|
-
#### Example
|
|
790
|
-
|
|
791
|
-
```TypeScript
|
|
792
|
-
const isAuth = isAuthenticated();
|
|
793
|
-
```
|
|
794
|
-
|
|
795
|
-
---
|
|
796
|
-
|
|
797
|
-
### enableHttpHandler
|
|
798
|
-
|
|
799
|
-
```typescript
|
|
800
|
-
enableHttpHandler(): Promise<Boolean>
|
|
801
|
-
```
|
|
802
|
-
|
|
803
|
-
#### Returns
|
|
804
|
-
|
|
805
|
-
A Promise that resolves with a `boolean` value indicating if the call was successful.
|
|
806
|
-
|
|
807
|
-
#### Description
|
|
808
|
-
|
|
809
|
-
This enables the callback functions attached to the http client. The callback functions are enabled by default. This needs to be called only if the [disableHttpHandler](#disableHttpHandler) method was called previously.
|
|
810
|
-
|
|
811
|
-
#### Example
|
|
202
|
+
<button onClick={() => signOut()}>Logout</button>
|
|
203
|
+
</div>
|
|
204
|
+
)
|
|
205
|
+
: <button onClick={() => signIn()}>Login</button>
|
|
206
|
+
}
|
|
207
|
+
</div>
|
|
208
|
+
);
|
|
209
|
+
}
|
|
812
210
|
|
|
813
|
-
|
|
814
|
-
enableHttpHandler();
|
|
211
|
+
export default App;
|
|
815
212
|
```
|
|
816
|
-
|
|
817
213
|
---
|
|
214
|
+
### Add Routing
|
|
818
215
|
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
```typescript
|
|
822
|
-
disableHttpHandler(): Promise<boolean>
|
|
823
|
-
```
|
|
824
|
-
|
|
825
|
-
#### Returns
|
|
826
|
-
|
|
827
|
-
A Promise that resolves with a `boolean` value indicating if the call was successful.
|
|
828
|
-
|
|
829
|
-
#### Description
|
|
830
|
-
|
|
831
|
-
This disables the callback functions attached to the http client.
|
|
832
|
-
|
|
833
|
-
#### Example
|
|
834
|
-
|
|
835
|
-
```TypeScript
|
|
836
|
-
disableHttpHandler();
|
|
837
|
-
```
|
|
838
|
-
|
|
839
|
-
### updateConfig
|
|
840
|
-
|
|
841
|
-
```TypeScript
|
|
842
|
-
updateConfig(config: Partial<AuthClientConfig<T>>): void
|
|
843
|
-
```
|
|
844
|
-
|
|
845
|
-
#### Arguments
|
|
846
|
-
|
|
847
|
-
1. config: [`AuthClientConfig<T>`](#AuthClientConfig<T>)
|
|
848
|
-
|
|
849
|
-
The config object containing the attributes that can be used to configure the SDK. To learn more about the available attributes, refer to the [`AuthClientConfig>T>`](#AuthClientConfig<T>) model.
|
|
850
|
-
|
|
851
|
-
#### Description
|
|
852
|
-
|
|
853
|
-
This method can be used to update the configurations passed into the constructor of the `AsgardeoAuthClient`. Please note that every attribute in the config object passed as the argument here is optional. Use this method if you want to update certain attributes after instantiating the class.
|
|
854
|
-
|
|
855
|
-
#### Example
|
|
856
|
-
|
|
857
|
-
```TypeScript
|
|
858
|
-
updateConfig({
|
|
859
|
-
signOutRedirectURL: "https://localhost:3000/sign-out"
|
|
860
|
-
});
|
|
861
|
-
```
|
|
216
|
+
If your application needs routing, the SDK provides a multiple approaches to secure routes in your application. You can read more about [routing capabilities in Asgardeo here](/API.md#securing-routes-with-asgardeo).
|
|
862
217
|
|
|
863
218
|
---
|
|
219
|
+
### API Documentation
|
|
864
220
|
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
```TypeScript
|
|
868
|
-
getHttpClient(): `HttpClientInstance`
|
|
869
|
-
```
|
|
870
|
-
|
|
871
|
-
#### Returns
|
|
872
|
-
|
|
873
|
-
An `HttpClientInstance`
|
|
221
|
+
Additionally to above, Asgardeo offers a wide range of APIs that you can use to integrate and make use of Asgardeo within your React Application. You can refer to a [detailed API documentation here](/API.md).
|
|
874
222
|
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
This method returns the `HttpClientInstance`. This is the client that is used to send http requests internally.
|
|
878
|
-
|
|
879
|
-
#### Example
|
|
880
|
-
|
|
881
|
-
```TypeScript
|
|
882
|
-
const httpClient = getHttpClient();
|
|
883
|
-
```
|
|
884
|
-
|
|
885
|
-
## Using the `form_post` response mode
|
|
886
|
-
|
|
887
|
-
When the `responseMode` is set to `form_post`, the authorization code is sent in the body of a `POST` request as opposed to in the URL. So, the Single Page Application should have a backend to receive the authorization code and send it back to the Single Page Application.
|
|
888
|
-
|
|
889
|
-
The backend can then inject the authorization code into a JavaScript variable while rendering the webpage in the server side. But this results in the authorization code getting printed in the HTML of the page creating a **threat vector**.
|
|
890
|
-
|
|
891
|
-
To address this issue, we recommend storing the authorization code in a server session variable and providing the Single Page Application a separate API endpoint to request the authorization code. The server, when the request is received, can then respond with the authorization code from the server session.
|
|
892
|
-
|
|
893
|
-

|
|
894
|
-
|
|
895
|
-
You can refer to a sample implementation using JSP [here](/samples/java-webapp).
|
|
896
|
-
|
|
897
|
-
## Storage
|
|
898
|
-
|
|
899
|
-
Asgardeo allows the session information including the access token to be stored in three different places, namely,
|
|
900
|
-
|
|
901
|
-
1. Session storage
|
|
902
|
-
2. Local storage
|
|
903
|
-
3. Web worker
|
|
904
|
-
4. Browser memory
|
|
905
|
-
|
|
906
|
-
Of the four methods, storing the session information in the **web worker** is the **safest** method. This is because the web worker cannot be accessed by third-party libraries and data there cannot be stolen through XSS attacks. However, when using a web worker to store the session information, the [`httpRequest`](#httprequest) method has to be used to send http requests. This method will route the request through the web worker and the web worker will attach the access token to the request before sending it to the server.
|
|
907
|
-
|
|
908
|
-
```TypeScript
|
|
909
|
-
initialize(config);
|
|
910
|
-
```
|
|
911
|
-
|
|
912
|
-
## Models
|
|
913
|
-
|
|
914
|
-
### AuthStateInterface
|
|
915
|
-
|
|
916
|
-
| Attribute | Type | Description |
|
|
917
|
-
| :---------------- | :-------- | :------------------------------------------------------------------------ |
|
|
918
|
-
| `allowedScopes` | `string` | The scopes that are allowed for the user. |
|
|
919
|
-
| `displayName` | `string` | The display name of the user. |
|
|
920
|
-
| `email` | `string` | The email address of the user. |
|
|
921
|
-
| `isAuthenticated` | `boolean` | Specifies if the user is authenticated or not. |
|
|
922
|
-
| `isLoading` | `boolean` | Specifies if the authentication requests are loading. |
|
|
923
|
-
| `username` | `string` | The username of the user. |
|
|
924
|
-
| `sub` | `string` | The `uid` corresponding to the user to whom the ID token belongs to. |
|
|
925
|
-
|
|
926
|
-
### AuthReactConfig
|
|
927
|
-
|
|
928
|
-
| Attribute | Required/Optional | Type | Default Value | Description |
|
|
929
|
-
| --------- | ----------------- | ---- | ------------- |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
930
|
-
| `signInRedirectURL` | Required | `string` | "" | The URL to redirect to after the user authorizes the client app. eg: `https//localhost:3000/sign-in` |
|
|
931
|
-
| `signOutRedirectURL` | Optional | `string` | The `signInRedirectURL` URL will be used if this value is not provided. | The URL to redirect to after the user | signs out. eg: `https://localhost:3000/dashboard` |
|
|
932
|
-
| `clientHost` | Optional | `string` | The origin of the client app obtained using `window.origin` | The hostname of the client app. eg: `https://localhost:3000` |
|
|
933
|
-
| `clientID` | Required | `string` | "" | The client ID of the OIDC application hosted in the Asgardeo. |
|
|
934
|
-
| `clientSecret` | Optional | `string` | "" | The client secret of the OIDC application |
|
|
935
|
-
| `enablePKCE` | Optional | `boolean` | `true` | Specifies if a PKCE should be sent with the request for the authorization code. |
|
|
936
|
-
| `prompt` | Optional | `string` | "" | Specifies the prompt type of an OIDC request |
|
|
937
|
-
| `responseMode` | Optional | `ResponseMode` | `"query"` | Specifies the response mode. The value can either be `query` or `form_post` |
|
|
938
|
-
| `scope` | Optional | `string[]` | `["openid"]` | Specifies the requested scopes. |
|
|
939
|
-
| `baseUrl` | Required (If `wellKnownEndpoint` or `endpoints` is not provided) | `string` | "" | The origin of the Identity Provider. eg: `https://www.asgardeo.io/t/<org_name>` |
|
|
940
|
-
| `endpoints` | Optional (Required to provide all endpoints, if `wellKnownEndpoint` or `baseUrl` is not provided) | `OIDCEndpoints` | [OIDC Endpoints Default Values](#oidc-endpoints) | The OIDC endpoint URLs. The SDK will try to obtain the endpoint URLS | using the `.well-known` endpoint. If this fails, the SDK will use these endpoint URLs. If this attribute is not set, then the default endpoint URLs will be | used. However, if the `overrideWellEndpointConfig` is set to `true`, then this will override the endpoints obtained from the `.well-known` endpoint. |
|
|
941
|
-
`wellKnownEndpoint` | Optional | `string` | `"/oauth2/token/.well-known/openid-configuration"` | The URL of the `.well-known` endpoint. |
|
|
942
|
-
| `overrideWellEndpointConfig` | Optional | `boolean` | `false` | If this option is set to `true`, then the `endpoints` object will override endpoints obtained | from the `.well-known` endpoint. If this is set to `false`, then this will be used as a fallback if the request to the `.well-known` endpoint fails. |
|
|
943
|
-
| `validateIDToken` | Optional | `boolean` | `true` | Allows you to enable/disable JWT ID token validation after obtaining the ID token. |
|
|
944
|
-
| `clockTolerance` | Optional | `number` | `60` | Allows you to configure the leeway when validating the id_token. |
|
|
945
|
-
| `skipRedirectCallback` | Optional | `boolean` | `false` | Stop listening to Auth param changes i.e `code` & `session_state` to trigger auto login. |
|
|
946
|
-
| [`storage`](#storage) | Optional | `"sessionStorage"`, `"webWorker"`, `"localStorage"` | `"sessionStorage"` | The storage medium where the session information such as the access token should be stored. | |
|
|
947
|
-
| `resourceServerURLs` |Required if the `storage` is set to `webWorker` | `string[]` | `[]` | The URLs of the API endpoints. This is required if the storage method is set to `webWorker`. Additionally, when API calls are made through the [`httpRequest`](#httprequest) or the [`httpRequestAll`](#httprequestall) method, only the calls to the endpoints specified either in `baseURL` or in `resourceServerURLs` attributes will be allowed. Everything else will be denied. | |
|
|
948
|
-
|`requestTimeout` | Optional | `number`| 60000 (seconds) | Specifies in seconds how long a request to the web worker should wait before being timed out. |
|
|
949
|
-
| `disableTrySignInSilently` | Optional | `boolean` | `true` | Specifies if the SDK should try to sign in silently on mount. |
|
|
950
|
-
|`enableOIDCSessionManagement` |Optional|`boolean`| false | Flag to enable OIDC Session Management. Set this flag to `true` to add single logout capabilities to your application. |
|
|
951
|
-
|
|
952
|
-
### BasicUserInfo
|
|
953
|
-
|
|
954
|
-
| Attribute | Type | Description |
|
|
955
|
-
| :-------------- | :------- | :------------------------------------------------------------------------------------------------- |
|
|
956
|
-
| `email` | `string` | The email address of the user. |
|
|
957
|
-
| `username` | `string` | The username of the user. |
|
|
958
|
-
| `displayName` | `string` | The display name of the user. It is the `preferred_username` in the id token payload or the `sub`. |
|
|
959
|
-
| `allowedScopes` | `string` | The scopes allowed for the user. |
|
|
960
|
-
| `tenantDomain` | `string` | The tenant domain to which the user belongs. |
|
|
961
|
-
| `sessionState` | `string` | The session state. |
|
|
962
|
-
|
|
963
|
-
### SignInConfig
|
|
964
|
-
|
|
965
|
-
| Method | Required/Optional | Type | Default Value | Description |
|
|
966
|
-
| ------------- | ----------------- | --------------------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
967
|
-
| `fidp` | Optional | `string` | "" | The `fidp` parameter that can be used to redirect a user directly to an IdP's sign-in page. |
|
|
968
|
-
| `forceInit` | Optional | `boolean` | `false` | Forces obtaining the OIDC endpoints from the `.well-known` endpoint. A request to this endpoint is not sent if a request has already been sent. This forces a request. |
|
|
969
|
-
| `callOnlyOnRedirect` | Optional | `boolean` | `false` | Specifies if the SDK should only call the `signIn` method when the user is redirected back to the client app. |
|
|
970
|
-
| key: `string` | Optional | `string` \| `boolean` | "" | Any key-value pair to be appended as path parameters to the authorization URL. |
|
|
971
|
-
|
|
972
|
-
### OIDCEndpoints
|
|
973
|
-
|
|
974
|
-
| Method | Type | Default Value | Description |
|
|
975
|
-
| ----------------------- | -------- | -------------------------------------------------- | ------------------------------------------------------------------------- |
|
|
976
|
-
| `authorizationEndpoint` | `string` | `"/oauth2/authorize"` | The authorization endpoint. |
|
|
977
|
-
| `tokenEndpoint` | `string` | `"/oauth2/token"` | The token endpoint. |
|
|
978
|
-
| `userinfoEndpoint` | `string` | "" | The user-info endpoint. |
|
|
979
|
-
| `jwksUri` | `string` | `"/oauth2/jwks"` | The JWKS URI. |
|
|
980
|
-
| `registrationEndpoint` | `string` | "" | The registration endpoint. |
|
|
981
|
-
| `revocationEndpoint` | `string` | `"/oauth2/revoke"` | The token-revocation endpoint. |
|
|
982
|
-
| `introspectionEndpoint` | `string` | "" | The introspection endpoint. |
|
|
983
|
-
| `checkSessionIframe` | `string` | `"/oidc/checksession"` | The check-session endpoint. |
|
|
984
|
-
| `endSessionEndpoint` | `string` | `"/oidc/logout"` | The end-session endpoint. |
|
|
985
|
-
| `issuer` | `string` | "" | The issuer of the token. |
|
|
986
|
-
| `wellKnownEndpoint` | `string` | `"/oauth2/token/.well-known/openid-configuration"` | The well-known endpoint. This is the default endpoint defined in the SDK. |
|
|
987
|
-
|
|
988
|
-
### CustomGrantConfig
|
|
989
|
-
|
|
990
|
-
| Attribute | Required/Optional | Type | Default Value | Description |
|
|
991
|
-
| ---------------- | ----------------- | --------- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
992
|
-
| `id` | Required | `string` | "" | Every custom-grant request should have an id. This attributes takes that id. |
|
|
993
|
-
| `data` | Required | `any` | `null` | The data that should be sent in the body of the custom-grant request. You can use template tags to send session information. Refer to the [Custom Grant Template Tags](#custom-grant-template-tags) section for more details. |
|
|
994
|
-
| `signInRequired` | Required | `boolean` | `false` | Specifies if the user should be sign-in or not to dispatch this custom-grant request. |
|
|
995
|
-
| `attachToken` | Required | `boolean` | `false` | Specifies if the access token should be attached to the header of the request. |
|
|
996
|
-
| `returnsSession` | Required | `boolean` | `false` | Specifies if the the request returns session information such as the access token. |
|
|
997
|
-
|
|
998
|
-
#### Custom Grant Template Tags
|
|
999
|
-
|
|
1000
|
-
Session information can be attached to the body of a custom-grant request using template tags. This is useful when the session information is not exposed outside the SDK but you want such information to be used in custom-grant requests. The following table lists the available template tags.
|
|
1001
|
-
|Tag|Data|
|
|
1002
|
-
|--|--|
|
|
1003
|
-
|"{{token}}" | The access token.|
|
|
1004
|
-
|{{username}}" | The username.|
|
|
1005
|
-
|"{{scope}}" | The scope.|
|
|
1006
|
-
|{{clientID}}" | The client ID.|
|
|
1007
|
-
|"{{clientSecret}}" | The client secret.|
|
|
1008
|
-
|
|
1009
|
-
#### The data attribute
|
|
1010
|
-
|
|
1011
|
-
### DecodedIDTokenPayload
|
|
1012
|
-
|
|
1013
|
-
| Method | Type | Description |
|
|
1014
|
-
| ------------------ | ---------------------- | ---------------------------------------------- |
|
|
1015
|
-
| aud | `string` \| `string[]` | The audience. |
|
|
1016
|
-
| sub | `string` | The subject. This is the username of the user. |
|
|
1017
|
-
| iss | `string` | The token issuer. |
|
|
1018
|
-
| email | `string` | The email address. |
|
|
1019
|
-
| preferred_username | `string` | The preferred username. |
|
|
1020
|
-
| tenant_domain | `string` | The tenant domain to which the user belongs. |
|
|
1021
|
-
|
|
1022
|
-
### HTTPRequestConfig
|
|
1023
|
-
This extends the `AxiosRequestConfig` by providing an additional attribute that is used to specify if the access token should be attached to the request or not.
|
|
1024
|
-
|Attribute | Type | Description|
|
|
1025
|
-
|--|--|--|
|
|
1026
|
-
|attachToken| `boolean`| Specifies if the access token should be attached to the header of the request.|
|
|
223
|
+
## Sample Apps
|
|
224
|
+
Sample React Apps offered by Asgardeo will allow you to take Asgardeo for a spin without having to setup your own application. You can see [how to setup sample apps here](/SAMPLE_APPS.md).
|
|
1027
225
|
|
|
1028
226
|
## Develop
|
|
1029
227
|
|
|
1030
228
|
### Prerequisites
|
|
1031
|
-
|
|
1032
229
|
- `Node.js` (version 10 or above).
|
|
1033
230
|
- `yarn` package manager.
|
|
1034
231
|
|
|
1035
232
|
### Installing Dependencies
|
|
233
|
+
The repository is a mono repository. The SDK repository is found in the [lib](/lib/) directory. You can install the dependencies by running the following command at the root.
|
|
1036
234
|
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
```
|
|
235
|
+
```bash
|
|
1040
236
|
yarn build
|
|
1041
237
|
```
|
|
1042
238
|
|
|
1043
239
|
## Contribute
|
|
1044
|
-
|
|
1045
240
|
Please read [Contributing to the Code Base](http://wso2.github.io/) for details on our code of conduct, and the process for submitting pull requests to us.
|
|
1046
241
|
|
|
1047
242
|
### Reporting issues
|
|
1048
|
-
|
|
1049
243
|
We encourage you to report issues, improvements, and feature requests creating [Github Issues](https://github.com/asgardeo/asgardeo-auth-react-sdk/issues).
|
|
1050
244
|
|
|
1051
245
|
Important: And please be advised that security issues must be reported to security@wso2com, not as GitHub issues, in order to reach the proper audience. We strongly advise following the WSO2 Security Vulnerability Reporting Guidelines when reporting the security issues.
|
|
1052
246
|
|
|
1053
247
|
## License
|
|
1054
|
-
|
|
1055
248
|
This project is licensed under the Apache License 2.0. See the [LICENSE](LICENSE) file for details.
|