node.js - 从 Electron 浏览器窗口获取 json

标签 node.js oauth-2.0 electron discord

我正在尝试使用 discord 的 Oauth2 为我的应用程序创建一个登录名,目前我正在显示一个单独的 BrowserWindow对于 API 调用,因为不和谐 Oauth2 要求用户单击授权。我的 API 调用返回 access_tokens 的原始 JSON。在我的应用程序的当前状态下,单独的窗口仅显示 JSON。我需要一种从窗口内或从变量中的请求获取 JSON 的方法。我似乎找不到任何访问原始内容的方法。

function createAuthWindow(){
    var authWindow = new BrowserWindow({
        width: 400, 
        height: 600, 
        show: false, 
        'node-integration': false,
        'web-security': false,
        icon: getFile('f','/src/asset/instance.png'),
    });
    // This is just an example url - follow the guide for whatever service you are using
    var authUrl = 'http://localhost:3001/api/discord/login'
    
    authWindow.loadURL(authUrl, (res) => {
        console.log(res)
        console.log(authWindow);
    });
    authWindow.show();
    // 'will-navigate' is an event emitted when the window.location changes
    // newUrl should contain the tokens you need
    authWindow.webContents.on('will-navigate', function (event, newUrl) {
        // More complex code to handle tokens goes here
        console.log(event.code);
        authWindow.webContents.session.webRequest.onCompleted({ urls: [newUrl] }, (details) => {
            // Access request headers via details.requestHeaders
            // Access response headers via details.responseHeaders
            console.log(authWindow.webContents.code)
          });
    });

最佳答案

听起来您的身份验证 URL 不正确,并且您应该发送授权代码流消息,以便您可以将 token 返回到您的应用程序。
桌面应用程序的常用技术是:

  • 格式化授权重定向 URL
  • 在系统浏览器中打开此 URL,它将为您处理重定向
  • 通过私有(private) URI 方案或环回通知接收响应
  • 交换 token 的授权代码,然后您的应用可以使用它来调用 API

  • 重定向 URL 将是一个类似这样的值,尽管我没有使用 Discord 作为提供者,所以这可能不是 100% 正确的:
    https://login.discord.com/oauth2/v2.0/authorize?
    client_id=y792f434f
    &response_type=code
    &redirect_uri=com.mycompany.myapp:/callback
    &scope=...
    &state=...
    &code_challenge=...
    &code_challenge_method=S256
    
    如果有帮助,我有几篇关于 Electron 桌面应用程序的 OAuth 的博客文章。虽然这是一个棘手的流程......
  • Initial Desktop Code Sample
  • Final Desktop Code Sample
  • 关于node.js - 从 Electron 浏览器窗口获取 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65273564/

    相关文章:

    python - Django Rest Framework 和 OAuth2 Toolkit 的额外保护层

    c# - Blazor/Electron : Handling close event

    javascript - 将 TypeScript 对象传递给 Electron 应用程序中的 Window

    javascript - node.js - 如何在expressjs中将数据从 Controller 传递到中间件?

    node.js - 在 Electron App (Nodejs) 中加载 TensorflowJS 时出错

    node.js - 通过 Docker 上 Supervisor 的 Cron 任务查看 Node JS 应用日志

    ios - 如何使用授权码流程为 IOS 客户端设置 Identity Server 3

    java - Spring OAuth2 隐式流重定向 url

    javascript - 如果错误回调不执行以下代码

    node.js - derbyjs 从 x-bind 在服务器上运行代码