Coder Social home page Coder Social logo

dan6erbond / sk-auth Goto Github PK

View Code? Open in Web Editor NEW
576.0 11.0 70.0 257 KB

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

License: MIT License

JavaScript 6.26% TypeScript 48.77% HTML 0.39% CSS 1.42% Svelte 43.16%
svelte sveltejs sveltekit auth oauth

sk-auth's Introduction

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.

sk-auth's People

Contributors

alexstaroselsky avatar dan6erbond avatar landongn avatar leovoon avatar lulzneko avatar odonno avatar ohmree avatar scott-fischer avatar vhscom avatar x-ror avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sk-auth's Issues

[ENHANCEMENT] Production Build for Use with Vite

Overview

The current Typescript build results in issues with Vite, see #7 as the bundle uses ES6 import syntax and setting the package.json type to module causes the Must use import to load ES Module error to be thrown.

Using a bundler like microbundle, which generates CJS, UMD and ESM outputs, will hopefully mitigate the issues and allow SvelteKitAuth to be installed in SvelteKit projects with ease.

Potential secret key exposure

Hey! Nice work on this library.

I noticed that in a few places you're prefixing secret keys with 'VITE_'. These variables can end up in your client bundle and shouldn't contain any sensitive information.

I'm happy to open a pull request to fix this if you'd like.

Thanks!

Getting Started

Love what you have going here! I was contemplating writing something along these lines since I am trying to use SK with an external API that conditionally uses OAuth2 (based on an initial request-response). Because of the SSR nature of SK and using hooks.js doesn't seem like the right way to do things for external APIs.

I realize you are still getting this up and running, but do you have a sample svelte.config.js for this?

I am getting issues with @sveltejs/adapter-static and vite complaining that it cannot resolve the package.

Here is what I have:

/** @type {import('@sveltejs/kit').Config} */

import adapter from "@sveltejs/adapter-static";
import * as carbon from "carbon-preprocess-svelte";

const config = {
	preprocess: carbon.presetCarbon(),
	kit: {
		target: '#svelte',
		adapter: adapter(),
		vite: {
			optimizeDeps: { include: ["clipboard-copy"] },
			plugins: [process.env.NODE_ENV === "production" && carbon.optimizeCss()],
			build: {
				rollupOptions: {
					external: [
						"SvelteKitAuth"
					],
				},
			},
		},
	},
};

export default config;

The base Oauth2 callback doesn't account for the user denying access at the provider stage

The callback implementation always assumes that the code query param will always exist and can be fed into getTokens, and tokens in turn will exist and be fed into getUserProfile:

const code = query.get("code");
const redirect = this.getStateValue(query, "redirect");
const tokens = await this.getTokens(code!, this.getCallbackUri(auth, host));
let user = await this.getUserProfile(tokens);

In my particular use case, I implemented login with GitHub, but if I choose to cancel, rather than share my account with the app, I'm redirected to /api/auth/callback/github?error=access_denied&error_description=The+user+has+denied+your+application+access.&error_uri=https%3A%2F%2Fdocs.github.com%2Fapps%2Fmanaging-oauth-apps%2Ftroubleshooting-authorization-request-errors%2F%23access-denied&state=cmVkaXJlY3Q9Lw%3D%3D.

No code param exists, so the callback page 500s. I'm not sure if error and error_description are unique to GitHub, but perhaps we can use them to handle this situation more gracefully?

Refresh tokens to obtain new access tokens

I'm trying to understand how to use the library with short lived access tokens (the google provider). How can I access the refresh_token, and thereby obtain new access_tokens? I need the access token to call googleapi calls, but after an hour it expires, and I need to login again to obtain new tokens.

[BUG] Redirect Callback Doesn't Work

Overview

As per discussion #35 the redirect() callback isn't called when a redirect URL is returned from Provider.callback(). Requires further investigation in the auth flow.

Add possibility to control cookie settings

Unless I am missing something, there is no way to control cookie at the moment. I don't care so much about the cookie name, but I would like to have a control about cookie value/time/path and other options.
(and a big thanks for providing the library ;-) )

Redirected to /api/auth

Hello!

I'm trying to use this package for my SvelteKit app. I'm using @sveltejs/kit 1.0.0-next.132.

I've copied your src/routes/api/auth/[...auth].ts and src/routes/login.svelte files. After clicking "Login with Google" I'm sent to through Googles flow but finally I just end up at /api/auth with a "Not found" message. If I go to /profile nothing is saved in the session.

Any suggestions on how to make this work?
Cheers

Cloudflare Worker adapter builds fail with sk-auth

I have a simple sveltekit app that works with sk-auth locally, and works with the node adapter build, but fails with the logs below when I try to use the Cloudflare worker adapter. I've tried playing around w/ the Vite excludes settings but haven't had any luck yet.

Here's my svelite.config.js

import preprocess from 'svelte-preprocess';
import cloudflare from '@sveltejs/adapter-cloudflare-workers';
// import node from '@sveltejs/adapter-node';

/** @type {import('@sveltejs/kit').Config} */
const config = {
	// Consult https://github.com/sveltejs/svelte-preprocess
	// for more information about preprocessors
	preprocess: [preprocess({
        "postcss": true
    })],

	kit: {
		adapter: cloudflare(),
		// adapter: node(),
		// hydrate the <div id="svelte"> element in src/app.html
		target: '#svelte'
	}
};

export default config;
// Workaround until SvelteKit uses Vite 2.3.8 (and it's confirmed to fix the Tailwind JIT problem)
const mode = process.env.NODE_ENV;
const dev = mode === "development";
process.env.TAILWIND_MODE = dev ? "watch" : "build";

And here's my package.json


{
	"name": "~TODO~",
	"version": "0.0.1",
	"scripts": {
		"dev": "svelte-kit dev",
		"build": "svelte-kit build",
		"preview": "svelte-kit preview",
		"check": "svelte-check --tsconfig ./tsconfig.json",
		"check:watch": "svelte-check --tsconfig ./tsconfig.json --watch",
		"lint": "prettier --check --plugin-search-dir=. . && eslint --ignore-path .gitignore .",
		"format": "prettier --write --plugin-search-dir=. ."
	},
	"devDependencies": {
		"@sveltejs/adapter-cloudflare-workers": "^1.0.0-next.16",
		"@sveltejs/adapter-node": "^1.0.0-next.34",
		"@sveltejs/adapter-static": "^1.0.0-next.13",
		"@sveltejs/kit": "^1.0.0-next.131",
		"@tailwindcss/custom-forms": "^0.2.1",
		"@typescript-eslint/eslint-plugin": "^4.28.3",
		"@typescript-eslint/parser": "^4.28.3",
		"autoprefixer": "^10.3.1",
		"cssnano": "^5.0.6",
		"eslint": "^7.31.0",
		"eslint-config-prettier": "^8.1.0",
		"eslint-plugin-svelte3": "^3.2.0",
		"postcss": "^8.3.5",
		"postcss-load-config": "^3.1.0",
		"prettier": "~2.2.1",
		"prettier-plugin-svelte": "^2.2.0",
		"svelte": "^3.34.0",
		"svelte-check": "^2.2.3",
		"svelte-preprocess": "^4.7.4",
		"tailwindcss": "^2.2.4",
		"tslib": "^2.0.0",
		"typescript": "^4.3.5"
	},
	"type": "module",
	"dependencies": {
		"@tailwindcss/forms": "^0.3.3",
		"@tailwindcss/typography": "^0.4.1",
		"faker": "^5.5.3",
		"sk-auth": "^0.3.7"
	}
}

Error log below:

> Using @sveltejs/adapter-cloudflare-workers
 > node_modules/jws/lib/verify-stream.js:5:21: error: Could not resolve "stream" (use "platform: 'node'" when building for node)
    5 │ var Stream = require('stream');
      ╵                      ~~~~~~~~

 > node_modules/jws/lib/verify-stream.js:7:19: error: Could not resolve "util" (use "platform: 'node'" when building for node)
    7 │ var util = require('util');
      ╵                    ~~~~~~

 > node_modules/jws/lib/sign-stream.js:5:21: error: Could not resolve "stream" (use "platform: 'node'" when building for node)
    5 │ var Stream = require('stream');
      ╵                      ~~~~~~~~

 > node_modules/jws/lib/tostring.js:2:21: error: Could not resolve "buffer" (use "platform: 'node'" when building for node)
    2 │ var Buffer = require('buffer').Buffer;
      ╵                      ~~~~~~~~

 > node_modules/safe-buffer/index.js:3:21: error: Could not resolve "buffer" (use "platform: 'node'" when building for node)
    3 │ var buffer = require('buffer')
      ╵                      ~~~~~~~~

 > node_modules/jws/lib/data-stream.js:3:21: error: Could not resolve "stream" (use "platform: 'node'" when building for node)
    3 │ var Stream = require('stream');
      ╵                      ~~~~~~~~

 > node_modules/jws/lib/sign-stream.js:7:19: error: Could not resolve "util" (use "platform: 'node'" when building for node)
    7 │ var util = require('util');
      ╵                    ~~~~~~

 > node_modules/jwa/index.js:3:21: error: Could not resolve "crypto" (use "platform: 'node'" when building for node)
    3 │ var crypto = require('crypto');
      ╵                      ~~~~~~~~

 > node_modules/jws/lib/data-stream.js:4:19: error: Could not resolve "util" (use "platform: 'node'" when building for node)
    4 │ var util = require('util');
      ╵                    ~~~~~~

 > node_modules/jwa/index.js:5:19: error: Could not resolve "util" (use "platform: 'node'" when building for node)
    5 │ var util = require('util');
      ╵                    ~~~~~~

 > node_modules/buffer-equal-constant-time/index.js:3:21: error: Could not resolve "buffer" (use "platform: 'node'" when building for node)
    3 │ var Buffer = require('buffer').Buffer; // browserify
      ╵                      ~~~~~~~~

> Build failed with 11 errors:
node_modules/buffer-equal-constant-time/index.js:3:21: error: Could not resolve "buffer" (use "platform: 'node'" when building for node)
node_modules/jwa/index.js:3:21: error: Could not resolve "crypto" (use "platform: 'node'" when building for node)
node_modules/jwa/index.js:5:19: error: Could not resolve "util" (use "platform: 'node'" when building for node)
node_modules/jws/lib/data-stream.js:3:21: error: Could not resolve "stream" (use "platform: 'node'" when building for node)
node_modules/jws/lib/data-stream.js:4:19: error: Could not resolve "util" (use "platform: 'node'" when building for node)
...
Error: Build failed with 11 errors:
node_modules/buffer-equal-constant-time/index.js:3:21: error: Could not resolve "buffer" (use "platform: 'node'" when building for node)
node_modules/jwa/index.js:3:21: error: Could not resolve "crypto" (use "platform: 'node'" when building for node)
node_modules/jwa/index.js:5:19: error: Could not resolve "util" (use "platform: 'node'" when building for node)
node_modules/jws/lib/data-stream.js:3:21: error: Could not resolve "stream" (use "platform: 'node'" when building for node)
node_modules/jws/lib/data-stream.js:4:19: error: Could not resolve "util" (use "platform: 'node'" when building for node)
...
    at failureErrorWithLog (/Users/dcaslin/projects/531-calc-2/node_modules/esbuild/lib/main.js:1449:15)
    at /Users/dcaslin/projects/531-calc-2/node_modules/esbuild/lib/main.js:1131:28
    at runOnEndCallbacks (/Users/dcaslin/projects/531-calc-2/node_modules/esbuild/lib/main.js:1049:65)
    at buildResponseToResult (/Users/dcaslin/projects/531-calc-2/node_modules/esbuild/lib/main.js:1129:7)
    at /Users/dcaslin/projects/531-calc-2/node_modules/esbuild/lib/main.js:1236:14
    at /Users/dcaslin/projects/531-calc-2/node_modules/esbuild/lib/main.js:609:9
    at handleIncomingPacket (/Users/dcaslin/projects/531-calc-2/node_modules/esbuild/lib/main.js:706:9)
    at Socket.readFromStdout (/Users/dcaslin/projects/531-calc-2/node_modules/esbuild/lib/main.js:576:7)
    at Socket.emit (events.js:315:20)
    at Socket.EventEmitter.emit (domain.js:467:12)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `svelte-kit build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Issues with peer dependencies found

Dependents using this library face warnings which are erroneous in the context of a development workflow. Here's an example of the warnings generated (outlined with box):

Screen Shot 2022-03-08 at 10 45 18 AM

I believe this can be addressed by adding peerDependenciesMeta and setting "optional": true. Tried peerDependenciesMeta with some success but it's not a complete solution. See note here for investigation.

Allow dev to set SameSite, MaxAge, & Secure attributes on cookie

Relevant line in sk-auth:

"set-cookie": `svelteauthjwt=${jwt}; Path=/; HttpOnly`,

Maybe also relevant? Do JWT and cookie need to be set to the same expiration?

expiresIn: this.config?.jwtExpiresIn ?? "30d",

[HELP] Firebase email auth provider

Is there a way to create a custom provider that signs in with Firebase Auth's email provider?

I dont understand the documentation for custom providers.

Thanks.

Getting Started improvements

Hi, I see a lot of effort has gone into this, but I'm not able to get it to work--the Getting Started assumes too much existing knowledge for me and I'm missing pieces; the example code seems to also be built with older versions of Svelte pieces or I'm missing something, given it's a full repo and hard to know if I've done everything needed.

Can I kindly request Getting Started section to have Steps 1,2,3...; file names and full contents of each file please? I'd love to use this!

Thanks!

[Enhancement] Post Token Callback

I've come across a scenario in which I would like to add additional information to the created token. I see there is a jwt callback, but I don't want to re-implement the cookie logic. It would be great if there was a callback that could manipulate the token just before it is saved to the cookie.

Something like this
image

Thoughts?

Allow setting of "redirect_uri"

sk-auth defaults to https://localhost:3000/api/auth/callback/github with no ability to change it successfully.

Note the s in https.

This is problematic because for localtesting where https isn't used.

signIn callback does not follow NextAuth API and is not called.

I am trying to implement a two step authorization. i.e. use Google/Facebook/name-your-method authentication and then check the associated email is verified and is in a white list database of authorized emails. It is my understanding that this can be done with NextAuth using the signIn call back.

For sk-auth, the documentation states:

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>;
}

NextAuth has the following interface for signIn:

async signIn({ user, account, profile, email, credentials }) {
     const isAllowedToSignIn = true
    if (isAllowedToSignIn) {
      return true
    } else {
      // Return false to display a default error message
      return false
      // Or you can return a URL to redirect to:
      // return '/unauthorized'
    }
}

Even when I put a signIn() call back, it is never called. Looking for all appearances of signIn in the source code gives this:

sk-auth % grep -rn signIn *      
README.md:71:  signIn?: () => boolean | Promise<boolean>;
src/client/index.ts:1:export { signIn } from "./signIn";
src/client/signIn.ts:10:export async function signIn(provider: string, data?: any, config?: SignInConfig) {
src/auth.ts:21:  signIn?: () => boolean | Promise<boolean>;

Thus it seems signIn is never called. Is that an upcoming upgrade, or is there another method to do what I want to do?

Is Twitter provider working?

Tried with Twitter, and it doesn't seems like working?

It gets stuck at a Twitter Error page at https://api.twitter.com/oauth/authorize?oauth_token=undefined.

[ENHANCEMENT] Provider Metainfo

Overview

Add a metainfo callback or data object to providers to retrieve information on expected HTTP POST body format, callback URLs, etc. This is required for the implementation of #2.

[BUG] Session is null on Initial Load, Requires HMR Reload to Fix

Overview

Upon initial load of the app, the session store from $app/stores is null.

TypeError: Cannot read property 'session' of null
    at eval (C:\Users\morav\Documents\Private\Programming\SvelteKitAuth\SvelteKitAuth\app\src\routes\__layout.svelte:19:61)
    at Object.$$render (C:\Users\morav\Documents\Private\Programming\SvelteKitAuth\SvelteKitAuth\app\node_modules\svelte\internal\index.js:1380:22)
    at eval (/C:\Users\morav\Documents\Private\Programming\SvelteKitAuth\SvelteKitAuth\app\.svelte-kit\dev/generated/root.svelte:55:122)
    at $$render (C:\Users\morav\Documents\Private\Programming\SvelteKitAuth\SvelteKitAuth\app\node_modules\svelte\internal\index.js:1380:22)
    at Object.render (C:\Users\morav\Documents\Private\Programming\SvelteKitAuth\SvelteKitAuth\app\node_modules\svelte\internal\index.js:1388:26)
    at render_response (file:///C:/Users/morav/Documents/Private/Programming/SvelteKitAuth/SvelteKitAuth/app/node_modules/@sveltejs/kit/dist/ssr.js:377:28)
    at async respond_with_error (file:///C:/Users/morav/Documents/Private/Programming/SvelteKitAuth/SvelteKitAuth/app/node_modules/@sveltejs/kit/dist/ssr.js:936:10)
    at async respond$1 (file:///C:/Users/morav/Documents/Private/Programming/SvelteKitAuth/SvelteKitAuth/app/node_modules/@sveltejs/kit/dist/ssr.js:1155:10)
    at async render_page (file:///C:/Users/morav/Documents/Private/Programming/SvelteKitAuth/SvelteKitAuth/app/node_modules/@sveltejs/kit/dist/ssr.js:1186:20)
    at async render (file:///C:/Users/morav/Documents/Private/Programming/SvelteKitAuth/SvelteKitAuth/app/node_modules/@sveltejs/kit/dist/ssr.js:1537:10)

This may be an issue in SvelteKit or the way it's used by __layout.svelte. Requires further investigation.

Prod builds with node adapter fail on google auth due to missing fetch

Looks like the oauth2.ts is using native fetch:

const res = await fetch(this.config.accessTokenUrl!, {

From what I've read, this won't work in SSR Sveltekit code, where we'd need to explicitly use node-fetch or pass through the sveltekit supplied "fetch". FWIW this is in sveltekit 1.0.0-next.165

Generated default settings
ReferenceError: fetch is not defined
    at GoogleOAuth2Provider.getTokens (C:\projects\531-calc\node_modules\sk-auth\dist\providers\oauth2.js:49:17)
    at GoogleOAuth2Provider.callback (C:\projects\531-calc\node_modules\sk-auth\dist\providers\oauth2.base.js:37:31)
    at Auth.handleProviderCallback (C:\projects\531-calc\node_modules\sk-auth\dist\auth.js:131:51)
    at Auth.handleEndpoint (C:\projects\531-calc\node_modules\sk-auth\dist\auth.js:180:29)
    at Auth.get (C:\projects\531-calc\node_modules\sk-auth\dist\auth.js:49:25)
    at render_endpoint (file:///C:/projects/531-calc/build/middlewares.js:1098:26)
    at async resolve (file:///C:/projects/531-calc/build/middlewares.js:2243:56)
    at async Object.handle (file:///C:/projects/531-calc/build/middlewares.js:2498:20)
    at async respond (file:///C:/projects/531-calc/build/middlewares.js:2227:12)
    at async Array.<anonymous> (file:///C:/projects/531-calc/build/middlewares.js:4322:22)

[Enhancement] Allows Http protocol configuration

First off, thank you for this library, it works great.
I deployed this to an app I am working on and noticed that although I am running on https, I was being redirected back to http

I've temporarily created a fork to get around this. This is what I have done for now
image

Can't get user session on vercel

After google authentication, I can get a user session, if in a local environment.
However, in the case of a production environment deployed on vercel, it does not return. (Undefined is returned)

Do you know the cause?

Session has been removed

Never-mind below. I see now that the usage of Session isn't baked in, just in the guidance. Not an issue.


I'm trying to use sk-auth in SvelteKit 1.0.0 and noticed that the session store, getSession and event.session from load have all been removed from SvelteKit as of Aug. See the following release notes:

sveltejs/kit#5883

This framework seems to rely heavily on the session store. What will need to be changed or how do I alter my usage of sk-auth to keep using it in SvelteKit versions past the update referenced above?

Missing copyright information in license?

I noticed in the history of this repo some code is copied from Cheeri-No:
d7c4438

And I saw in Cherri-No some code may have been copied from NestJS MikroORM template:
Dan6erbond/Cheeri-No@705a9bb

I found the following repos related to NestJS MikroORM but not any auth code:
https://github.com/mikro-orm/nestjs
Copyright (c) 2019 Dario Mancuso, Martin Adámek

Though I did find at least some parts of the code copied here:
https://github.com/nestjs/nest/blob/99ee3fd99341bcddfa408d1604050a9571b19bc9/sample/19-auth-jwt/src/auth/auth.service.ts
Copyright (c) 2017-2022 Kamil Mysliwiec https://kamilmysliwiec.com

The above use MIT licenses with copyright lines which should be included in the license of this repo if there was code which was copied in. For the sake of completeness, would you mind reviewing the sources of the code in this auth library and adding the necessary copyright lines to the LICENSE file? At current it looks like Kamil's copyright notice should be in there but I'm not sure.

Thank you!

Breaking change in sveltekit

An update has been made to sveltekit (not 100% sure which version it came with) that breaks the library. This is the breaking PR: sveltejs/kit#3384

The error message is event.headers has been replaced by event.request.headers. See https://github.com/sveltejs/kit/pull/3384 for details pointing to this chunk of code:

this.getSession = async ({ headers }) => {
      const token = await this.getToken(headers);
      if (token) {
        if (this.config?.callbacks?.session) {
          return await this.config.callbacks.session(token, { user: token.user });
        }
        return { user: token.user };
      }
      return {};
    };

I believe that instead of { headers } it should be { request }, and then request.headers.

I tried modifying the library to make a PR, but having issues building the library in a way that the app will accept it.

Sample app errors

I am getting the following errors on the sample app:

8:47:01 AM [vite] Error when evaluating SSR module /@fs/D:/Development/svelte/sk-auth/dist/index.js:
ReferenceError: exports is not defined
    at /@fs/D:/Development/svelte/sk-auth/dist/index.js:3:23
    at instantiateModule (D:\Development\svelte\sk-auth\app\node_modules\vite\dist\node\chunks\dep-e9a16784.js:68197:166)
8:47:01 AM [vite] Error when evaluating SSR module /@fs/D:/Development/svelte/sk-auth/dist/providers/index.js:
ReferenceError: exports is not defined
    at /@fs/D:/Development/svelte/sk-auth/dist/providers/index.js:3:23
    at instantiateModule (D:\Development\svelte\sk-auth\app\node_modules\vite\dist\node\chunks\dep-e9a16784.js:68197:166)

This is from a fresh clone of sk-auth and then npm run dev in the app directory.

session.user undefined if all tokens are added to it with AWS cognito oauth2 flow

I am trying to add authentication for AWS cognito with sk-auth.

This is my current src/lib/appAuth.ts file

import { SvelteKitAuth } from "sk-auth";
import { dev } from '$app/env';
import {
    OAuth2Provider
} from "sk-auth/providers";

const DOMAIN = import.meta.env.VITE_COGNITO_DOMAIN;
export const appAuth = new SvelteKitAuth({
    protocol: dev ? 'http' : 'https',
    providers: [
        new OAuth2Provider({
            id: 'cognito',
            accessTokenUrl: `https://${DOMAIN}/oauth2/token`,
            profileUrl: `https://${DOMAIN}/oauth2/userInfo`,
            authorizationUrl: `https://${DOMAIN}/oauth2/authorize`,
            clientId: import.meta.env.VITE_COGNITO_CLIENT_ID,
            clientSecret: import.meta.env.VITE_COGNITO_CLIENT_SECRET,
            scope: ['openid', 'email'],
            contentType: 'application/x-www-form-urlencoded',
            profile(profile, tokens) {
                return {
                    ...profile,
                    access_token: tokens.access_token,
                    id_token: tokens.id_token,
                    refresh_token: tokens.refresh_token,
                    provider: 'cognito'
                };
            }
        })
    ]
});

I am testing the login with this index.svelte file

<script lang="ts">
    import { session } from "$app/stores";
    import { signOut as authSignOut } from "sk-auth/client";
    
    function signIn() {
        location.assign('/api/auth/signin/cognito?redirect=/');
    }

    function signOut() {
        authSignOut().then(session.set);
    }

    console.log($session.user)
</script>

{#if !$session.user}
    <button on:click="{signIn}">Log In with Cognito</button>
{:else}
    <p>You are logged in as: {$session.user.email}!</p>
    <button on:click={signOut}>Log Out</button>
{/if}

The authentication works but as soon as I am passing more then one token to the session.user the login breaks and the session.user remains "undefined":

image

When I am removing all but one token from the OAuth2 Configuration the object is passed as expected:

(src/lib/appAuth.ts)

...
...
            profile(profile, tokens) {
                return {
                    ...profile,
                    id_token: tokens.id_token,
                    provider: 'cognito'
...
...

image

Any clues why this happens? I assume this has to do with the size of the passed cookie / HTTP headers, but I do not know how to verify this assumption.

Should this package be deprecated?

With the release of SvelteKit 1.0 and the revamp of NextAuth as Auth.js, should this package be deprecated in favor of @auth/sveltekit and @auth/core?

When I recently tried this library, it didn't seem to work with the recent breaking changes of SvelteKit, and while Auth.js is still experimental and unstable, it does work.

I'm mostly wondering for newcomers to SvelteKit if keeping this project active would cause more confusion and issues than directing folks elsewhere.

My thanks and huge kudos to all the contributors on this repo!

Verify oauth token?

Hi. Does this library verify the OAuth JWT tokens for me (towards a standard keycloak oauth server) or do I need to do that myself? Verification of the issuer, signature of the JWT etc.

Best regards,
Lars

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.