• Stars
    star
    245
  • Rank 165,304 (Top 4 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 1 year ago
  • Updated 7 months ago

Reviews

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

Repository Details

High-level OAuth 2.0 powered by Deno KV.
Deno KV OAuth logo

High-level OAuth 2.0 powered by Deno KV.

Docs CI codecov

Deno KV OAuth (Beta)

Features

Live Demo

You can also check out a live demo at https://kv-oauth.deno.dev, which uses Github as the OAuth 2.0 provider. Source code is located in demo.ts.

Usage

Check out the full documentation and API reference here.

Getting Started with Fresh

Note: The minimum required version for plugins in Fresh is 1.3.0

If you're not performing anything special in the sign-in, sign-out and callback handlers, you can add the Fresh plugin to your project. This automatically handles GET /oauth/signin, GET /oauth/callback and GET /oauth/signout routes.

  1. Create your OAuth 2.0 application for your given provider.

  2. Create your pre-configured or custom OAuth 2.0 client instance and configure Fresh to use the plugin.

    // main.ts
    import { start } from "$fresh/server.ts";
    import { createGitHubOAuth2Client } from "https://deno.land/x/deno_kv_oauth@$VERSION/mod.ts";
    import { kvOAuthPlugin } from "https://deno.land/x/deno_kv_oauth@$VERSION/fresh.ts";
    import manifest from "./fresh.gen.ts";
    
    await start(manifest, {
      plugins: [
        kvOAuthPlugin(createGitHubOAuth2Client()),
      ],
    });

If you require more advanced setups, you can create your own plugin. For more information, see:

Getting Started with Other Frameworks

This example uses GitHub as the OAuth 2.0 provider. However, you can use any provider you like.

  1. Create your OAuth 2.0 application for your given provider.

  2. Create your pre-configured or custom OAuth 2.0 client instance.

    // Pre-configured OAuth 2.0 client
    import { createGitHubOAuth2Client } from "https://deno.land/x/deno_kv_oauth@$VERSION/mod.ts";
    
    const oauth2Client = createGitHubOAuth2Client();
  3. Using the OAuth 2.0 client instance, insert the authentication flow functions into your authentication routes.

    // Sign-in, callback and sign-out handlers
    import {
      createGitHubOAuth2Client,
      handleCallback,
      signIn,
      signOut,
    } from "https://deno.land/x/deno_kv_oauth@$VERSION/mod.ts";
    
    const oauth2Client = createGitHubOAuth2Client();
    
    async function handleSignIn(request: Request) {
      return await signIn(request, oauth2Client);
    }
    
    async function handleOAuth2Callback(request: Request) {
      return await handleCallback(request, oauth2Client);
    }
    
    async function handleSignOut(request: Request) {
      return await signOut(request);
    }
  4. Use Deno KV OAuth's helper functions where needed.

    // Protected route
    import {
      createGitHubOAuth2Client,
      getSessionAccessToken,
      getSessionId,
    } from "https://deno.land/x/deno_kv_oauth@$VERSION/mod.ts";
    
    const oauth2Client = createGitHubOAuth2Client();
    
    async function getGitHubUser(accessToken: string): Promise<any> {
      const response = await fetch("https://api.github.com/user", {
        headers: { authorization: `Bearer ${accessToken}` },
      });
      if (!response.ok) {
        const { message } = await response.json();
        throw new Error(message);
      }
      return await response.json();
    }
    
    async function handleAccountPage(request: Request) {
      const sessionId = getSessionId(request);
      const hasSessionIdCookie = sessionId !== undefined;
    
      if (!hasSessionIdCookie) return new Response(null, { status: 404 });
    
      const accessToken = await getSessionAccessToken(oauth2Client, sessionId);
      if (accessToken === null) return new Response(null, { status: 400 });
    
      try {
        const githubUser = await getGitHubUser(accessToken);
        return Response.json(githubUser);
      } catch (error) {
        console.error(error);
        return Response.error();
      }
    }
  5. Start your server with the necessary environment variables.

    GITHUB_CLIENT_ID=xxx GITHUB_CLIENT_SECRET=xxx deno run --unstable --allow-env --allow-net server.ts

Check out a full implementation in the demo source code.

  1. When needed, you can delete all KV-stored OAuth 2.0 sessions and tokens.

    import { clearOAuthSessionsAndTokens } from "https://deno.land/x/deno_kv_oauth@$VERSION/mod.ts";
    
    await clearOAuthSessionsAndTokens();

Pre-configured OAuth 2.0 Clients

This module comes with a suite of pre-configured OAuth 2.0 clients for the following providers:

  1. Auth0
  2. Discord
  3. Dropbox
  4. Facebook
  5. GitHub
  6. GitLab
  7. Google
  8. Notion
  9. Okta
  10. Patreon
  11. Slack
  12. Spotify
  13. Twitter

Each function is typed so that their respective platform's requirements are met.

If there's a pre-configured OAuth 2.0 client for a provider you'd like added, please submit a pull request or create a new issue.

Custom OAuth 2.0 Client

If you require custom OAuth 2.0 configuration, you must define your client using new OAuth2Client() from the oauth2_client module. E.g.:

import { OAuth2Client } from "https://deno.land/x/oauth2_client/mod.ts";

const client = new OAuth2Client({
  clientId: Deno.env.get("CUSTOM_CLIENT_ID")!,
  clientSecret: Deno.env.get("CUSTOM_CLIENT_SECRET")!,
  authorizationEndpointUri: "https://custom.com/oauth/authorize",
  tokenUri: "https://custom.com/oauth/token",
  redirectUri: "https://my-site.com",
});

Environment Variables

  • KV_PATH (optional) - defines the path that Deno KV uses. See the API reference for further details.
  • ${PROVIDER}_CLIENT_ID and ${PROVIDER}_CLIENT_SECRET - required when creating a pre-configured OAuth 2.0 client for a given provider. E.g. for Twitter, the environment variable keys are TWITTER_CLIENT_ID and TWITTER_CLIENT_SECRET. See the list below for specifics.
  • OKTA_DOMAIN or AUTH0_DOMAIN - required only when using the Okta or Auth0 provider to supply your own given domain.

Note: reading environment variables requires the --allow-env[=<VARIABLE_NAME>...] permission flag. See the manual for further details.

Running the Demo

Run deno task demo to start the demo application. The task uses environment variables defined in a .env file at the root of this folder.

By default, the demo uses GitHub with a minimal scope. Use the PROVIDER and SCOPE environment variables, if you'd like to change this behavior. E.g. for Twitter:

PROVIDER=Twitter SCOPE=users.read deno task demo

Redirect URL after Sign-In or Sign-Out

The URL that the client is redirected to upon successful sign-in or sign-out is determined by the request made to the sign-in or sign-out endpoint. This value is set by the following order of precedence:

  1. The value of the success_url URL parameter of the request URL, if defined. E.g. a request to http://example.com/signin?success_url=/success redirects the client to /success after successful sign-in.
  2. The value of the Referer header, if of the same origin as the request. E.g. a request to http://example.com/signin with Referer header http://example.com/about redirects the client to http://example.com/about after successful sign-in.
  3. The root path, "/". E.g. a request to http://example.com/signin without the Referer header redirects the client to http://example.com after successful sign-in.

The same applies to user sign-out.

Known Issues

Twitch Incompatibility

This module is incompatible with Twitch as an OAuth 2.0 provider, as the platform doesn't support PKCE. PKCE is a requirement for all OAuth 2.0 providers for this module.

In the Wild

Check out these projects powered by Deno KV OAuth 2.0:

  1. Deno SaaSKit - A modern SaaS template built on Fresh.
  2. KV SketchBook - Dead simple sketchbook app.
  3. Fresh + Deno KV OAuth demo - A demo of Deno KV OAuth working in the Fresh web framework.
  4. Oak + Deno KV OAuth demo - A demo of Deno KV OAuth working in the Oak web framework.
  5. Ultra + Deno KV OAuth demo - A demo of Deno KV OAuth working in the Ultra web framework.
  6. Hono + Deno KV OAuth demo - A demo of Deno KV OAuth working in the Hono web framework.
  7. Cheetah + Deno KV OAuth demo - A demo of Deno KV OAuth working in the Cheetah web framework.
  8. Paquet - A web app shop

Do you have a project powered by Deno KV OAuth 2.0 that you'd like to share? Please submit a pull request adding that project to this list.

More Repositories

1

deno

A modern runtime for JavaScript and TypeScript.
Rust
93,907
star
2

fresh

The next-gen web framework.
TypeScript
12,234
star
3

rusty_v8

Rust bindings for the V8 JavaScript engine
Rust
3,094
star
4

deno_std

Deno standard library
TypeScript
2,705
star
5

deno_lint

Blazing fast linter for JavaScript and TypeScript written in Rust
Rust
1,514
star
6

vscode_deno

Visual Studio Code plugin for Deno
TypeScript
1,468
star
7

dnt

Deno to npm package build tool.
Rust
1,211
star
8

saaskit

A modern SaaS template built on Fresh.
TypeScript
1,195
star
9

dotland

[Archived] deno.land website
TypeScript
958
star
10

deno_install

Deno Binary Installer
PowerShell
945
star
11

deno_docker

Latest dockerfiles and images for Deno - alpine, centos, debian, ubuntu
Dockerfile
876
star
12

fastwebsockets

A fast RFC6455 WebSocket implementation
Rust
837
star
13

deno-lambda

A deno runtime for AWS Lambda. Deploy deno via docker, SAM, serverless, or bundle it yourself.
TypeScript
836
star
14

deno_blog

Minimal boilerplate blogging.
TypeScript
459
star
15

denokv

A self-hosted backend for Deno KV
TypeScript
456
star
16

deployctl

Command line tool for Deno Deploy
TypeScript
331
star
17

showcase_chat

TypeScript
302
star
18

roll-your-own-javascript-runtime

Rust
298
star
19

merch

The Deno shop!
TypeScript
283
star
20

deno_bindgen

Write high-level Deno FFI libraries in Rust.
Rust
275
star
21

wasmbuild

Build tool to use Rust code in Deno and the browser.
TypeScript
263
star
22

deno_core

The core engine at the heart of Deno
Rust
262
star
23

deno_doc

Documentation generator for Deno
Rust
251
star
24

setup-deno

Set up your GitHub Actions workflow with a specific version of Deno
JavaScript
248
star
25

meet-me

A calendly clone in Deno and hosted on Deno Deploy
TypeScript
245
star
26

eszip

A compact file format to losslessly serialize an ECMAScript module graph into a single file
Rust
220
star
27

deno-gfm

Server-side GitHub Flavored Markdown rendering for Deno
TypeScript
220
star
28

deno_emit

Transpile and bundle JavaScript and TypeScript under Deno and Deno Deploy
TypeScript
217
star
29

webgpu-examples

TypeScript
214
star
30

doc_website

Archived. New version at https://github.com/denoland/docland
TypeScript
195
star
31

manual

Deprecated - find these resources on docs.deno.com instead
TypeScript
162
star
32

node_shims

npm packages providing shims for the Deno namespace and other globals. Useful for running Deno-first programs on Node.
TypeScript
149
star
33

deno_ast

Source text parsing, lexing, and AST related functionality for Deno
Rust
148
star
34

denobyexample

[Archived] Deno by example - short examples showcasing how to use Deno. Now the examples have been moved to https://github.com/denoland/deno-docs / https://docs.deno.com/examples
TypeScript
146
star
35

fresh_charts

A server-side-rendered charting library for Fresh
TypeScript
136
star
36

deploy_examples

Examples for Deno Deploy
TypeScript
125
star
37

docland

The documentation generation website for Deno
TypeScript
120
star
38

deno_graph

The module graph logic for Deno CLI
Rust
111
star
39

deno_task_shell

Cross-platform shell for deno task.
Rust
104
star
40

deno_registry2

The backend for the deno.land/x service
TypeScript
92
star
41

showcase_todo

Collaborative todo-list app built with Deno and Fresh
TypeScript
82
star
42

deno_third_party

TypeScript
78
star
43

monch

Inspired by nom, but specifically for strings.
Rust
77
star
44

examples

A simple todo app using Deno and React.
TypeScript
77
star
45

tic-tac-toe

A global, real-time multiplayer TicTacToe game for Deno 🦕
TypeScript
75
star
46

deploy_feedback

For reporting issues with Deno Deploy
74
star
47

deno-astro-adapter

A Deno adapter for running Astro applications on the Deno runtime.
TypeScript
67
star
48

pixelpage

Pixel page is an r/place style shared pixel art canvas 🎨🦕
TypeScript
64
star
49

v8

floating patches for rusty_v8
TypeScript
60
star
50

rust-urlpattern

Rust implementation of the `URLPattern` web API
Rust
58
star
51

docs

Deno documentation, examples and API Reference. Powered by Lume.
TypeScript
57
star
52

fresh-wordpress-themes

https://wp-blog-example.deno.dev/ https://wp-sweets-co.deno.dev/
TypeScript
53
star
53

apiland

The API server for deno.land
TypeScript
52
star
54

deno-astro-template

Template repo for an Astro site, preconfigured to run with Deno and Deno Deploy
Astro
49
star
55

sui

Embed custom RO data into precompiled executables
Rust
47
star
56

wanted_modules

Is there a missing deno module that is preventing you from building something? Let us know here.
46
star
57

cargo_gn

Cargo GN integration
Rust
40
star
58

wasmbuild_example

Example of using wasmbuild.
JavaScript
38
star
59

deno_cache_dir

Deno CLI's module cache
Rust
38
star
60

ga

Utilities for server side processing of Google Analytics in Deno CLI and Deploy
TypeScript
38
star
61

serde_v8

Moved to https://github.com/denoland/deno
Rust
36
star
62

import_map

An implementation of WICG Import Maps specification
Rust
30
star
63

flaky_test

atttribute macro for running a flaky test multiple times
Rust
30
star
64

chromium_build

Deno floats patches to //build here (they will be sent upstream eventually)
Python
29
star
65

fresh-blog-example

An example for building a blog with Fresh.
TypeScript
28
star
66

libffi-rs

Fork of libffi-rs which corrects autotools usage
C
22
star
67

deno_npm

npm registry client and dependency resolver used in the Deno CLI.
Rust
22
star
68

deno-sveltekit-template

A starter template for running SvelteKit on Deno Deploy
JavaScript
22
star
69

chatspace

Real-time, collaborative GPT frontend built with Deno KV
TypeScript
22
star
70

doc_components

A set of components for rendering deno_doc doc nodes
TypeScript
21
star
71

rustls-tokio-stream

AsyncRead/AsyncWrite interface for rustls-on-Tokio
Rust
21
star
72

subhosting_ide_starter

Basic starter app for a browser-based IDE using the Deno Subhosting API
JavaScript
21
star
73

deno-vue-example

An example of using Vue with Deno.
Vue
20
star
74

terraform-deploy-provider

Terraform provider for Deno Deploy
Go
20
star
75

deploy_lume_example

An example demonstrating using static site generators on Deno Deploy
TypeScript
20
star
76

monaco-nextjs-demo

A demo Next.js app that features an in-browser IDE built with Monaco.
JavaScript
20
star
77

image-resizing-api

A simple image resizing API written in Deno.
TypeScript
19
star
78

kv_api

WORK IN PROGRESS: Attach a flexible REST API to your Deno web app to manage data in Deno KV
TypeScript
19
star
79

deno-kv-hackathon

Rules, details, and place to submit your project for the Deno KV hackathon.
18
star
80

automation

Automation scripts used for denoland org repos
TypeScript
17
star
81

react18-with-deno

A starter app and tutorial with React18 and Deno.
TypeScript
17
star
82

chromium_buildtools

forked from chromium to use git submodules instead of gclient
Python
17
star
83

benchmark_data

TypeScript
16
star
84

terraform-provider-deno

Terraform provider for hosted Deno APIs
Go
15
star
85

deno-nuxt-template

A template repo for a Nuxt project preconfigured for Deno Deploy
TypeScript
14
star
86

fresh-deno-kv-oauth-demo

Fresh + Deno KV OAuth demo
TypeScript
14
star
87

x-to-jsr

TypeScript
14
star
88

serverless-coldstart-benchmarks

Configuration, benchmarking scripts, and raw data for serverless cold start benchmarks.
Jupyter Notebook
14
star
89

icu

For floating patches on top of https://chromium.googlesource.com/chromium/deps/icu.git
C++
12
star
90

fresh_template

template repository for a Fresh project
12
star
91

deno-vite-plugin

Vite plugin to enable Deno resolution inside vite.
TypeScript
12
star
92

experimental-deno-specifiers-example

TypeScript
12
star
93

deno_lockfile

Rust
12
star
94

fresh-auth-example

TypeScript
11
star
95

deno_config

Rust
11
star
96

deno_media_type

Media type used in Deno.
Rust
11
star
97

notebook

TypeScript
10
star
98

nextgen-install

HCL
10
star
99

v8_valueserializer

A Rust implementation of V8's ValueSerializer and ValueDeserializer
Rust
10
star
100

website_feedback

For reporting issues & suggestions for deno.com and deno.land
9
star