如何在 Angular 中动态生成 Host URL (v. 4)

How to dynamically generate the Host URL in Angular (v. 4)

所以我正在使用 Auth0 并想知道如何动态生成主机 URL 来设置 redirectUri 属性 WebAuth() 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 应用程序时硬编码我的主机地址。正如你在上面看到的,我正在硬编码 <a href="http://localhost:4200/#/" rel="nofollow noreferrer">http://localhost:4200/#/</a> redirectUri.

我该怎么做?

您可以使用没有特定主机的 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'
});

我在这里发布这个是因为我认为其他人可能遇到了同样的问题。

这是我的 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.

你可以直接使用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'
});