Coder Social home page Coder Social logo

ynwd / deno_kv_oauth Goto Github PK

View Code? Open in Web Editor NEW

This project forked from denoland/deno_kv_oauth

0.0 0.0 0.0 332 KB

High-level OAuth 2.0 powered by Deno KV.

Home Page: https://deno.land/x/deno_kv_oauth

License: MIT License

TypeScript 100.00%

deno_kv_oauth's Introduction

Deno KV OAuth logo

High-level OAuth 2.0 powered by Deno KV.

Docs CI codecov

Deno KV OAuth (Beta)

Features

Documentation

Check out the full documentation and API reference here.

How-to

Get Started with a Pre-Defined OAuth Configuration

See here for the list of OAuth providers with pre-defined configurations.

  1. Create your OAuth application for your given provider.

  2. Create your web server using Deno KV OAuth's request handlers, helpers and pre-defined OAuth configuration.

    // server.ts
    import {
      createGitHubOAuthConfig,
      getSessionId,
      handleCallback,
      signIn,
      signOut,
    } from "https://deno.land/x/deno_kv_oauth@$VERSION/mod.ts";
    
    const oauthConfig = createGitHubOAuthConfig();
    
    async function handler(request: Request) {
      const { pathname } = new URL(request.url);
      switch (pathname) {
        case "/oauth/signin":
          return await signIn(request, oauthConfig);
        case "/oauth/callback":
          const { response } = await handleCallback(request, oauthConfig);
          return response;
        case "/oauth/signout":
          return await signOut(request);
        case "/protected-route":
          return await getSessionId(request) === undefined
            ? new Response("Unauthorized", { status: 401 })
            : new Response("You are allowed");
        default:
          return new Response(null, { status: 404 });
      }
    }
    
    Deno.serve(handler);
  3. 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 which runs https://kv-oauth.deno.dev.

Get Started with a Custom OAuth Configuration

  1. Create your OAuth application for your given provider.

  2. Create your web server using Deno KV OAuth's request handlers and helpers, and custom OAuth configuration.

    // server.ts
    import {
      getRequiredEnv,
      getSessionId,
      handleCallback,
      type OAuth2ClientConfig,
      signIn,
      signOut,
    } from "https://deno.land/x/deno_kv_oauth@$VERSION/mod.ts";
    
    const oauthConfig: OAuth2ClientConfig = {
      clientId: getRequiredEnv("CUSTOM_CLIENT_ID"),
      clientSecret: getRequiredEnv("CUSTOM_CLIENT_SECRET"),
      authorizationEndpointUri: "https://custom.com/oauth/authorize",
      tokenUri: "https://custom.com/oauth/token",
      redirectUri: "https://my-site.com/another-dir/callback",
    };
    
    async function handler(request: Request) {
      const { pathname } = new URL(request.url);
      switch (pathname) {
        case "/oauth/signin":
          return await signIn(request, oauthConfig);
        case "/another-dir/callback":
          const { response } = await handleCallback(request, oauthConfig);
          return response;
        case "/oauth/signout":
          return await signOut(request);
        case "/protected-route":
          return await getSessionId(request) === undefined
            ? new Response("Unauthorized", { status: 401 })
            : new Response("You are allowed");
        default:
          return new Response(null, { status: 404 });
      }
    }
    
    Deno.serve(handler);
  3. Start your server with the necessary environment variables.

    CUSTOM_CLIENT_ID=xxx CUSTOM_CLIENT_SECRET=xxx deno run --unstable --allow-env --allow-net server.ts

Get Started with Cookie Options

This is required for OAuth solutions that span more than one sub-domain.

  1. Create your OAuth application for your given provider.

  2. Create your web server using Deno KV OAuth's helpers factory function with cookie options defined.

    // server.ts
    import {
      createGitHubOAuthConfig,
      createHelpers,
    } from "https://deno.land/x/deno_kv_oauth@$VERSION/mod.ts";
    
    const {
      signIn,
      handleCallback,
      signOut,
      getSessionId,
    } = createHelpers(createGitHubOAuthConfig(), {
      cookieOptions: {
        name: "__Secure-triple-choc",
        domain: "news.site",
      },
    });
    
    async function handler(request: Request) {
      const { pathname } = new URL(request.url);
      switch (pathname) {
        case "/oauth/signin":
          return await signIn(request);
        case "/oauth/callback":
          const { response } = await handleCallback(request);
          return response;
        case "/oauth/signout":
          return await signOut(request);
        case "/protected-route":
          return await getSessionId(request) === undefined
            ? new Response("Unauthorized", { status: 401 })
            : new Response("You are allowed");
        default:
          return new Response(null, { status: 404 });
      }
    }
    
    Deno.serve(handler);
  3. 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

Get Started with Fresh

  1. Create your OAuth application for your given provider.

  2. Create your OAuth configuration and Fresh plugin.

    // plugins/kv_oauth.ts
    import {
      createGitHubOAuthConfig,
      createHelpers,
    } from "https://deno.land/x/deno_kv_oauth@$VERSION/mod.ts";
    import type { Plugin } from "$fresh/server.ts";
    
    const { signIn, handleCallback, signOut, getSessionId } = createHelpers(
      createGitHubOAuthConfig(),
    );
    
    export default {
      name: "kv-oauth",
      routes: [
        {
          path: "/signin",
          async handler(req) {
            return await signIn(req);
          },
        },
        {
          path: "/callback",
          async handler(req) {
            // Return object also includes `accessToken` and `sessionId` properties.
            const { response } = await handleCallback(req);
            return response;
          },
        },
        {
          path: "/signout",
          async handler(req) {
            return await signOut(req);
          },
        },
        {
          path: "/protected",
          async handler(req) {
            return await getSessionId(req) === undefined
              ? new Response("Unauthorized", { status: 401 })
              : new Response("You are allowed");
          },
        },
      ],
    } as Plugin;
  3. Add the plugin to your Fresh app.

  4. Start your Fresh server with the necessary environment variables.

    GITHUB_CLIENT_ID=xxx GITHUB_CLIENT_SECRET=xxx deno task start

Run the Demo Locally

The demo uses GitHub as the OAuth provider. You can change the OAuth configuration by setting the oauthConfig constant as mentioned above.

  1. Create your OAuth application for your given provider.

  2. Start the demo with the necessary environment variables.

    TWITTER_CLIENT_ID=xxx TWITTER_CLIENT_SECRET=xxx deno task demo

Concepts

Redirects after Sign-In and 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 in 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.

Pre-Defined OAuth Configurations

Providers

The following providers have pre-defined OAuth configurations:

  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

Environment Variables

These must be set when starting a server with a pre-defined OAuth configuration. Replace the PROVIDER prefix with your given OAuth provider's name when starting your server. E.g. DISCORD, GOOGLE, or SLACK.

  1. PROVIDER_CLIENT_ID - Client ID of a given OAuth application.
  2. PROVIDER_CLIENT_SECRET - Client secret of a given OAuth application.
  3. PROVIDER_DOMAIN (optional) - Server domain of a given OAuth application. Only required for Okta and Auth0.

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

Built with Deno KV OAuth

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

Do you have a project powered by Deno KV OAuth that you'd like to share? Feel free to let us know in a new issue.

Known Issues

  • Twitch is not supported as an OAuth provider because it does not support PKCE. See #79 and this post for more information.

deno_kv_oauth's People

Contributors

iuioiua avatar github-actions[bot] avatar lino-levan avatar j3lte avatar mbhrznr avatar mitchwadair avatar adoublef avatar kt3k avatar brettchalupa avatar cirolosapio avatar jabolol avatar jollytoad avatar notangelmario avatar zachauten avatar dependabot[bot] avatar ntns avatar ynm3n avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.