SvelteKit-Armor Svelte Themes

Sveltekit Armor

Minimal config OAuth 2.0/OIDC protection for SvelteKit

SvelteKit Armor

[!IMPORTANT] The library is being tested in production and will be tagged 1.0.0 once I'm confident it works.

Highly opinionated, minimal config OAuth protection for SvelteKit apps. Get login working in few lines of code - no complex setup, no custom UI, just secure authentication using your own OAuth 2.0/OIDC IdP hosted UI, such as AWS Cognito or auth0.

Installation

Install with your favorite package manager:

npm install --save @nekm/sveltekit-armor @sveltejs/kit

Usage

Create a src/hooks.server.ts and write:

import { armor, armorCookieSession } from '@nekm/sveltekit-armor';

export const handle = armor({
    oauth: {
        clientId: 'foo',
        clientSecret: 'bar',
        baseUrl: 'https://myapp.auth.eu-west-1.amazoncognito.com',
        issuer: 'https://cognito-idp.eu-west-1.amazonaws.com/eu-west-1_ABC123xyz',
    },
    session: armorCookieSession,
});

Done. Entire app now requires login.

Access the tokens:

import {armorCookieSessionGet} from '@nekm/sveltekit-armor';

const tokens = armorCookieSessionGet(event.cookies);

For simplicity, we provide you with a default cookie session, but it is recommended to write your own session storage to store tokens in your database.

Routes

Your app will now expose these routes:

  • /_armor/login - Redirect the user here to initiate a login.
  • /_armor/redirect/login - Configure your IdP to redirect here.
  • /_armor/logout - Only if logout endpoint is configured.
  • /_armor/redirect/logout - Only if logout endpoint is configured.

Examples

Protect only certain routes

Assume you only want to protect routes prefixed by admin. Create a src/hooks.server.ts and write:

import { armor } from '@nekm/sveltekit-armor';

const protect = armor({ /* config */ });

export const handle = ({ event, resolve }) => {
    if (event.url.pathname.startsWith('/admin')) {
        return protect({ event, resolve });
    }

    return resolve(event);
}

Versioning

This project complies with Semantic Versioning.

Changelog

For a complete list of changes, and how to migrate between major versions, see releases page.

Buy me a coffee

If you appreciate my work, then consider buying me a coffee. Donations are completely voluntary.

Top categories

Loading Svelte Themes