【问题标题】:How to dynamically generate the Host URL in Angular (v. 4)如何在 Angular (v. 4) 中动态生成主机 URL
【发布时间】:2017-11-18 00:55:17
【问题描述】:

所以我正在使用 Auth0 并想知道如何动态生成 Host URL 来设置 WebAuth()redirectUri 属性auth0

auth0 = new auth0.WebAuth({
  clientID: AUTH_CONFIG.clientID,
  domain: AUTH_CONFIG.domain,
  responseType: 'token id_token',
  audience: `https://${AUTH_CONFIG.domain}/userinfo`,
  redirectUri: 'http://localhost:4200/#/callback',
  scope: 'openid'
});

目的是我不想在切换环境或部署 Angular 应用程序时硬编码我的主机地址。正如你在上面看到的,我正在硬编码@987654321@redirectUri。

我该怎么做?

【问题讨论】:

    标签: angular auth0


    【解决方案1】:

    您可以使用没有特定主机的 URL 来实现所需的行为:

    auth0 = new auth0.WebAuth({
      clientID: AUTH_CONFIG.clientID,
      domain: AUTH_CONFIG.domain,
      responseType: 'token id_token',
      audience: `https://${AUTH_CONFIG.domain}/userinfo`,
      redirectUri: '/callback',
      scope: 'openid'
    });
    

    【讨论】:

    • 这不起作用。它破坏了 auth0 服务,向我表明 redirectUri 必须是明确的,这就是难题的开始。
    • 使用 location.hostname + '/callback'
    • 这仍然不足;记得有 hashStrategy。另外,它也不包括协议或端口。
    【解决方案2】:

    我在此处发布此内容是因为我认为其他人可能遇到了同样的问题。

    这是我的 AuthService 解决方案,更详细:

    @Injectable()
    export class AuthService {
      // Configure Auth0
      hashStrategy = true;
    
      host = (() => {
        let hostUrl: string;
        let index: number;
        if (this.hashStrategy) {
          hostUrl = window.location.href;
          index = hostUrl.indexOf('#/') + 2; // add 2 to include the hash and forward slash
          hostUrl = hostUrl.slice(0, index);
        } else {
          hostUrl = window.location.protocol + '//' + window.location.hostname;
          if (window.location.port) {
              hostUrl += ':' + window.location.port + '/';
          }
        }
        return hostUrl;
      })();
    
      auth0 = new auth0.WebAuth({
        clientID: AUTH_CONFIG.clientID,
        domain: AUTH_CONFIG.domain,
        responseType: 'token id_token',
        audience: `https://${AUTH_CONFIG.domain}/userinfo`,
        redirectUri: this.host  + 'callback',
        scope: 'openid'
      });
    ...
    }
    

    通过将匿名函数分配给我的 AuthService 的实例属性,我可以为 hashStrategy 生成我的主机 URL,或者如果它不是 hashStrategy,则将实例属性 hashStrategy 设置为 false,然后将值实现到 Auth0。

    【讨论】:

      【解决方案3】:

      您可以只使用 window.location.origin。例如:

      auth0 = new auth0.WebAuth({
        clientID: AUTH_CONFIG.clientID,
        domain: AUTH_CONFIG.domain,
        responseType: 'token id_token',
        audience: `https://${AUTH_CONFIG.domain}/userinfo`,
        redirectUri: `${window.location.origin}/#/callback`,
        scope: 'openid'
      });
      

      【讨论】:

      • 无需手动将 hashStrategy 添加到 redirectUri 属性。 Angular 会自动附加 /#
      猜你喜欢
      • 1970-01-01
      • 2021-11-21
      • 2016-08-21
      • 2020-02-21
      • 2018-06-12
      • 2015-01-18
      • 2017-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多