There are multiple ways in which we can authenticate a user over the web, few of them are: matching user credentials in the database, delegating responsibility to an external OAuth provider etc. We can extend those similar concepts in SvelteKit too and implement authentication.
SvelteKit does not provide out-of-box authentication. We can extend the means that we discussed above and implement authentication in SvelteKit. This guide will focus on implementing authentication in SvelteKit using SvelteKitAuth and OAuth providers. After reading this guide, you'll have a decent understanding of implementing authentication mechanisms in SvelteKit.
SvelteKitAuth is part of the Auth.js project - Authentication for Web which is an open-source library that is easy to use.
SvelteKitAuth is an extension of NextAuth - a popular authentication framework from the Next / React world. NextAuth is now getting a major overhaul and is now becoming Auth.js
It can be used with any OAuth2 or OpenID Connect provider and has built-in support for 68+ popular services like Google, Facebook, Auth0, Apple etc.
Apart from OAuth authentication, it has built-in support for authentication using email/passwordless/magic link/username/password.
We can configure SvelteKitAuth to use database sessions (MySQL, Postgres, MSSQL, MongoDB etc.) or JWT.
Although there are other options available as well, the reason I choose SvelteKitAuth is that it supports OAuth 1.0, 1.0A, 2.0 and OpenID Connect and has built-in support for the most popular sign-in services like Google, GitHub, Auth0, Salesforce etc. It also supports multiple popular database adapters like MySQL, Postgres, MSSQL, MongoDB etc. Apart from that it provides a mechanism to create a custom OAuth provider and custom database adapter as well.
Another reason for going ahead with SvelteKitAuth is it has bigger community support and is backed by Vercel which makes it runtime agnostic, runs anywhere & supports Vercel Edge Functions, Node.js, and Serverless.
To understand how SvelteKitAuth works under the hood, let's explore its internal architecture and the steps involved in the authentication flow.
Configuration: When setting up SvelteKitAuth, you define a configuration file that specifies authentication providers, such as Google, GitHub, or a custom provider. The configuration also includes settings like secret keys, session storage options, and callback URLs.
Authentication Providers: SvelteKitAuth supports multiple authentication providers, and you can choose the ones you want to enable. Each provider has its configuration options, such as client ID, client secret, scopes, and authorization URLs.
Client-Side Flow: When a user initiates the authentication process, SvelteKitAuth handles the flow by redirecting them to the respective authentication provider's login page. This typically involves generating a state and storing it in a server-side session to prevent CSRF attacks.
Callback URL: After successful authentication with the provider, the user is redirected back to a callback URL specified in the SvelteKitAuth configuration. This URL is typically an API route that SvelteKitAuth exposes.
Server-Side Flow: SvelteKitAuth receives the callback request on the specified API route. It validates the received data, including the state parameter, to ensure it matches the stored session state. This step prevents CSRF attacks.
Token Exchange: SvelteKitAuth then exchanges the authorization code received from the authentication provider with an access token. This token allows SvelteKitAuth to make authenticated API requests on behalf of the user.
User Information: With the access token, SvelteKitAuth retrieves the user's profile information from the authentication provider's API. It can fetch details like name, email, profile picture, or any other data that the provider makes available.
Session Management: SvelteKitAuth creates a session for the authenticated user, typically using a secure HTTP-only cookie or a JWT (JSON Web Token). This session contains the user's data and is used for subsequent authenticated requests.
Persistent Sessions: SvelteKitAuth can optionally store session information in a database or other storage mechanisms. This allows users to remain logged in even if the server restarts or the user refreshes the page.
Hooks and Events: SvelteKitAuth provides various hooks and events that you can use to customize the authentication flow, add additional functionality, or integrate with external systems. Examples include the
$page.data.sessionfor accessing the session data in components and event hooks like
signOutfor performing actions on authentication events.
Overall, SvelteKitAuth abstracts away the complexities of authentication and provides a unified API for integrating with multiple authentication providers. It handles the authentication flow, token exchange, and session management, allowing developers to focus on building their applications without getting caught up in the intricacies of authentication protocols.
As I mentioned earlier that this guide will focus on implementing authentication in SvelteKit using SvelteKitAuth and OAuth providers, we must know how OAuth works.
Auth.js has given a detailed explanation on this topic and I will be quoting that from their site as is. Without going into too much detail, the OAuth flow generally has 6 parts:
The application requests authorization to access service resources from the user.
If the user authorized the request, the application receives an authorization grant.
The application requests an access token from the authorization server (API) by presenting authentication of its own identity, and the authorization grant.
If the application identity is authenticated and the authorization grant is valid, the authorization server (API) issues an access token to the application. Authorization is complete.
The application requests the resource from the resource server (API) and presents the access token for authentication.
If the access token is valid, the resource server (API) serves the resource to the application.
For more details, check out Aaron Parecki's blog post - OAuth2 Simplified or Postman's blog post - OAuth 2.0: Implicit Flow is Dead, Try PKCE Instead.
For more details, please read rest of article on my blog