GithubHelp home page GithubHelp logo

macfja / svelte-oauth2 Goto Github PK

View Code? Open in Web Editor NEW
39.0 4.0 4.0 45 KB

OAuth2 authorization for Svelte

License: MIT License

JavaScript 7.76% Svelte 11.54% TypeScript 78.95% HTML 1.75%
svelte sveltejs sveltekit oauth2 oauth2-client svelte-kit svelte3 svelte-v3 oauth2-authentication

svelte-oauth2's Introduction

Svelte (and SvelteKit) OAuth2

Add OAuth2 authorization in Svelte

Installation

npm install @macfja/svelte-oauth2

Examples

Svelte

<script>
    import Auth, { init, browserStrategy, AuthorizationCodePKCE, addAuthHeader } from "@macfja/svelte-oauth2"

    init(
        browserStrategy,
        new AuthorizationCodePKCE(
            browserStrategy,
            '$$gitlab client id$$',
            'http://localhost:5000/',
            'https://gitlab.com/oauth/token',
            'https://gitlab.com/oauth/authorize',
            'http://localhost:5000/',
        )
    )

    let username
    const getUserName = () => {
        addAuthHeader().then(headers => {
            fetch('https://gitlab.com/api/v4/user', { headers })
                .then(response => response.json())
                .then(response => username = response.username)
        })
    }
</script>

<Auth scopes={['read_user']} on:authenticated={getUserName}>
    <div slot="loading">Loading...</div>
    <div slot="error" let:error>{error.message}</div>
    Hello {username}!
</Auth>

SvelteKit

src/hooks.js

import { svelteKitStrategy } from "@macfja/svelte-oauth2"

export async function handle({ request, resolve }) {
    return svelteKitStrategy.handleHook({request, resolve})
}

src/routes/index.html

<script context="module">
    import { init, svelteKitStrategy, AuthorizationCodePKCE, runOAuth2Process } from "@macfja/svelte-oauth2"

    const scopes = ['read_user'];

    export const load = async ({fetch, page}) => {
        svelteKitStrategy.setFetch(fetch)
        svelteKitStrategy.setQuery(page.query)
        init(
            svelteKitStrategy,
            new AuthorizationCodePKCE(
                svelteKitStrategy,
                '$$gitlab client id$$',
                'http://localhost:3000/',
                'https://gitlab.com/oauth/token',
                'https://gitlab.com/oauth/authorize',
                'http://localhost:3000/',
            )
        )
        try {
            return {
                props: { authentication: await runOAuth2Process(scopes) }
            }
        } catch (e) {
            return {
                props: { authentication: Promise.reject(e) }
            }
        }
    }
</script>
<script>
    import Auth, { addAuthHeader } from "@macfja/svelte-oauth2"

    export let authentication
    /*
     For the example purpose this is done in the browser, but can also be done in SSR
     See below.
     */
    let username
    const getUserName = () => {
        addAuthHeader().then(headers => {
            fetch('https://gitlab.com/api/v4/user', { headers })
                .then(response => response.json())
                .then(response => username = response.username)
        })
    }
</script>

<h1>Welcome to SvelteKit</h1>
<p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p>

<Auth scopes={['read_user']} on:authenticated={getUserName}>
    <div slot="loading">Loading...</div>
    <div slot="error" let:error>{error.message}</div>
    Hello {username}!
</Auth>

SvelteKit full SSR

src/hooks.js

import { svelteKitStrategy } from "@macfja/svelte-oauth2"

export async function handle({ request, resolve }) {
    return svelteKitStrategy.handleHook({request, resolve})
}

src/routes/index.html

<script context="module">
    import { init, svelteKitStrategy, AuthorizationCodePKCE, runOAuth2Process, addAuthHeader, isAuthorized } from "@macfja/svelte-oauth2"

    const scopes = ['read_user'];

    export const load = async ({fetch, page}) => {
        svelteKitStrategy.setFetch(fetch)
        svelteKitStrategy.setQuery(page.query)
        init(
            svelteKitStrategy,
            new AuthorizationCodePKCE(
                svelteKitStrategy,
                '$$gitlab client id$$',
                'http://localhost:3000/',
                'https://gitlab.com/oauth/token',
                'https://gitlab.com/oauth/authorize',
                'http://localhost:3000/',
            )
        )
        try {
            const auth = await runOAuth2Process(scopes)
            let username;
            if (await isAuthorized(scopes)) {
                username = await getUserName()
            }
            return {
                props: { authentication: auth, username }
            }
        } catch (e) {
            return {
                props: { authentication: Promise.reject(e) }
            }
        }
    }

    const getUserName = () => {
        return addAuthHeader().then(headers => {
            return fetch('https://gitlab.com/api/v4/user', { headers })
                    .then(response => response.json())
                    .then(response => response.username)
        })
    }
</script>
<script>
    import Auth from "@macfja/svelte-oauth2"

    export let authentication
    export let username
    const onAuth = () => {
        if (username !== undefined) return
        getUserName().then(value => username = value)
    }
</script>

<h1>Welcome to SvelteKit</h1>
<p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p>

<Auth scopes={['read_user']} on:authenticated={onAuth}>
    <div slot="loading">Loading...</div>
    <div slot="error" let:error>{error.message}</div>
    Hello {username}!
</Auth>

Available Grant

Client Credential

Implementation of Client Credential flow

import { ClientCredentials } from "@macfja/svelte-oauth2"
new ClientCredentials(
    contextStrategy, // The context strategy to use (How the auth integrate with the app), Svelte/Browser or SvelteKit
    'Client Id', // The OAuth2 Client Id
    'Client Secret', // The OAuth2 Client Secret
    'Token Uri', // The Auth Server URI where to get the access token.
    'Post Authenticate Uri', // The application URI to go when the user is authenticated.
    credentialMode, // Where to put credential (Client Id and Client Secret). "request" or "header"
)

Authorization Code

Implementation of Authorization Code flow

import { AuthorizationCode } from "@macfja/svelte-oauth2"
new AuthorizationCode(
    contextStrategy, // The context strategy to use (How the auth integrate with the app), Svelte/Browser or SvelteKit
    'Client Id', // The OAuth2 Client Id
    'Client Secret', // The OAuth2 Client Secret
    'Post Login Redirect Uri', // The application URI to go when the user is authenticated.
    'Token Uri', // The Auth Server URI where to get the access token.
    'Post Authenticate Uri', // The application URI to go when the user is authenticated.
    'Authorization Redirect Uri', // The application URI to go back from the Auth Server
    credentialMode, // Where to put credential (Client Id and Client Secret). "request" or "header"
)

Authorization Code With PKCE

Implementation of PKCE flow

import { AuthorizationCodePKCE } from "@macfja/svelte-oauth2"
new AuthorizationCodePKCE(
    contextStrategy, // The context strategy to use (How the auth integrate with the app), Svelte/Browser or SvelteKit
    'Client Id', // The OAuth2 Client Id
    'Post Login Redirect Uri', // The application URI to go when the user is authenticated.
    'Token Uri', // The Auth Server URI where to get the access token.
    'Post Authenticate Uri', // The application URI to go when the user is authenticated.
    'Authorization Redirect Uri', // The application URI to go back from the Auth Server
)

Contributing

Contributions are welcome. Please open up an issue or create PR if you would like to help out.

Read more in the Contributing file

License

The MIT License (MIT). Please see License File for more information.

svelte-oauth2's People

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

Watchers

 avatar  avatar  avatar  avatar

Forkers

mrtact thylou

svelte-oauth2's Issues

Import error in Svelet 4.0

Hi,

I tryed to use your OAuth2 library in our project, but I have the foloowing error during import of the lib


Could not find a declaration file for module '@macfja/svelte-oauth2'. '/workspace/retail-planner/frontend/node_modules/@macfja/svelte-oauth2/dist/index.mjs' implicitly has an 'any' type.
Try npm i --save-dev @types/macfja__svelte-oauth2 if it exists or add a new declaration (.d.ts) file containing declare module '@macfja/svelte-oauth2';ts(7016)

My Environnement :
"svelte": "^4.0.5",

Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating 'parent_component.$$')

As soon as I add

    <Auth scopes={['read']} on:authenticated={getUserName}>
        <div slot="loading">Loading...</div>
        <div slot="error" let:error>{error.message}</div>
        Hello {username}!
    </Auth>

From the example I get an error:

[Error] Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating 'parent_component.$$')
	construct_svelte_component_dev (bundle.js:540)
	update (bundle.js:840)
	update (bundle.js:1007)
	update$1 (bundle.js:245)
	flush$1 (bundle.js:212)
	promiseReactionJob
```

Does it work with current Svelte? `^3.53.1`

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.