@asgardeo/auth-react 1.1.20 → 2.0.1
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 +136 -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 +9 -1
- package/src/models.ts +1 -0
- package/src/secure-route.tsx +1 -2
- package/webpack.config.js +8 -19
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,245 @@
|
|
|
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
|
|
44
|
+
## Getting Started
|
|
90
45
|
|
|
91
|
-
|
|
46
|
+
Follow this guide to integrate Asgardeo to your own React Application. To try out the sample apps, use [this guide](/SAMPLE_APPS.md).
|
|
92
47
|
|
|
93
|
-
|
|
48
|
+
### 1. Installing the Package
|
|
94
49
|
|
|
95
|
-
|
|
50
|
+
Run the following command to install `@asgardeo/auth-react` & `react-router-dom` from the npm registry.
|
|
96
51
|
|
|
97
|
-
|
|
52
|
+
Use below command if you are using *React v16.8* or greater & *React Router v6*
|
|
98
53
|
|
|
99
|
-
```
|
|
100
|
-
|
|
101
|
-
"clientID": "",
|
|
102
|
-
"baseUrl": "https://api.asgardeo.io/t/<org_name>",
|
|
103
|
-
"signInRedirectURL": "https://localhost:3000",
|
|
104
|
-
"signOutRedirectURL": "https://localhost:3000"
|
|
105
|
-
}
|
|
54
|
+
```bash
|
|
55
|
+
npm install @asgardeo/auth-react react-router-dom --save
|
|
106
56
|
```
|
|
107
|
-
|
|
108
|
-
3. Build and deploy the apps by running the following command at the root directory.
|
|
57
|
+
Else if you are using *React v16.8* or greater & *React Router v5*, use below command
|
|
109
58
|
|
|
110
59
|
```bash
|
|
111
|
-
npm install
|
|
60
|
+
npm install @asgardeo/auth-react@1.1.19 react-router-dom@5.3.4 --save
|
|
112
61
|
```
|
|
113
62
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
#### Basic React Sample
|
|
63
|
+
> **Note**
|
|
64
|
+
> 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.
|
|
117
65
|
|
|
118
|
-
|
|
66
|
+
### 2. Import `AuthProvider` and Provide Configuration Parameters
|
|
119
67
|
|
|
120
|
-
|
|
68
|
+
Asgardeo React SDK exposes the `AuthProvider` component, which helps you easily integrate Asgardeo to your application.
|
|
121
69
|
|
|
122
|
-
-
|
|
123
|
-
|
|
70
|
+
First, import the `AuthProvider` component from `@asgardeo/auth-react.` where you applications root component is defined.
|
|
71
|
+
> **Note**
|
|
72
|
+
> Typically the root component of a react app is defined in the index.* file.
|
|
124
73
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
### 1. Installing the Package
|
|
128
|
-
|
|
129
|
-
Install `@asgardeo/auth-react` and `react-router-dom` from the npm registry.
|
|
130
|
-
|
|
131
|
-
```
|
|
132
|
-
npm install @asgardeo/auth-react react-router-dom --save
|
|
74
|
+
```TypeScript
|
|
75
|
+
import { AuthProvider } from "@asgardeo/auth-react";
|
|
133
76
|
```
|
|
77
|
+
Then, wrap your root component with the `AuthProvider`.
|
|
134
78
|
|
|
135
|
-
### 2. Import `AuthProvider`, `useAuthContext` and Provide Configuration Parameters
|
|
136
79
|
|
|
137
80
|
```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";
|
|
81
|
+
import React from "react";
|
|
82
|
+
import { AuthProvider } from "@asgardeo/auth-react";
|
|
142
83
|
|
|
143
|
-
// The config data.
|
|
144
84
|
const config = {
|
|
145
85
|
signInRedirectURL: "https://localhost:3000/sign-in",
|
|
146
86
|
signOutRedirectURL: "https://localhost:3000/dashboard",
|
|
147
|
-
clientID: "
|
|
148
|
-
baseUrl: "https://api.asgardeo.io/t/<org_name>"
|
|
87
|
+
clientID: "<client_ID>",
|
|
88
|
+
baseUrl: "https://api.asgardeo.io/t/<org_name>",
|
|
89
|
+
scope: [ "openid","profile" ]
|
|
149
90
|
};
|
|
150
91
|
|
|
151
|
-
// Encapsulate your components with the `AuthProvider`.
|
|
152
92
|
export const MyApp = (): ReactElement => {
|
|
153
93
|
return (
|
|
154
94
|
<AuthProvider config={ config }>
|
|
155
|
-
<
|
|
95
|
+
<App />
|
|
156
96
|
</AuthProvider>
|
|
157
97
|
)
|
|
158
98
|
}
|
|
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
99
|
```
|
|
178
100
|
|
|
179
|
-
[
|
|
180
|
-
|
|
181
|
-
<!-- ## Browser Compatibility
|
|
101
|
+
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.
|
|
182
102
|
|
|
183
|
-
The SDK supports all major browsers and provides polyfills to support incompatible browsers. If you want the SDK to run on Internet Explorer or any other old browser, you can use the polyfilled script instead of the default one.
|
|
184
103
|
|
|
185
|
-
|
|
104
|
+
## Using APIs
|
|
186
105
|
|
|
187
|
-
|
|
188
|
-
<script src="https://unpkg.com/@asgardeo/auth-spa@0.1.26/dist/polyfilled/asgardeo-spa.production.min.js.js"></script>
|
|
189
|
-
```
|
|
106
|
+
### Best practices when using APIs
|
|
190
107
|
|
|
191
|
-
|
|
192
|
-
You can specify the preferred module type by appending the type to the module name as follows.
|
|
108
|
+
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.
|
|
193
109
|
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
```TypeScript
|
|
197
|
-
import { AsgardeoSPAClient } from "@asgardeo/auth-spa/polyfilled/esm";
|
|
198
|
-
```
|
|
110
|
+
- The only SDK that should be listed in the app dependencies is `@asgardeo/auth-react`.
|
|
111
|
+
- Always import APIs from `@asgardeo/auth-react`.
|
|
199
112
|
|
|
200
|
-
|
|
113
|
+
>**Warning**
|
|
114
|
+
>IDE or Editor auto import may sometimes import certain APIs from `@asgardeo/auth-spa`, change them back manually.
|
|
201
115
|
|
|
116
|
+
<details><summary><strong>Click here for Tips:</strong> Do's When importing a component from Asgardeo React SDK</summary>
|
|
117
|
+
<p>
|
|
118
|
+
|
|
119
|
+
##### DO ✅
|
|
202
120
|
```TypeScript
|
|
203
|
-
import { AsgardeoSPAClient } from "@asgardeo/auth-
|
|
121
|
+
import { AsgardeoSPAClient } from "@asgardeo/auth-react";
|
|
204
122
|
```
|
|
205
123
|
|
|
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.
|
|
221
|
-
|
|
222
|
-
As an optional parameter, `plugin` parameter can be used to pass an external plugin.
|
|
223
|
-
|
|
224
|
-
The `AuthProvider` also automatically requests for the access token should the URL contain the `code` query parameter.
|
|
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
|
|
124
|
+
#### When including React SDK as a dependency:
|
|
229
125
|
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
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";
|
|
126
|
+
##### DO ✅
|
|
127
|
+
```json
|
|
128
|
+
// In package.json
|
|
244
129
|
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
<AuthProvider config={ config } plugin={ TokenExchangePlugin.getInstance() }>
|
|
248
|
-
<Dashboard />
|
|
249
|
-
</AuthProvider>
|
|
250
|
-
)
|
|
130
|
+
dependencies: {
|
|
131
|
+
"@asgardeo/auth-react": "1.1.18"
|
|
251
132
|
}
|
|
252
133
|
```
|
|
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
|
-
```
|
|
134
|
+
</p>
|
|
135
|
+
</details>
|
|
327
136
|
|
|
328
137
|
---
|
|
138
|
+
### `useAuthContext()` hook
|
|
329
139
|
|
|
330
|
-
|
|
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
|
|
140
|
+
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.
|
|
350
141
|
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
#### Example
|
|
356
|
-
|
|
357
|
-
```TypeScript
|
|
358
|
-
signIn();
|
|
142
|
+
Import the `useAuthContext()` hook from `@asgardeo/auth-react`.
|
|
143
|
+
```Typescript
|
|
144
|
+
import { useAuthContext } from "@asgardeo/auth-react";
|
|
359
145
|
```
|
|
360
|
-
---
|
|
361
|
-
### trySignInSilently
|
|
362
146
|
|
|
363
|
-
|
|
364
|
-
|
|
147
|
+
And then inside your components, you can access the context as follows
|
|
148
|
+
```Typescript
|
|
149
|
+
const { state, signIn, signOut } = useAuthContext();
|
|
365
150
|
```
|
|
366
151
|
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
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.***
|
|
152
|
+
Few common methods that you will require when implementing authentication capabilities in your application.
|
|
153
|
+
- [`signIn`](API.md#signin) - Initiate a login request to Asgardeo, process the response to obtain authentication response.
|
|
154
|
+
- [`signOut`](API.md#signout) - Logout the user from Asgardeo and clear any authentication data from the SDK storage.
|
|
155
|
+
- [`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.
|
|
156
|
+
- [`getBasicUserInfo`](API.md#getbasicuserinfo) - Get authenticated user's basic information from the authentication response.
|
|
157
|
+
- [`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.
|
|
158
|
+
- [`getIDToken`](API.md#getidtoken) - Get the `id_token` (JWT) obtained in the authentication response.
|
|
159
|
+
- [`getAccessToken`](API.md#getaccesstoken) - Get the `access_token` obtained in the authentication response.
|
|
160
|
+
- [`refreshAccessToken`](API.md#refreshaccesstoken) - Get the `refresh_token` obtained in the authentication response.
|
|
161
|
+
- [`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.
|
|
381
162
|
|
|
382
|
-
|
|
163
|
+
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.
|
|
383
164
|
|
|
384
|
-
|
|
385
|
-
|
|
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
|
-
```
|
|
165
|
+
>**Note**
|
|
166
|
+
>You can refer to the [detailed API documentation here](/API.md)
|
|
394
167
|
|
|
395
168
|
---
|
|
169
|
+
### Add a Login/Logout Button
|
|
396
170
|
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
signOut();
|
|
171
|
+
You can use the `signIn()` method from `useAuthContext()` to easily implement a **login button**.
|
|
172
|
+
```Typescript
|
|
173
|
+
<button onClick={ () => signIn() }>Login</button>
|
|
401
174
|
```
|
|
402
175
|
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
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>;
|
|
176
|
+
Similarly to the above step, we can use the `signOut()` method from `useAuthContext()` to implement a **logout button**.
|
|
177
|
+
```Typescript
|
|
178
|
+
<button onClick={() => signOut()}>Logout</button>
|
|
421
179
|
```
|
|
180
|
+
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`.
|
|
422
181
|
|
|
423
|
-
|
|
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.
|
|
182
|
+
Clicking on **Logout button** will sign out the user and will be redirected to `signOutRedirectURL` and the `state.isAuthenticated` will be set to `false`.
|
|
437
183
|
|
|
438
|
-
|
|
184
|
+
> **Note**
|
|
185
|
+
> Instead of buttons you can use the `signIn()` & `signOut()` methods from the SDK to implement any preffered user-experience in your application
|
|
439
186
|
|
|
440
|
-
|
|
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
|
-
```
|
|
187
|
+
You can use the `state.isAuthenticated` attribute to check the authenticated status of the user.
|
|
503
188
|
|
|
504
189
|
---
|
|
190
|
+
### Show Authenticated User's Information
|
|
191
|
+
|
|
192
|
+
The following code snippet demonstrates the usage of the `state` object, together with `signIn()` and `signOut()` methods from the context.
|
|
193
|
+
```Typescript
|
|
194
|
+
import React from "react";
|
|
195
|
+
import { useAuthContext } from "@asgardeo/auth-react";
|
|
196
|
+
|
|
197
|
+
function App() {
|
|
198
|
+
|
|
199
|
+
const { state, signIn, signOut } = useAuthContext();
|
|
200
|
+
|
|
201
|
+
return (
|
|
202
|
+
<div className="App">
|
|
203
|
+
{
|
|
204
|
+
state.isAuthenticated
|
|
205
|
+
? (
|
|
206
|
+
<div>
|
|
207
|
+
<ul>
|
|
208
|
+
<li>{state.username}</li>
|
|
209
|
+
</ul>
|
|
210
|
+
|
|
211
|
+
<button onClick={() => signOut()}>Logout</button>
|
|
212
|
+
</div>
|
|
213
|
+
)
|
|
214
|
+
: <button onClick={() => signIn()}>Login</button>
|
|
215
|
+
}
|
|
216
|
+
</div>
|
|
217
|
+
);
|
|
218
|
+
}
|
|
505
219
|
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
```typescript
|
|
509
|
-
requestCustomGrant(config: CustomGranConfig, callback?: (response: BasicUserInfo | HttpResponse<any>) => void): Promise<HttpResponse | BasicUserInfo>;
|
|
510
|
-
```
|
|
511
|
-
|
|
512
|
-
#### Arguments
|
|
513
|
-
|
|
514
|
-
1. config: [`CustomGrantConfig`](#CustomGrantConfig)
|
|
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();
|
|
557
|
-
```
|
|
558
|
-
|
|
559
|
-
#### Description
|
|
560
|
-
|
|
561
|
-
This method revokes the access token and clears the session information from the storage.
|
|
562
|
-
|
|
563
|
-
The `end-user-session` hook is used to fire a callback function after end user session is successful. Check the [on()](#on) section for more information.
|
|
564
|
-
|
|
565
|
-
#### Example
|
|
566
|
-
|
|
567
|
-
```TypeScript
|
|
568
|
-
revokeAccessToken();
|
|
569
|
-
```
|
|
570
|
-
|
|
571
|
-
---
|
|
572
|
-
|
|
573
|
-
### getOIDCServiceEndpoints
|
|
574
|
-
|
|
575
|
-
```TypeScript
|
|
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
|
-
});
|
|
604
|
-
```
|
|
605
|
-
|
|
606
|
-
---
|
|
607
|
-
|
|
608
|
-
### getDecodedIDToken
|
|
609
|
-
|
|
610
|
-
```typescript
|
|
611
|
-
getDecodedIDToken(): Promise<DecodedIDTokenPayload>
|
|
612
|
-
```
|
|
613
|
-
|
|
614
|
-
#### Returns
|
|
615
|
-
|
|
616
|
-
A promise that returns with the [`DecodedIDTokenPayload`](#DecodedIDTokenPayload) object.
|
|
617
|
-
|
|
618
|
-
#### Description
|
|
619
|
-
|
|
620
|
-
This method returns a promise that resolves with the decoded payload of the JWT ID token.
|
|
621
|
-
|
|
622
|
-
#### Example
|
|
623
|
-
|
|
624
|
-
```TypeScript
|
|
625
|
-
getDecodedIDToken().then((idToken) => {
|
|
626
|
-
// console.log(idToken);
|
|
627
|
-
}).error((error) => {
|
|
628
|
-
// console.error(error);
|
|
629
|
-
});
|
|
630
|
-
```
|
|
631
|
-
---
|
|
632
|
-
|
|
633
|
-
### getDecodedIDPIDToken
|
|
634
|
-
|
|
635
|
-
```typescript
|
|
636
|
-
getDecodedIDPIDToken(): Promise<DecodedIDTokenPayload>
|
|
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`.
|
|
743
|
-
|
|
744
|
-
#### Description
|
|
745
|
-
|
|
746
|
-
The `on` method is used to hook callback functions to authentication methods. The method accepts a hook name and a callback function as the only arguments except when the hook name is "custom-grant", in which case the id of the custom grant should be passed as the third argument. The following hooks are available.
|
|
747
|
-
|
|
748
|
-
If you are using TypeScript, you may want to use the `Hooks` enum that consists of the following string literals instead of directly inputting the string value.
|
|
749
|
-
|
|
750
|
-
| Hook | Method to which the callback function is attached | Returned Response |
|
|
751
|
-
| :----------------------- | :------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------- |
|
|
752
|
-
| `"sign-in"` | `signIn()` | The user information. See [getUserInfo()](#getuserinfo)'s return type for more details. |
|
|
753
|
-
| `"sign-out"` | `signOut()` | |
|
|
754
|
-
| `"initialize"` | `initialize()` | A boolean value indicating if the initialization was successful or not. |
|
|
755
|
-
| `"http-request-start"` | `httpRequest()` (Called before an http request is sent) |
|
|
756
|
-
| `"http-request-finish"` | `httpRequest()` (Called after an http request is sent and response is received.) |
|
|
757
|
-
| `"http-request-error"` | `httpRequest()` (Called when an http request returns an error) |
|
|
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
|
|
812
|
-
|
|
813
|
-
```TypeScript
|
|
814
|
-
enableHttpHandler();
|
|
220
|
+
export default App;
|
|
815
221
|
```
|
|
816
|
-
|
|
817
222
|
---
|
|
223
|
+
### Add Routing
|
|
818
224
|
|
|
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
|
-
```
|
|
225
|
+
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
226
|
|
|
863
227
|
---
|
|
228
|
+
### API Documentation
|
|
864
229
|
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
```TypeScript
|
|
868
|
-
getHttpClient(): `HttpClientInstance`
|
|
869
|
-
```
|
|
870
|
-
|
|
871
|
-
#### Returns
|
|
872
|
-
|
|
873
|
-
An `HttpClientInstance`
|
|
230
|
+
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
231
|
|
|
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.|
|
|
232
|
+
## Sample Apps
|
|
233
|
+
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
234
|
|
|
1028
235
|
## Develop
|
|
1029
236
|
|
|
1030
237
|
### Prerequisites
|
|
1031
|
-
|
|
1032
238
|
- `Node.js` (version 10 or above).
|
|
1033
239
|
- `yarn` package manager.
|
|
1034
240
|
|
|
1035
241
|
### Installing Dependencies
|
|
242
|
+
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
243
|
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
```
|
|
244
|
+
```bash
|
|
1040
245
|
yarn build
|
|
1041
246
|
```
|
|
1042
247
|
|
|
1043
248
|
## Contribute
|
|
1044
|
-
|
|
1045
249
|
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
250
|
|
|
1047
251
|
### Reporting issues
|
|
1048
|
-
|
|
1049
252
|
We encourage you to report issues, improvements, and feature requests creating [Github Issues](https://github.com/asgardeo/asgardeo-auth-react-sdk/issues).
|
|
1050
253
|
|
|
1051
254
|
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
255
|
|
|
1053
256
|
## License
|
|
1054
|
-
|
|
1055
257
|
This project is licensed under the Apache License 2.0. See the [LICENSE](LICENSE) file for details.
|