Auth0失败localauthsetup 3次,以后我可以路由到主页

时间:2019-12-18 05:46:00

标签: angular authentication auth0

当我通过auth0登录时-localauthsetup失败3次,然后返回true进行登录,您能帮我吗?

在应用程序组件中调用

localauthsetup和handleAuthCallback,这与构造中的调用类似。

域ID和客户端ID是从配置文件中导入的,它也可以按预期工作,并且代码工作与提供的链接中的代码几乎相同:

https://auth0.com/docs/quickstart/spa/angular2/01-login#add-the-authentication-service

auth0Client$ = (from(
    createAuth0Client({
      domain: AuthConfig.domain,
      client_id: AuthConfig.clientId,
      redirect_uri: `${window.location.origin}`
    })
  ) as Observable<Auth0Client>).pipe(
    shareReplay(1), // Every subscription receives the same shared value
    catchError(err => _throw(err))
  );
  // Define observables for SDK methods that return promises by default
  // For each Auth0 SDK method, first ensure the client instance is ready
  // concatMap: Using the client instance, call SDK method; SDK returns a promise
  // from: Convert that resulting promise into an observable
  isAuthenticated$ = this.auth0Client$.pipe(
    concatMap((client: Auth0Client) => from(client.isAuthenticated())),
    tap(res => this.loggedIn = res)
  );
  handleRedirectCallback$ = this.auth0Client$.pipe(
    concatMap((client: Auth0Client) => from(client.handleRedirectCallback()))
  );
  // Create subject and public observable of user profile data
  private userProfileSubject$ = new BehaviorSubject<any>(null);
  userProfile$ = this.userProfileSubject$.asObservable();
  // Create a local property for login status
  loggedIn: boolean = null;

  constructor(private router: Router) {
    console.log('service called');
    //calling localauthsetup and handleAuthCallback here 

   }

  // When calling, options can be passed if desired
  // https://auth0.github.io/auth0-spa-js/classes/auth0client.html#getuser
  getUser$(options?): Observable<any> {
    return this.auth0Client$.pipe(
      concatMap((client: Auth0Client) => from(client.getUser(options))),
      tap(user => this.userProfileSubject$.next(user))
    );
  }

  localAuthSetup() {
    // This should only be called on app initialization
    // Set up local authentication streams
    const checkAuth$ = this.isAuthenticated$.pipe(
      concatMap((loggedIn: boolean) => {
        console.log('localauthsetup',loggedIn);
        if (loggedIn) {
          // If authenticated, get user and set in app
          // NOTE: you could pass options here if needed
          return this.getUser$();
        }
        // If not authenticated, return stream that emits 'false'
        return of(loggedIn);
      })
    );
    checkAuth$.subscribe((res)=>{
      console.log('subscripbe',res)
    });
  }

  login(redirectPath: string = '/') {
    console.log('login called',redirectPath);
    // A desired redirect path can be passed to login method
    // (e.g., from a route guard)
    // Ensure Auth0 client instance exists
    this.auth0Client$.subscribe((client: Auth0Client) => {
      // Call method to log in
      client.loginWithRedirect({
        redirect_uri: `${window.location.origin}`,
        appState: { target: redirectPath }
      });
    });
  }

  handleAuthCallback() {
    console.log('handleauth called');
    // Call when app reloads after user logs in with Auth0
    const params = window.location.search;
    if (params.includes('code=') && params.includes('state=')) {
      let targetRoute: string; // Path to redirect to after login processsed
      const authComplete$ = this.handleRedirectCallback$.pipe(
        // Have client, now call method to handle auth callback redirect
        tap(cbRes => {
          // Get and set target redirect route from callback results
          targetRoute = cbRes.appState && cbRes.appState.target ? cbRes.appState.target : '/';
        }),
        concatMap(() => {
          // Redirect callback complete; get user and login status
          return combineLatest([
            this.getUser$(),
            this.isAuthenticated$
          ]);
        })
      );
      // Subscribe to authentication completion observable
      // Response will be an array of user and login status
      authComplete$.subscribe(([user, loggedIn]) => {
        // Redirect to target route after callback processing
        this.router.navigate([targetRoute]);
      });
    }
  }

  logout() {
    // Ensure Auth0 client instance exists
    this.auth0Client$.subscribe((client: Auth0Client) => {
      // Call method to log out
      client.logout({
        client_id: AuthConfig.clientId,
        returnTo: `${window.location.origin}`
      });
    });
  }

2 个答案:

答案 0 :(得分:2)

这里是Konrad。我是Auth0社区工程师。不是Angular专家,但正如我看到的快速入门和您的代码段所示,您不会在仅定义了它的地方以及handleAuthCallback处调用localAuthSetup方法。您可以尝试按照快速入门中的建议在构造函数中同时调用两者吗?

答案 1 :(得分:0)

登录到您的租户,转到spa应用程序,设置。 找到允许的回调URL,并确保在那里有类似的内容。

您的域, your_domain /登录 “”“

PS“ / login”是应用程序登录URI的相同路径