Implementing OAuth2

Written — Updated
  • For each supported provider (Github, Twitter, etc.) you need to create an application with that provider in order to do OAuth2, even if all you want to do is authenticate.
  • To login, open a new window pointing to a local endpoint.
    • Also add a message handler to know when the login is done
      • const loginWindow =
            if (loginWindow) {
         window.addEventListener('message', function handler(event) {
           window.removeEventListener('message', handler);
      • This one closes the window and tells SvelteKit to reload the user data.
  • That endpoint should redirect to the authorization URL at the provider for your app.
  • The OAuth callback is then another app endpoint that handles the code
    • If the user hasn't logged in before, create a new one.
    • Fetch the user metadata and optionally update it if needed
    • Create a new session, create the session cookie, etc.
    • Finally, return some a small <script> snippet that talks back to the original app's handler and tells it the login is done.
    •   return {
      headers: {
        'Set-Cookie': cookie,
        'Content-Type': 'text/html; charset=utf-8',
      body: `
           success: true
         }, window.location.origin);

Thanks for reading! If you have any questions or comments, please send me a note on Twitter.