跳到主内容

将用户登录到 Electron 应用

本指南介绍如何运行 Casdoor 的 Electron 示例,以及如何将相同的登录流程添加到您自己的应用中。用户在系统浏览器中登录,浏览器通过自定义协议将结果返回给应用。


学习目标​

  • 配置、运行和打包示例应用。
  • 为您的应用注册自定义协议。
  • 在浏览器中打开 Casdoor 登录页面并接收授权码。
  • 用授权码交换令牌并读取用户信息。

所需条件​

示例代码​


运行示例​

  1. 克隆 casdoor-electron-example 并安装其依赖项。

  2. 设置以下值。它们都是字符串。

    名称描述路径
    serverUrl您的Casdoor服务器URLsrc/App.js
    clientid您的Casdoor应用程序的客户端IDsrc/App.js
    appName您的Casdoor应用程序的名称src/App.js
    redirectPath如果未提供,您的Casdoor应用程序的重定向URL路径将为/callbacksrc/App.js
    clientSecret您的Casdoor应用程序的客户端密钥src/App.js
    casdoorServiceDomainYour Casdoor server URLpublic/electron.js
  3. 使用 npm run dev 或 yarn dev 构建并启动应用。

  4. 在应用窗口中,点击 Login with Casdoor。

    Example app before sign-in

    Casdoor 登录页面将在您的浏览器中打开。

    Casdoor sign-in page in the browser

  5. 登录。浏览器会再次打开应用,应用显示您的用户名。

    Example app after sign-in

Recording of the complete sign-in flow

打包示例​

要打包应用以便分发,请运行 npm run make 或 yarn make。该命令创建包含包的 out 文件夹:

// Example for macOS out/  
├── out/make/zip/darwin/x64/casdoor-electron-example-darwin-x64-1.0.0.zip
├── ...
└── out/casdoor-electron-example-darwin-x64/casdoor-electron-example.app/Contents/MacOS/casdoor-electron-example

向您的应用添加登录功能​

注册自定义协议​

注册 casdoor 协议,以便浏览器可以打开您的应用并将授权码传递给它:

const protocol = "casdoor";

if (process.defaultApp) {
if (process.argv.length >= 2) {
app.setAsDefaultProtocolClient(protocol, process.execPath, [
path.resolve(process.argv[1]),
]);
}
} else {
app.setAsDefaultProtocolClient(protocol);
}

在浏览器中打开登录页面​

构建登录 URL 并在系统浏览器中打开它。将前五个变量更改为您 Casdoor 实例的值。

const serverUrl = "https://door.casdoor.com";
const appName = "app-casnode";
const redirectPath = "/callback";
const clientId = "014ae4bd048734ca2dea";
const clientSecret = "f26a4115725867b7bb7b668c81e1f8f7fae1544d";

const redirectUrl = "casdoor://localhost:3000" + redirectPath;

const signinUrl = `${serverUrl}/login/oauth/authorize?client_id=${clientId}&response_type=code&redirect_uri=${encodeURIComponent(redirectUrl)}&scope=profile&state=${appName}&noRedirect=true`;

shell.openExternal(signinUrl); //Open the login url in the browser

接收授权码​

After the user signs in, the browser opens your app through the custom protocol. 监听该事件:

const gotTheLock = app.requestSingleInstanceLock();
const ProtocolRegExp = new RegExp(`^${protocol}://`);

if (!gotTheLock) {
app.quit();
} else {
app.on("second-instance", (event, commandLine, workingDirectory) => {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
commandLine.forEach((str) => {
if (ProtocolRegExp.test(str)) {
const params = url.parse(str, true).query;
if (params && params.code) {
store.set("casdoor_code", params.code);
mainWindow.webContents.send("receiveCode", params.code);
}
}
});
}
});
app.whenReady().then(createWindow);

app.on("open-url", (event, openUrl) => {
const isProtocol = ProtocolRegExp.test(openUrl);
if (isProtocol) {
const params = url.parse(openUrl, true).query;
if (params && params.code) {
store.set("casdoor_code", params.code);
mainWindow.webContents.send("receiveCode", params.code);
}
}
});
}

授权码位于 casdoor_code 或 params.code 中。

用授权码交换用户信息​

async function getUserInfo(clientId, clientSecret, code) {
const { data } = await axios({
method: "post",
url: authCodeUrl,
headers: {
"content-type": "application/json",
},
data: JSON.stringify({
grant_type: "authorization_code",
client_id: clientId,
client_secret: clientSecret,
code: code,
}),
});
const resp = await axios({
method: "get",
url: `${getUserInfoUrl}?accessToken=${data.access_token}`,
});
return resp.data;
}

ipcMain.handle("getUserInfo", async (event, clientId, clientSecret) => {
const code = store.get("casdoor_code");
const userInfo = await getUserInfo(clientId, clientSecret, code);
store.set("userInfo", userInfo);
return userInfo;
});

有关此流程背后的请求,请参阅 OAuth 2.0。

另请参阅​