Nothing Special   »   [go: up one dir, main page]

Skip to main content

Integrate Logto with Nuxt 3

tip
  • The following demonstration is built on Nuxt 3.10.2.
  • The sample project is available in the GitHub repository.
  • Logto Nuxt SDK requires server-side rendering (SSR) to work properly. For single-page applications (SPA), check out our Vue SDK.

Prerequisites

  • A Logto Cloud account or a self-hosted Logto (Check out the ⚡ Get started guide to create one if you don't have).
  • A Logto traditional web application created.

Installation

Install Logto SDK via your favorite package manager:

npm i @logto/nuxt

Integration

Register Logto module

In your Nuxt config file, add the Logto module and configure it:

nuxt.config.ts
export default defineNuxtConfig({
modules: ['@logto/nuxt'],
runtimeConfig: {
logto: {
endpoint: '<your-logto-endpoint>',
appId: '<your-logto-app-id>',
appSecret: '<your-logto-app-secret>',
cookieEncryptionKey: '<a-random-string>',
},
},
// ...other configurations
});

Since these information are sensitive, it's recommended to use environment variables (.env):

.env
NUXT_LOGTO_ENDPOINT="<your-logto-endpoint>"
NUXT_LOGTO_APP_ID="<your-logto-app-id>"
NUXT_LOGTO_APP_SECRET="<your-logto-app-secret>"
NUXT_LOGTO_COOKIE_ENCRYPTION_KEY="<a-random-string>"

See runtime config for more information.

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:

  1. Your app invokes the sign-in method.
  2. The user is redirected to the Logto sign-in page. For native apps, the system browser is opened.
  3. The user signs in and is redirected back to your app (configured as the redirect URI).
Regarding redirect-based sign-in
  1. This authentication process follows the OpenID Connect (OIDC) protocol, and Logto enforces strict security measures to protect user sign-in.
  2. 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.


note

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/callback.

Redirect URI in Logto Console

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.

Handle callback

There's no additional setup needed to handle the callback route. When registering @logto/nuxt module, it will do the following:

  • Add three routes for sign-in (/sign-in), sign-out (/sign-out), and callback (/callback).
  • Import two composables: useLogtoClient and useLogtoUser.

These routes are configurable via logto.pathnames in the module options, for example:

nuxt.config.ts
export default defineNuxtConfig({
logto: {
pathnames: {
signIn: '/login',
signOut: '/logout',
callback: '/auth/callback',
},
},
// ...other configurations
});

Check out the type definition file in the @logto/nuxt package for more information.

note

If you configure the callback route to a different path, you need to update the redirect URI in Logto accordingly.

Implement sign-in and sign-out

Since Nuxt pages will be hydrated and become a single-page application (SPA) after the initial load, we need to redirect the user to the sign-in or sign-out route when needed. To help with this, our SDK provides the useLogtoUser() composable, which can be used in both server and client side.

index.vue
<script setup lang="ts">
import { useLogtoUser } from '#imports'; // Add this line if auto-import is disabled
const user = useLogtoUser();
</script>
<template>
<!-- Simplified button for sign-in and sign-out -->
<nuxt-link :to="`/sign-${ user ? 'out' : 'in' }`"> Sign {{ user ? 'out' : 'in' }} </nuxt-link>
</template>

Checkpoint: Test your application

Now, you can test your application:

  1. Run your application, you will see the sign-in button.
  2. Click the sign-in button, the SDK will init the sign-in process and redirect you to the Logto sign-in page.
  3. After you signed in, you will be redirected back to your application and see the sign-out button.
  4. Click the sign-out button to clear local storage and sign out.

Get user information

Display user information

When user is signed in, the return value of useLogtoUser() will be an object containing the user's information. You can display this information in your app:

index.vue
<script setup lang="ts">
const user = useLogtoUser();
</script>
<template>
<!-- Display user information when signed in -->
<ul v-if="Boolean(user)">
<li v-for="(value, key) in user"><b>{{ key }}:</b> {{ value }}</li>
</ul>
<!-- Simplified button for sign-in and sign-out -->
<nuxt-link :to="`/sign-${ user ? 'out' : 'in' }`"> Sign {{ user ? 'out' : 'in' }} </nuxt-link>
</template>

Request additional claims

You may find some user information are missing in the returned object from useLogtoUser(). This is because OAuth 2.0 and OpenID Connect (OIDC) are designed to follow the principle of least privilege (PoLP), and Logto is built on top of these standards.

By default, limited claims are returned. If you need more information, you can request additional scopes to access more claims.

info

A "claim" is an assertion made about a subject; a "scope" is a group of claims. In the current case, a claim is a piece of information about the user.

Here's a non-normative example the scope - claim relationship:

tip

The "sub" claim means "subject", which is the unique identifier of the user (i.e. user ID).

Logto SDK will always request three scopes: openid, profile, and offline_access.

To request additional scopes, you can configure the logto module options:

nuxt.config.ts
import { UserScope } from '@logto/nuxt';

export default defineNuxtConfig({
logto: {
scopes: [UserScope.Email, UserScope.Phone], // Add more scopes if needed
// ...other configs
},
});

Then you can access the additional claims in the user object:

index.vue
<template>
<div v-if="user">
<p>Name: {{ user.name }}</p>
<p>Email: {{ user.email }}</p>
<p>Phone: {{ user.phone }}</p>
</div>
</template>

Claims that need network requests

To prevent bloating the ID token, some claims require network requests to fetch. For example, the custom_data claim is not included in the user object even if it's requested in the scopes. To access these claims, you can configure the fetchUserInfo option:

nuxt.config.ts
export default defineNuxtConfig({
logto: {
scopes: [UserScope.CustomData],
fetchUserInfo: true,
},
// ...other configurations
});
By configuring fetchUserInfo, the SDK will fetch the user information by requesting to the userinfo endpoint after the user is signed in, and user.custom_data will be available once the request is completed.

Get user information manually

To access all methods provided by the Logto client, you can use the useLogtoClient() composable:

index.vue
const client = useLogtoClient();
warning

Logto client is only available in the server-side. The composable will return undefined in the client-side.

You can use these Logto methods to retrieve user information programmatically:

  • client.getIdTokenClaims(): Get user information by decoding the local ID token. Some claims may not be available.
  • client.fetchUserInfo(): Get user information by sending a request to the userinfo endpoint.

It's important to note that the user information claims that can be retrieved depending on the scopes used by the user during signing-in, and considering performance and data size, the ID token may not contain all user claims, some user claims are only available in the userinfo endpoint (see the related list below).

For example, to manually fetch user information:

index.vue
import { useLogtoClient, useState, callOnce } from '#imports';

const client = useLogtoClient();
const userInfo = useState(null);

// Call once to prevent running from client-side
await callOnce(async () => {
if (!client) {
throw new Error('Logto client is not available');
}

if (!(await client.isAuthenticated())) {
return;
}

try {
userInfo.value = await client.fetchUserInfo();
} catch (error) {
console.error('Failed to get user information:', error);
}
});

Scopes and claims

Logto uses OIDC scopes and claims conventions to define the scopes and claims for retrieving user information from the ID token and OIDC userinfo endpoint. Both of the "scope" and the "claim" are terms from the OAuth 2.0 and OpenID Connect (OIDC) specifications.

Here's the list of supported scopes and the corresponding claims:

openid

Claim nameTypeDescriptionNeeds userinfo?
substringThe unique identifier of the userNo

profile

Claim nameTypeDescriptionNeeds userinfo?
namestringThe full name of the userNo
usernamestringThe username of the userNo
picturestringURL of the End-User's profile picture. This URL MUST refer to an image file (for example, a PNG, JPEG, or GIF image file), rather than to a Web page containing an image. Note that this URL SHOULD specifically reference a profile photo of the End-User suitable for displaying when describing the End-User, rather than an arbitrary photo taken by the End-User.No
created_atnumberTime the End-User was created. The time is represented as the number of milliseconds since the Unix epoch (1970-01-01T00:00:00Z).No
updated_atnumberTime the End-User's information was last updated. The time is represented as the number of milliseconds since the Unix epoch (1970-01-01T00:00:00Z).No

Other standard claims include family_name, given_name, middle_name, nickname, preferred_username, profile, website, gender, birthdate, zoneinfo, and locale will be also included in the profile scope without the need for requesting the userinfo endpoint. A difference compared to the claims above is that these claims will only be returned when their values are not empty, while the claims above will return null if the values are empty.

note

Unlike the standard claims, the created_at and updated_at claims are using milliseconds instead of seconds.

email

Claim nameTypeDescriptionNeeds userinfo?
emailstringThe email address of the userNo
email_verifiedbooleanWhether the email address has been verifiedNo

phone

Claim nameTypeDescriptionNeeds userinfo?
phone_numberstringThe phone number of the userNo
phone_number_verifiedbooleanWhether the phone number has been verifiedNo

address

Please refer to the OpenID Connect Core 1.0 for the details of the address claim.

custom_data

Claim nameTypeDescriptionNeeds userinfo?
custom_dataobjectThe custom data of the userYes

identities

Claim nameTypeDescriptionNeeds userinfo?
identitiesobjectThe linked identities of the userYes
sso_identitiesarrayThe linked SSO identities of the userYes

urn:logto:scope:organizations

Claim nameTypeDescriptionNeeds userinfo?
organizationsstring[]The organization IDs the user belongs toNo
organization_dataobject[]The organization data the user belongs toYes

urn:logto:scope:organization_roles

Claim nameTypeDescriptionNeeds userinfo?
organization_rolesstring[]The organization roles the user belongs to with the format of <organization_id>:<role_name>No

Considering performance and the data size, if "Needs userinfo?" is "Yes", it means the claim will not show up in the ID token, but will be returned in the userinfo endpoint response.

API resources and organizations

We recommend to read 🔐 Role-Based Access Control (RBAC) first to understand the basic concepts of Logto RBAC and how to set up API resources properly.

Configure Logto client

Once you have set up the API resources, you can add them when configuring Logto in your app:

nuxt.config.ts
export default defineNuxtConfig({
logto: {
resources: ['https://shopping.your-app.com/api', 'https://store.your-app.com/api'], // Add API resources
// ...other configs
},
});

Each API resource has its own permissions (scopes).

For example, the https://shopping.your-app.com/api resource has the shopping:read and shopping:write permissions, and the https://store.your-app.com/api resource has the store:read and store:write permissions.

To request these permissions, you can add them when configuring Logto in your app:

nuxt.config.ts
export default defineNuxtConfig({
logto: {
scopes: ['shopping:read', 'shopping:write', 'store:read', 'store:write'],
resources: ['https://shopping.your-app.com/api', 'https://store.your-app.com/api'],
// ...other configs
},
});

You may notice that scopes are defined separately from API resources. This is because Resource Indicators for OAuth 2.0 specifies the final scopes for the request will be the cartesian product of all the scopes at all the target services.

Thus, in the above case, scopes can be simplified from the definition in Logto, both of the API resources can have read and write scopes without the prefix. Then, in the Logto config:

nuxt.config.ts
export default defineNuxtConfig({
logto: {
scopes: ['read', 'write'],
resources: ['https://shopping.your-app.com/api', 'https://store.your-app.com/api'],
// ...other configs
},
});

For every API resource, it will request for both read and write scopes.

note

It is fine to request scopes that are not defined in the API resources. For example, you can request the email scope even if the API resources don't have the email scope available. Unavailable scopes will be safely ignored.

After the successful sign-in, Logto will issue proper scopes to API resources according to the user's roles.

Fetch access token for the API resource

To fetch the access token for a specific API resource, you can use the getAccessToken method:

index.vue
<script setup lang="ts">
// A composable to access Logto client
const client = useLogtoClient();
// Make the token available globally
const accessToken = useState<string | undefined>('access-token');

// Call once in the server side
await callOnce(async () => {
if (!client) {
throw new Error('Logto client is not available');
}

if (!(await client.isAuthenticated())) {
return;
}

try {
accessToken.value = await client.getAccessToken('https://shopping.your-app.com/api');
} catch (error) {
console.error('Failed to get access token', error);
}
});
</script>

This method will return a JWT access token that can be used to access the API resource when the user has related permissions. If the current cached access token has expired, this method will automatically try to use a refresh token to get a new access token.

Fetch organization tokens

If organization is new to you, please read 🏢 Organizations (Multi-tenancy) to get started.

You need to add UserScope.Organizations scope when configuring the Logto client:

nuxt.config.ts
import { UserScope } from '@logto/nuxt';

export default defineNuxtConfig({
logto: {
scopes: [UserScope.Organizations],
// ...other configs
},
});

Once the user is signed in, you can fetch the organization token for the user:

index.vue
const token = await client.getOrganizationToken(organizationId);

Organization API resources

To fetch an access token for an API resource in an organization, you can use the getAccessToken method with both the API resource and organization ID as parameters:

index.vue
const accessToken = await client.getAccessToken(
'https://shopping.your-app.com/api',
organizationId
);

Further readings