React: Integrate @logto/react
This tutorial assumes you have created an Application of type "Single Page App" in Admin Console. If you are not ready, read this before continuing.
Add Logto SDK as a dependencyโ
- npm
- Yarn
- pnpm
npm i @logto/react
yarn add @logto/react
pnpm add @logto/react
Init LogtoClientโ
Import and use LogtoProvider
to provide a Logto context:
import { LogtoProvider, LogtoConfig } from '@logto/react';
const config: LogtoConfig = {
endpoint: '<your-logto-endpoint>', // E.g. http://localhost:3001
appId: '<your-application-id>',
};
const App = () => (
<LogtoProvider config={config}>
<YourAppContent />
</LogtoProvider>
);
In the following code snippets, we assume your app is running on http://localhost:3000
.
Sign inโ
The sign-in flow can be simplified as:
Configure Redirect URIโ
Let's switch to the Application details page of Admin Console in this section. Add a Redirect URI http://localhost:3000/callback
and click "Save Changes".
Redirect URI is an OAuth 2.0 concept which implies the location should redirect after authentication.
Implement a sign-in buttonโ
We provide two hooks useHandleSignInCallback()
and useLogto()
which can help you easily manage the authentication flow.
Before calling .signIn()
, make sure you have correctly configured Redirect URI in Admin Console.
Go back to your IDE/editor, use the following code to implement the sign-in button:
import { useLogto } from '@logto/react';
const SignIn = () => {
const { signIn, isAuthenticated } = useLogto();
if (isAuthenticated) {
return <div>Signed in</div>;
}
return <button onClick={() => signIn('http://localhost:3000/callback')}>Sign In</button>;
};
Handle redirectโ
We're almost there! In the last step, we use http://localhost:3000/callback
as the Redirect URI, and now we need to handle it properly.
First let's create a callback component:
import { useHandleSignInCallback } from '@logto/react';
const Callback = () => {
const { isLoading } = useHandleSignInCallback(() => {
// Navigate to root path when finished
});
// When it's working in progress
if (isLoading) {
return <div>Redirecting...</div>;
}
};
Finally insert the code below to create a /callback
route which does NOT require authentication:
// Assuming react-router
<Route path="/callback" element={<Callback />} />
Sign outโ
Calling .signOut()
will clear all the Logto data in memory and localStorage if they exist.
After signing out, it'll be great to redirect your user back to your website. Let's add http://localhost:3000
as one of the Post Sign-out URIs in Admin Console (shows under Redirect URIs), and use the URL as the parameter when calling .signOut()
.
Implement a sign-out buttonโ
const SignOut = () => {
const { signOut } = useLogto();
return <button onClick={() => signOut('http://localhost:3000')}>Sign out</button>;
};
Fetch user informationโ
Logto SDK helps you fetch the user information from the OIDC UserInfo Endpoint.
You can get the user information by calling fetchUserInfo()
after signing in.
The user information response will vary based on the scopes used in the LogtoConfig
while initializing the LogtoClient
; and the following table lists the relations between user information and scopes:
Field Name | Type | Required Scope | Notes |
---|---|---|---|
sub | string | openid | The openid scope is added by default. |
name | string | profile | The profile scope is added by default. |
username | string | profile | The profile scope is added by default. |
picture | string | profile | The profile scope is added by default. |
string | email | ||
email_verified | boolean | email | |
phone_number | string | phone | |
phone_number_verified | boolean | phone | |
custom_data | object | custom_data | |
identities | object | identities |
Backend API authorizationโ
Logto also helps you apply authorization to your backend APIs . Please check our Protect your API see how to integrate Logto with your backend applications.
You can claim an authorization token for a protected API Resource request easily through Logto SDK.
In order to grant an audience restricted authorization token for your request, make sure the requested API Resource is registered in the Logto Admin Console.
Add your API resource indicators to the Logto SDK configs:
import { LogtoProvider, LogtoConfig } from '@logto/react';
const config: LogtoConfig = {
appId: '<your-application-id>',
endpoint: '<your-logto-endpoint>',
resources: ['<your-api-resource>'],
};
const App = () => <LogtoProvider config={config}>{/* Your app content */}</LogtoProvider>;
Claim an authorization token from Logto before making your API request:
const { getAccessToken } = useLogto();
const token = await getAccessToken('<your-target-api-resource>');
// custom logic
With the user's authorization status, a JWT format access_token
will be granted and issued by Logto, specifically for the requested API resource. Encrypted and audience-restricted with an expiration time. The token carries all the necessary info to represent the authority of this request.
Put the token in the Authorization
field of HTTP headers with the Bearer format (Bearer YOUR_TOKEN
), and you are good to go.
The Bearer Token's integration flow may vary based on the framework or requester you are using. Choose your own way to apply the request Authorization
header.