Electronアプリでユーザーをサインインさせる
このガイドでは、Electron用Casdoor例の実行方法と、同じサインインフローを自分のアプリに追加する方法について説明します。ユーザーはシステムブラウザでサインインし、ブラウザはカスタムプロトコルを通じて結果をアプリに返します。
学習目標
- サンプルアプリの設定、実行、パッケージ化を行います。
- アプリのカスタムプロトコルを登録します。
- ブラウザでCasdoorのサインインページを開き、認可コードを受信します。
- コードをトークンと交換し、ユーザー情報を読み取ります。
必要なもの
- npmまたはYarnを含むNode.js
- Casdoor内のアプリケーション。指定しない場合、例ではCasdoorデモサイトとそのアプリケーションapp-casnodeを使用します。
サンプルコード
例を実行する
-
casdoor-electron-exampleをクローンし、依存関係をインストールします。
-
以下の値を設定します。すべて文字列です。
名前 説明 パス serverUrl あなたのCasdoorサーバーURL src/App.jsclientId あなたのCasdoorアプリケーションのクライアントID src/App.jsappName あなたのCasdoorアプリケーションの名前 src/App.jsredirectPath あなたのCasdoorアプリケーションのリダイレクトURLのパス、提供されていない場合は /callbackになりますsrc/App.jsclientSecret あなたのCasdoorアプリケーションのクライアントシークレット src/App.jscasdoorServiceDomain Your Casdoor server URL public/electron.js -
npm run devまたはyarn devでアプリをビルドして起動します。 -
アプリのウィンドウで Login with Casdoor をクリックします。

ブラウザに Casdoor のサインインページが開きます。

-
サインインすると、ブラウザでアプリが再度開き、ユーザー名が表示されます。


サンプルのパッケージ化
配布用にアプリをパッケージ化するには、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 を構築し、システムブラウザで開きます。最初の5つの変数を 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
認可コードの受信
ユーザーがサインインした後、ブラウザはカスタムプロトコル経由でアプリを開きます。そのイベントをリッスンします:
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 を参照してください。