在Chrome扩展程序中验证Salesforce

yeotifhr  于 2023-04-09  发布在  Go
关注(0)|答案(1)|浏览(156)

我试图在Chrome扩展程序中对Salesforce进行身份验证,但我收到400错误。如果我在Express.js服务器中尝试此代码,则可以正常工作。

background.js

console.log("Extension loaded");

let user_signed_in = false;
const clientId =
  "xyz";
const callbackUrl = "https://dfghlbaebomdoihlfmegbpcmfkfgfno.chromiumapp.org";

const getSalesforceLoginLink = async () => {
  const res = await fetch(
    `https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=${clientId}&redirect_uri=${callbackUrl}`
  );

  if (res.status === 200) {
    // append login link
    return res.url;
  } else {
    console.error("Not able to fetch login link");
  }
};

const authenticateSalesforce = (salesforceLink) => {
  chrome.identity.launchWebAuthFlow(
    {
      url: salesforceLink,
      interactive: true,
    },
    function (redirect_url) {
      const codeParam = searchParams.get('code');
      let authCode = codeParam;
      const loginUrl = `https://login.salesforce.com/services/oauth2/token?grant_type=authorization_code&redirect_uri=${
    process.env.SALESFORCE_CALLBACK_URL
  }&client_id=${process.env.SALESFORCE_CLIENT_ID}&client_secret=${
    process.env.SALESFORCE_CLIENT_SECRET
  }&code=${encodeURIComponent(authCode)}`;
  const response = await fetch(loginUrl)
    .then(function (response) {
      return response?.json();
    })
    .then(function (data) {
      return data;
    });
      if (chrome.runtime.lastError) {
        sendResponse({ message: "fail" });
      } else {
        console.log({ redirect_url });
      }
    }
  );
};

chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
  if (request.message === "login") {
    if (user_signed_in) {
      console.log("User is already signed in.");
    } else {
      const salesforceLink = await getSalesforceLoginLink();
      authenticateSalesforce(salesforceLink);
    }

    return true;
  } else if (request.message === "logout") {
    user_signed_in = false;
    chrome.browserAction.setPopup({ popup: "./popup.html" }, () => {
      sendResponse({ message: "success" });
    });

    return true;
  }
});

manifest.json

{
  "manifest_version": 3,
  "name": "SF POC",
  "description": "A quick way to browse top posts from DEV Community.",
  "version": "0.0.1",
  "action": {
    "default_title": "SF POC"
  },
  "key": "xyz",
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["identity", "activeTab", "tabs", "windows"],
  "host_permissions": ["https://login.salesforce.com/*"]
}

nbnkbykc

nbnkbykc1#

您遇到的问题是由于使用fetch API获取Salesforce登录链接。Chrome扩展遵循同源策略,因此您无法使用fetch API进行跨域请求。在这种情况下,您应该直接使用为Salesforce登录构建的URL作为chrome.identity.launchWebAuthFlow的URL参数。
此外,authenticateSalesforce函数似乎存在问题,因为您在非异步函数中使用了await关键字。您应该使用async函数 Package 回调函数以避免错误。
下面是修改后的background.js文件:

console.log("Extension loaded");

let user_signed_in = false;
const clientId = "xyz";
const callbackUrl = "https://dfghlbaebomdoihlfmegbpcmfkfgfno.chromiumapp.org";

const getSalesforceLoginLink = () => {
  return `https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=${clientId}&redirect_uri=${callbackUrl}`;
};

const authenticateSalesforce = (salesforceLink) => {
  chrome.identity.launchWebAuthFlow(
    {
      url: salesforceLink,
      interactive: true,
    },
    async function (redirect_url) {
      if (chrome.runtime.lastError) {
        sendResponse({ message: "fail" });
      } else {
        const searchParams = new URLSearchParams(new URL(redirect_url).search);
        const authCode = searchParams.get("code");
        // Continue with your authentication flow using the authCode
        console.log({ redirect_url });
      }
    }
  );
};

chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
  if (request.message === "login") {
    if (user_signed_in) {
      console.log("User is already signed in.");
    } else {
      const salesforceLink = getSalesforceLoginLink();
      authenticateSalesforce(salesforceLink);
    }

    return true;
  } else if (request.message === "logout") {
    user_signed_in = false;
    chrome.browserAction.setPopup({ popup: "./popup.html" }, () => {
      sendResponse({ message: "success" });
    });

    return true;
  }
});

相关问题