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 = window.open(
         `/user/login/${provider}`,
         'oauthLogin',
         'width=600,height=400'
            );
            if (loginWindow) {
         window.addEventListener('message', function handler(event) {
           loginWindow.close();
           window.removeEventListener('message', handler);
           invalidate('/user');
         });
            }
        
      • 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: `
       <script>
         window.opener.postMessage({
           success: true
         }, window.location.origin);
       </script>
      `,
        };
      

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