Пользователь ng-oid c -клиента не найден в хранилище - PullRequest
0 голосов
/ 05 апреля 2020

Я обновил все свои Angular зависимости, включая ng-oid c -клиент (~ 2.0.3) и oid c -клиент (^ 1.10. 1) но после обновления я не могу войти в свое приложение из-за бесконечного перенаправления.

В консоли я получил следующую ошибку:

UserManager.getUser: user not found in storage
UserManager.signinRedirectCallback: successful, signed in sub:  auth0|auth0|5cac7184cf805a119895edc6

Я могу ' Не могу найти причину, по которой это больше не работает после обновления.

Я также заменил страницы stati c HTML на последние из их документации:

oid c -login-redirect-callback. html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Callback</title>
    <link rel="icon" type="image/x-icon" href="favicon.png" />
    <script src="oidc-client.min.js" type="application/javascript"></script>
  </head>

  <body>
    <script>
      var Oidc = window.Oidc;

      var config = {
        userStore: new Oidc.WebStorageStateStore({ store: window.localStorage }),
      };

      if (Oidc && Oidc.Log && Oidc.Log.logger) {
        Oidc.Log.logger = console;
      }
      var isPopupCallback = JSON.parse(window.localStorage.getItem('ngoidc:isPopupCallback'));

      if (isPopupCallback) {
        new Oidc.UserManager(config).signinPopupCallback();
      } else {
        new Oidc.UserManager(config).signinRedirectCallback().then((t) => {
          window.location.href = '/';
        });
      }
    </script>
  </body>
</html>

oid c -login-redirect-callback. html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Renew Callback</title>
    <link rel="icon" type="image/x-icon" href="favicon.png" />
  </head>

  <body>
    <script src="oidc-client.min.js"></script>
    <script>
      var config = {
        userStore: new Oidc.WebStorageStateStore({ store: window.localStorage }),
      };
      new Oidc.UserManager(config).signinSilentCallback().catch(function (e) {
        console.error(e);
      });
    </script>
  </body>
</html>

oid c -logout-redirect-callback. html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Signout Callback</title>
    <link rel="icon" type="image/x-icon" href="favicon.png" />
    <script src="oidc-client.min.js" type="application/javascript"></script>
  </head>

  <body>
    <script>
      var Oidc = window.Oidc;

      var config = {
        userStore: new Oidc.WebStorageStateStore({ store: window.localStorage }),
      };

      if (Oidc && Oidc.Log && Oidc.Log.logger) {
        Oidc.Log.logger = console;
      }

      var isPopupCallback = JSON.parse(window.localStorage.getItem('ngoidc:isPopupCallback'));

      if (isPopupCallback) {
        new Oidc.UserManager(config).signoutPopupCallback();
      } else {
        new Oidc.UserManager(config).signoutRedirectCallback().then((test) => {
          window.location.href = '/';
        });
      }
    </script>
  </body>
</html>

auth.module по-прежнему настроен, как и до обновления:

export function getWebStorageStateStore() {
  return new WebStorageStateStore({ store: window.localStorage });
}

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    NgOidcClientModule.forRoot({
      // prettier-ignore
      oidc_config: {
        authority: environment.sts.authority,
        client_id: environment.sts.clientId,
        redirect_uri: `${environment.appRoot}oidc-login-redirect-callback.html`,
        scope: 'openid profile email',
        response_type: 'id_token token',
        post_logout_redirect_uri: `${environment.appRoot}oidc-logout-redirect-callback.html`,
        silent_redirect_uri: `${environment.appRoot}oidc-silent-renew-redirect-callback.html`,
        accessTokenExpiringNotificationTime: 10,
        automaticSilentRenew: true,
        metadata: {
          authorization_endpoint: `${environment.sts.authority}authorize?audience=${environment.sts.audience}`,
          userinfo_endpoint: `${environment.sts.authority}userinfo`,
          issuer: environment.sts.authority,
          jwks_uri: `${environment.sts.authority}.well-known/jwks.json`,
          // tslint:disable-next-line:max-line-length
          end_session_endpoint: `${environment.sts.authority}v2/logout?returnTo=${environment.appRootEncoded + 'oidc-logout-redirect-callback.html'}&client_id=${environment.sts.clientId}`
        },
        userStore: getWebStorageStateStore
      }
    }),
  ],
  exports: [],
  providers: [
    AuthService,
    CanActivateAuthGuard,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthInterceptorService,
      multi: true,
    },
  ],
})

И я также использую тот же перехватчик, что и раньше:

intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return this.authService.identity$.pipe(
      take(1),
      switchMap(user => {
        if (user && !user.expired && user.access_token) {
          req = req.clone({
            setHeaders: {
              Authorization: `Bearer ${user.access_token}`,
            },
          });
        } else {
          this.authService.signinRedirect();
        }
        return next.handle(req);
      })
    );
  }
}

И тот же охранник:

@Injectable()
export class CanActivateAuthGuard implements CanActivate {
  constructor(private authService: AuthService) {}

  public canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | boolean {
    return this.authService.loggedIn$.pipe(take(1));
  }
}

Что я должен сделать, чтобы исправить UserManager.getUser ошибка и удалить бесконечный редирект на o ID c -logout переадресация обратного вызова. html

...