如何从 iframe 并使用 REST API 返回的 authToken 在 RocketChat 中登录用户

问题描述

我将 RocketChat 以 angular 形式嵌入到我网站上的 iframe 中。理想情况下,当用户对我的 REST API 进行身份验证时,请使用 RocketChat REST API 对其进行身份验证,并使用 (RocketChat) 令牌在 Iframe 中对其进行身份验证。 我尝试通过多种方式使用 RocketChat REST API 返回的令牌对用户进行身份验证,但没有奏效。这是我的测试代码

模板:

<iframe
  #iframe
  id="iframe"
  src="https://myrocketchat.example.com/channel/general?layout=embedded"
  (load)="onIframeLoad()">
</iframe>

TS:

@ViewChild('iframe',{ static: false,read: ElementRef })
private iframe: ElementRef;

onIframeLoad() {
    this.iframe.nativeElement.contentwindow.postMessage({
      event: 'login-with-token',loginToken: 'LNpNjcARrh-GBwP8dxO5TEwLUwCP2lEIcRB5-GKgalX' // I get this token using Postman against the RocketChat REST API
    },'*');
}

这样就行不通了,我一直让窗口登录到 iframe。 我也尝试在 iframe 中调用 Meteor 对象,但它带来了 CROSS-ORIGIN 问题

this.iframe.nativeElement.contentwindow.Meteor.loginWithToken('LNpNjcARrh-GBwP8dxO5TEwLUwCP2lEIcRB5-GKgalX');

DOMException: Blocked a frame with origin "http://client-angular.example.com" from accessing a cross-origin frame.

解决方法

我在这里有两点,首先我可以看到您没有为 postMessage 使用正确的属性,您必须对 'externalCommand' 使用 'event' 而不是 'login-with-token'。更改此设置并测试您的代码。

如果第一步没有解决你的问题,那么第二点是关于在火箭聊天中验证你的会话的时间,我担心 'onIframeLoad' 事件会在它被验证之前加载,使用例如 window.onload,此事件将在加载 iframe 之前发生。

window.onload = function () {
     ocument.getElementById('iframe').contentWindow.postMessage({
          externalCommand: 'login-with-token',loginToken: 'LNpNjcARrh-GBwP8dxO5TEwLUwCP2lEIcRB5-GKGalX'
          },'*');
};