如何以Angular动态生成主机URL(v.4)

时间:2017-06-15 13:38:10

标签: angular auth0

所以我使用的是 Auth0 ,想知道如何动态生成主机网址,以设置 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应用程序时,我不想对主机地址进行硬编码。正如您在上面所看到的,我很难编码http://localhost:4200/#/ redirectUri。

我该怎么做?

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

run.exe

答案 2 :(得分:-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'
});