• Stars
    star
    578
  • Rank 77,250 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 3 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Authentication library for use with SvelteKit featuring built-in OAuth providers and zero restriction customization!

SvelteKitAuth Banner

SvelteKitAuth

License: MIT NPM Release NPM Downloads NPM Type Definitions

Authentication library for use with SvelteKit featuring built-in OAuth providers and zero restriction customization!

Installation

SvelteKitAuth is available on NPM as sk-auth, it can be installed with NPM:

npm i sk-auth --save

Or Yarn:

yarn add sk-auth

Usage with Typescript

SvelteKitAuth also comes with first-class support for Typescript out of the box, so no need to add an additional @types/ dev dependency! πŸŽ‰

Getting Started

SvelteKitAuth is very easy to setup! All you need to do is instantiate the SvelteKitAuth class, and configure it with some default providers, as well as a JWT secret key used to verify the cookies:

Warning: env variables prefixed with VITE_ can be exposed and leaked into client-side bundles if they are referenced in any client-side code. Make sure this is not the case, or consider using an alternative method such as loading them via dotenv directly instead.

export const appAuth = new SvelteKitAuth({
  providers: [
    new GoogleOAuthProvider({
      clientId: import.meta.env.VITE_GOOGLE_OAUTH_CLIENT_ID,
      clientSecret: import.meta.env.VITE_GOOGLE_OAUTH_CLIENT_SECRET,
      profile(profile) {
        return { ...profile, provider: "google" };
      },
    }),
  ],
  jwtSecret: import.meta.env.JWT_SECRET_KEY,
});

If you want to override or augment the default SvelteKit session to get access to the user in the session store, you can use the getSession hook:

// overriding the default session
export const { getSession } = appAuth;

// augmenting it
export const getSession: GetSession = async (request) => {
  const { user } = await appAuth.getSession(request);

  return { user };
};

Callbacks

SvelteKitAuth provides some callbacks, similar to NextAuth.js. Their call signatures are:

interface AuthCallbacks {
  signIn?: () => boolean | Promise<boolean>;
  jwt?: (token: JWT, profile?: any) => JWT | Promise<JWT>;
  session?: (token: JWT, session: Session) => Session | Promise<Session>;
  redirect?: (url: string) => string | Promise<string>;
}

Adding more Providers

SvelteKitAuth uses a object-oriented approach towards creating providers. It is unopionated and allows you to implement any three-legged authentication flow such as OAuth, SAML SSO, and even regular credential logins by omitting the signin() route.

You can implement your own using the Provider base provider class, and by implementing the signin() and callback() methods:

export abstract class Provider<T extends ProviderConfig = ProviderConfig> {
  abstract signin<Locals extends Record<string, any> = Record<string, any>, Body = unknown>(
    request: ServerRequest<Locals, Body>,
  ): EndpointOutput | Promise<EndpointOutput>;

  abstract callback<Locals extends Record<string, any> = Record<string, any>, Body = unknown>(
    request: ServerRequest<Locals, Body>,
  ): CallbackResult | Promise<CallbackResult>;
}

signin() must return a generic endpoint output, this can be a redirect, or the path to the provider's sign-in page. When implementing a HTTP POST route, signin() can simply return an empty body and callback() should handle the user login flow.

callback() takes a ServerRequest and must return a CallbackResult which is a custom type exported by svelte-kit-auth:

export type Profile = any;
export type CallbackResult = [Profile, string | null];

The first item in the tuple is the user profile, which gets stored in the token, and is provided to the jwt() callback as the second argument. The second item is a redirect route, which may be tracked using the state query parameter for OAuth providers, or other implementations depending on the sign-in method.

OAuth2

SvelteKitAuth comes with a built-in OAuth2 provider that takes extensive configuration parameters to support almost any common OAuth2 provider which follows the OAuth2 spec. It can be imported from sk-auth/providers and configured with the following configuration object:

export interface OAuth2ProviderConfig<ProfileType = any, TokensType extends OAuth2Tokens = any>
  extends OAuth2BaseProviderConfig<ProfileType, TokensType> {
  accessTokenUrl?: string;
  authorizationUrl?: string;
  profileUrl?: string;
  clientId?: string;
  clientSecret?: string;
  scope: string | string[];
  headers?: any;
  authorizationParams?: any;
  params: any;
  grantType?: string;
  responseType?: string;
  contentType?: "application/json" | "application/x-www-form-urlencoded";
}

Some values have defaults which can be seen below:

const defaultConfig: Partial<OAuth2ProviderConfig> = {
  responseType: "code",
  grantType: "authorization_code",
  contentType: "application/json",
};

The OAuth2Provider class can then be instantiated with the configuration to support the OAuth2 flow, including authorization redirect, token retrieval and profile fetching. It will also automatically handle the state and nonce params for you.

Motivation

SvelteKitAuth is inspired by the NextAuth.js package built for the Next.js SSR framework for React. Unlike NextAuth.js it is completely unopinionated and only provides implementations for default flows, while still empowering users to add their own providers.

As it leverages classes and Typescript, the implementation of such providers is very straightforward, and in the future it will even be possible to register multiple SvelteKitAuth handlers in the same project, should the need arise, by leveraging a class-based client and server setup.

Examples

Looking for help? Check out the example app in the repository source. Make something cool you want to show off? Share it with others in the discussion section.

Contributing

🚧 Work in Progress!

License

This project is licensed under the terms of the MIT license.

More Repositories

1

jolt

The social hub for your media server. Rate, review and recommend movies and shows, as well as manage your watchlist, follow friends and more.
TypeScript
165
star
2

share-me

An image and video hosting platform for your server, with rich embed support and API.
TypeScript
143
star
3

aPRAW

Asynchronous Python Reddit API Wrapper
Python
50
star
4

Fuzzle

Expandable search engine written in Python. Models upcoming!
HTML
15
star
5

Cheeri-No

Say no to those pesky corporate overlords!
TypeScript
13
star
6

go-gqlgen-fx-template

Go GraphQL API template with Uber FX for Dependency Injection and GORM.
Go
11
star
7

Banhacker

Mariavi's take on Reddit moderation.
Python
10
star
8

Banhammer.py

Python framework to create Reddit moderation bots for Discord using reactions and streams.
Python
9
star
9

reddit-comments-crypto-counter

Crypto coin ticker counter for Reddit comments.
Python
8
star
10

Reddify

Reddit verification bot for Discord with useful statistics and an intuitive verification process.
Python
6
star
11

react-video-trimmer

TypeScript
5
star
12

media-hoarder

A simple web app to calculate how many shows and movies can be stored on a given array of storage.
TypeScript
5
star
13

svelte-custom-element-template

Svelte custom elements (WebComponent) template with Prettier and ESLint!
JavaScript
5
star
14

kraken-staking-countdown

Tracking app for Kraken staking rewards and countdown timer.
JavaScript
3
star
15

1000DOP

Bot for /r/1000DaysOfPractice.
Python
2
star
16

Hyperlinkr

Quickly generate hyperlinks for the web as a PWA!
Vue
2
star
17

anti-crypto-scammer

Python
2
star
18

Idealist

Bot for the Idealist Discord server
Python
2
star
19

ReactivePy

Reactive properties and owners for Python classes.
Python
2
star
20

dan6erbond.github.io

Website about me
HTML
2
star
21

SchoolHelper

A tool to provide support for the busy I1A students...
Java
2
star
22

Egosaurus

Script to print/post/save Reddit statistics.
Python
2
star
23

shrinkarr

Shrink your qBittorrent downloads folder by magnitudes.
Python
2
star
24

terraform-kubernetes-shlink

HCL
1
star
25

Seedless

Clear your Reddit comments and use simple rules to specify which ones!
Python
1
star
26

SantasChristmasWish

Bots for the SCW subreddit and its Discord server.
Python
1
star
27

Im17A

Im17A Class Website
TypeScript
1
star
28

terraform-kubernetes-mariadb

HCL
1
star
29

ChatApp

GraphQL based web server and Vue chat app.
JavaScript
1
star
30

CarRanker

Car ranking web app with built-in webscraper to find your perfect car.
TypeScript
1
star
31

RGB

A simple script that takes images, gets the most prominent colors and turns it into a grid/stretch.
Python
1
star
32

terraform-kubernetes-chevereto

HCL
1
star
33

Employee-Manager

Employee Manager to describe the Composite Pattern.
Java
1
star
34

2019-Casino

Casino-Projekt der Gruppe 3 von der IMS Projektwoche 2019.
Java
1
star
35

projects

Project-Page for GH-Pages
TypeScript
1
star
36

CarManagement

Car management system for a luxury car rental garage with VueJS frontend and NodeJS backend.
JavaScript
1
star
37

crypto-wallet-widget

Crypto wallet widget to accept payments in various blockchain coins and tokens.
Svelte
1
star