DEV Community

Cover image for πŸ’‘ Simplifying Chrome Extension Development with GitHub OAuth
Artem Turlenko
Artem Turlenko

Posted on β€’ Edited on

πŸ’‘ Simplifying Chrome Extension Development with GitHub OAuth

Hey devs! πŸš€

Are you building a Chrome Extension and want to integrate GitHub OAuth for secure authentication? πŸ” Whether you're looking to automate workflows, manage repositories, or simply personalize user experiences, this guide will walk you through the process of setting up GitHub OAuth in your Chrome Extension. Let's dive in! 🌊


🌐 Why Use GitHub OAuth in Chrome Extensions?

  1. Secure Authentication: OAuth ensures secure, token-based authentication without sharing passwords.
  2. Access Control: You can manage repository access with fine-grained permissions.
  3. Enhanced User Experience: Seamless integration with GitHub accounts improves usability and trust.

πŸ”§ Setting Up GitHub OAuth for Your Chrome Extension

1. Register Your Application on GitHub πŸ”–

  1. Go to GitHub Developer Settings.
  2. Click on "New OAuth App".
  3. Fill out the details:
    • Application Name: Your extension’s name.
    • Homepage URL: https://yourwebsite.com (or any placeholder).
    • Authorization Callback URL: https://<extension-id>.chromiumapp.org

Note: The <extension-id> is generated when you load your unpacked extension. You can fix this by adding a key in your manifest.json.

2. Configure manifest.jsonπŸ’‘

Add the following to your manifest.json:

{
  "manifest_version": 3,
  "name": "Your Extension Name",
  "version": "1.0",
  "permissions": ["identity", "storage", "activeTab"],
  "oauth2": {
    "client_id": "YOUR_GITHUB_CLIENT_ID",
    "scopes": ["repo"]
  },
  "background": {
    "service_worker": "background.js"
  }
}
Enter fullscreen mode Exit fullscreen mode

3. Implement OAuth Flow in background.js πŸ”„

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'start_oauth') {
    const redirectUri = chrome.identity.getRedirectURL();
    const authUrl = `https://github.com/login/oauth/authorize?client_id=YOUR_GITHUB_CLIENT_ID&redirect_uri=${encodeURIComponent(redirectUri)}&scope=repo`;

    chrome.identity.launchWebAuthFlow({ url: authUrl, interactive: true }, (redirectUrl) => {
      if (redirectUrl) {
        const code = new URL(redirectUrl).searchParams.get('code');
        if (code) {
          // Exchange code for token via your backend
          fetch('https://your-backend.com/auth/github', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ code })
          })
          .then(response => response.json())
          .then(data => {
            chrome.storage.local.set({ github_token: data.access_token });
            sendResponse({ success: true });
          });
        }
      }
    });
    return true;
  }
});
Enter fullscreen mode Exit fullscreen mode

4. Set Up Your Backend πŸš€

To exchange the OAuth code for an access token, use a simple Node.js backend:

const express = require('express');
const axios = require('axios');
require('dotenv').config();

const app = express();
app.use(express.json());

app.post('/auth/github', async (req, res) => {
  const { code } = req.body;
  const response = await axios.post('https://github.com/login/oauth/access_token', {
    client_id: process.env.GITHUB_CLIENT_ID,
    client_secret: process.env.GITHUB_CLIENT_SECRET,
    code
  }, { headers: { Accept: 'application/json' } });

  res.json(response.data);
});

app.listen(3000, () => console.log('OAuth Server running on port 3000'));
Enter fullscreen mode Exit fullscreen mode

πŸŽ‰ Done! What's Next?

  1. Test your extension by clicking the login button and verifying GitHub authentication.
  2. Store the token securely using chrome.storage.local.
  3. Automate tasks like committing code, managing repos, or fetching user data directly from GitHub!

πŸš€ Final Thoughts

Integrating GitHub OAuth into your Chrome Extension can significantly enhance the functionality and user experience. Plus, it keeps your app secure and streamlined! πŸš€

Have you tried adding OAuth to your extensions? Let me know your thoughts and experiences in the comments! πŸ‘‡πŸ»

Happy coding! πŸ’»πŸ’š


Follow me on LinkedIn, Codewars, LeetCode, and Behance!

Check out the full source code on GitHub!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay