Every app needs authentication and authorization. Logto is an Auth0 alternative designed for modern apps and SaaS products.
In this article, we will go through the steps to quickly build the OAuth2 sign-in experience (user authentication) with Next and Logto.
Prerequisites
- A running Logto instance. Check out the introduction page to get started.
- Basic knowledge of Next.
- A usable OAuth2 account.
Create an application in Logto
In you browser, open a new tab and enter the link of Logto Admin Console.
Once the page is loaded, in the "Get Started" section click the View all
link to open the application framework list page.
Choose your application type
In the opening modal, scroll to the "Traditional web" section or filter all the available " Traditional web" frameworks using the quick filter checkboxes on the left.
Click the "Next.js" framework card to start creating your application.
Enter application name
Enter the application name, e.g., "Bookstore," and click "Create application."
🎉 Ta-da! You just created your first application in Logto. You'll see a congrats page which includes a detailed integration guide. Follow the guide to see what the experience will be in your application.
Integrate Logto SDK
- The sample project is available on our SDK repository.
- The example is based on Next.js Pages Router.
Installation
Install Logto SDK via your favorite package manager:
- npm
- pnpm
- yarn
npm i @logto/next
pnpm add @logto/next
yarn add @logto/next
Integration
Init LogtoClient
Import and initialize LogtoClient:
import LogtoClient from '@logto/next';
export const logtoClient = new LogtoClient({
appId: '<your-application-id>',
appSecret: '<your-app-secret-copied-from-console>',
endpoint: '<your-logto-endpoint>', // E.g. http://localhost:3001
baseUrl: 'http://localhost:3000',
cookieSecret: 'complex_password_at_least_32_characters_long',
cookieSecure: process.env.NODE_ENV === 'production',
});
Configure Redirect URIs
Before we dive into the details, here's a quick overview of the end-user experience. The sign-in process can be simplified as follows:
- Your app invokes the sign-in method.
- The user is redirected to the Logto sign-in page. For native apps, the system browser is opened.
- The user signs in and is redirected back to your app (configured as the redirect URI).
Regarding redirect-based sign-in
- This authentication process follows the OpenID Connect (OIDC) protocol, and Logto enforces strict security measures to protect user sign-in.
- If you have multiple apps, you can use the same identity provider (Logto). Once the user signs in to one app, Logto will automatically complete the sign-in process when the user accesses another app.
To learn more about the rationale and benefits of redirect-based sign-in, see Logto sign-in experience explained.
In the following code snippets, we assume your app is running on http://localhost:3000/
.
Configure redirect URIs
Switch to the application details page of Logto Console. Add a redirect URI http://localhost:3000/api/logto/sign-in-callback
.
Just like signing in, users should be redirected to Logto for signing out of the shared session. Once finished, it would be great to redirect the user back to your website. For example, add http://localhost:3000/
as the post sign-out redirect URI section.
Then click "Save" to save the changes.
Prepare API routes
Prepare API routes to connect with Logto.
Go back to your IDE/editor, use the following code to implement the API routes first:
import { logtoClient } from '../../../libraries/logto';
export default logtoClient.handleAuthRoutes();
This will create 4 routes automatically:
/api/logto/sign-in
: Sign in with Logto./api/logto/sign-in-callback
: Handle sign-in callback./api/logto/sign-out
: Sign out with Logto./api/logto/user
: Check if user is authenticated with Logto, if yes, return user info.
Implement sign-in and sign-out
We have prepared the API routes, now let's implement the sign-in and sign-out buttons in your home page. We need to redirect the user to the sign-in or sign-out route when needed. To help with this, use useSWR
to fetch authentication status from /api/logto/user
.
Check this guide to learn more about useSWR
.
import { type LogtoContext } from '@logto/next';
import useSWR from 'swr';
const Home = () => {
const { data } = useSWR<LogtoContext>('/api/logto/user');
return (
<nav>
{data?.isAuthenticated ? (
<p>
Hello, {data.claims?.sub},
<button
onClick={() => {
window.location.assign('/api/logto/sign-out');
}}
>
Sign Out
</button>
</p>
) : (
<p>
<button
onClick={() => {
window.location.assign('/api/logto/sign-in');
}}
>
Sign In
</button>
</p>
)}
</nav>
);
};
export default Home;
Checkpoint: Test your application
Now, you can test your application:
- Run your application, you will see the sign-in button.
- Click the sign-in button, the SDK will init the sign-in process and redirect you to the Logto sign-in page.
- After you signed in, you will be redirected back to your application and see the sign-out button.
- Click the sign-out button to clear local storage and sign out.
Open your Next app to test if the integration works. When you click the "Sign In" button, the page should be redirected to a Logto sign-in page, and you should be able to create a new account by entering username and password and complete the sign-in process.
Add OAuth2 connector
To add a social connector, go to the "Connector" tab in the Admin Console, then click on "Social connectors". From there, click "Add social connector".
In the openning modal, select "OAuth2" and click "Next".
On the next page, you will see a two-column layout with the README content on the left and configuration on the right.
Feel free to follow the README file in place or read the following section to complete the configuration process. If you follow the in-place guide, you can skip the next section.
Set up Standard OAuth 2.0 app
Create your OAuth 2.0 app
When you open this page, we believe you already know which social identity provider you want to connect to. The first thing to do is to confirm that the identity provider supports the OAuth 2.0 protocol, which is a prerequisite for configuring a valid connector. Then, follow the identity provider's instructions to register and create the relevant app for OAuth 2.0 authorization.
Configure your connector
We ONLY support "Authorization Code" grant type for security consideration and it can perfectly fit Logto's scenario.
clientId
and clientSecret
can be found at your OAuth 2.0 apps details page.
clientId: The client ID is a unique identifier that identifies the client application during registration with the authorization server. This ID is used by the authorization server to verify the identity of the client application and to associate any authorized access tokens with that specific client application.
clientSecret: The client secret is a confidential key that is issued to the client application by the authorization server during registration. The client application uses this secret key to authenticate itself with the authorization server when requesting access tokens. The client secret is considered confidential information and should be kept secure at all times.
scope: The scope parameter is used to specify the set of resources and permissions that the client application is requesting access to. The scope parameter is typically defined as a space-separated list of values that represent specific permissions. For example, a scope value of "read write" might indicate that the client application is requesting read and write access to a user's data.
You are expected to find authorizationEndpoint
, tokenEndpoint
and userInfoEndpoint
in social vendor's documentation.
authenticationEndpoint: This endpoint is used to initiate the authentication process. The authentication process typically involves the user logging in and granting authorization for the client application to access their resources.
tokenEndpoint: This endpoint is used by the client application to obtain an access token that can be used to access the requested resources. The client application typically sends a request to the token endpoint with a grant type and authorization code to receive an access token.
userInfoEndpoint: This endpoint is used by the client application to obtain additional information about the user, such as their fullname, email address or profile picture. The user info endpoint is typically accessed after the client application has obtained an access token from the token endpoint.
Logto also provide a profileMap
field that users can customize the mapping from the social vendors' profiles which are usually not standard. The keys are Logto's standard user profile field names and corresponding values should be social profiles' field names. In current stage, Logto only concern 'id', 'name', 'avatar', 'email' and 'phone' from social profile, only 'id' is required and others are optional fields.
responseType
and grantType
can ONLY be FIXED values with authorization code grant type, so we make them optional and default values will be automatically filled.
For example, you can find Google user profile response and hence its profileMap
should be like:
{
"id": "sub",
"avatar": "picture"
}
ℹ️ Note
We provided an OPTIONAL
customConfig
key to put your customize parameters. Each social identity provider could have their own variant on OAuth 2.0 standard protocol. If your desired social identity provider strictly stick to OAuth 2.0 standard protocol, the you do not need to care aboutcustomConfig
.
Config types
Name | Type | Required |
---|---|---|
authorizationEndpoint | string | true |
userInfoEndpoint | string | true |
clientId | string | true |
clientSecret | string | true |
tokenEndpointResponseType | enum | false |
responseType | string | false |
grantType | string | false |
tokenEndpoint | string | false |
scope | string | false |
customConfig | { [key: string]: string } | false |
profileMap | ProfileMap | false |
ProfileMap fields | Type | Required | Default value |
---|---|---|---|
id | string | false | id |
name | string | false | name |
avatar | string | false | avatar |
string | false | ||
phone | string | false | phone |
Reference
Save your configuration
Double check you have filled out necessary values in the Logto connector configuration area. Click "Save and Done" (or "Save changes") and the OAuth2 connector should be available now.
Enable OAuth2 connector in Sign-in Experience
Switch to the "Sign-in experience" tab, then click the "Sign-up and sign-in" tab.
If it's the first time you enter the tab, you will see a quick introduction about Sign-in Experience and its basic configuration.
Select "None" for the "Sign-up identifier" to provide minimum sign-up effort for OAuth2 sign-in, which may increase your conversion rate.
In the "Social sign-in" section, add "Add Social Connector" and choose "OAuth2". Then you should be able to see a button with text "Continue with OAuth2" in the preview section.
Finally, click "Save changes" on the bottom right corner.
Testing and Validation
Return to your Next app. You should now be able to sign in with OAuth2. Enjoy!
Further readings
Protect your API For native and single page apps, you'll need to call one or more API endpoints to retrieve and update data.
Learn more about identifying who's who and keeping your API secure.
User management We know you care about user management and activities, as we also do.
Learn more about how to know your users and see the figures like DAU and MAU graphically.
Localization From one regional business to a global corporate, the willingness to offer the best user experience won't change.
You can change current language phrases or add a new language without friction.
Customer IAM series Our serial blog posts about Customer (or Consumer) Identity and Access Management, from 101 to advanced topics and beyond.