ClientAuthError: операция обновления токена не удалась из-за тайм-аута MSAL Angular - PullRequest
0 голосов
/ 14 июля 2020

Я очень новичок в MSAL. Таким образом, я следовал только настройкам basi c для его реализации отсюда https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-angular/README.md.

Я сделал настройку конфигурации в app.module, как это

    MsalModule.forRoot({
      auth: {
        clientId: 'myclientid', // This is your client ID
        authority: 'https://login.microsoftonline.com/mytenantid', // This is your tenant ID
        redirectUri: 'http://localhost:4200'// This is your redirect URI
       
      },
      cache: {
        cacheLocation: 'sessionStorage',
        storeAuthStateInCookie: isIE, // Set to true for Internet Explorer 11
      },
    }, {
      popUp: !isIE,
      consentScopes: [
                  'user.read',
                  'openid',
                  'apiappid/user_impersonation',
                ], 
      unprotectedResources: [],
      protectedResourceMap: [
                  [
                    'https://localhost:44331/',
                    ['apiappid/user_impersonation'],
                  ]
                  
                ], 
      extraQueryParameters: {}
    })

и в файле маршрутизации это было добавлено

 {path : 'das',canActivate: [MsalGuard], component:CrMainComponent},

Вот мой app.component.ts

import {
  Component,
  Injectable
} from '@angular/core';
import {
  Observable,
  Subscription
} from 'rxjs';

import {
  BroadcastService,
  MsalService
} from '@azure/msal-angular';
import {
  CryptoUtils,
  Logger,
  AuthError,
  AuthResponse
} from 'msal';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'angular-client';
  loggedIn: boolean;

  public userInfo: any = null;
  private subscription: Subscription;
  public isIframe: boolean;

  constructor(private broadcastService: BroadcastService, private authService: MsalService) {

    this.isIframe = window !== window.parent && !window.opener;

    if (this.authService.getAccount())

    {
      //console.info(JSON.stringify(this.authService.getAccount()));
      this.loggedIn = true;

    } else {

      this.loggedIn = false;
      //this.login();

    }
  }
  login()

  {

    const isIE = window.navigator.userAgent.indexOf("MSIE ") > -1 || window.navigator.userAgent.indexOf("Trident/") > -1;

    if (isIE) {
      this.authService.loginRedirect();

    } else {

      this.authService.loginPopup();

    }
  }

  logout()
  {
    this.authService.logout();

  }
  ngOnInit() {

    this.broadcastService.subscribe("msal:loginFailure", (payload) => {

      console.log("login failure " + JSON.stringify(payload));

      this.loggedIn = false;

    });

    this.broadcastService.subscribe("msal:loginSuccess", (payload) => {
      console.log("login success " + JSON.stringify(payload));
      this.loggedIn = true;
      //alert("Login Success");

    });
    this.authService.handleRedirectCallback((redirectError: AuthError, redirectResponse: AuthResponse) => {
      if (redirectError) {
        console.error("Redirect error: ", redirectError);
        return;
      }

      console.log("Redirect success: ", redirectResponse);
    });
  }

  ngOnDestroy() {

    this.broadcastService.getMSALSubject().next(1);
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}

Итак, я предполагаю, поскольку я указал Msalguard в своей конфигурации маршрутизации, его перенаправление на Microsoft Azure аутентификации AD и при успешной аутентификации перенаправляет меня обратно на мою страницу. Все работает нормально.

Но иногда я получаю сообщение об ошибке

Uncaught (in promise): ClientAuthError: Token renewal operation failed due to timeout.

Честно говоря, я понятия не имею, что мне не хватает или что я сделал не так. Ни в одном из моих кодов я не выполняю никаких операций для процедуры входа в систему. Все это происходит автоматически, когда у меня есть этот код. Так действительно ли мы что-то делаем, чтобы исправить эту проблему с продлением токена? Я имею в виду, нужно ли нам обновлять токен вручную? Если да, то как ??

Ответы [ 2 ]

0 голосов
/ 03 сентября 2020

Используйте приведенный ниже код, чтобы избежать операции обновления токена.

this.authService.acquireTokenPopup(requestObj).then(function (tokenResponse) {
  // Callback code here
  console.log(tokenResponse.accessToken);
}).catch(function (error) {
  console.log(error);
});

Не используйте => this.authService. acquTokenSilent

это обходной путь, актуальная проблема здесь https://github.com/AzureAD/microsoft-authentication-library-for-js/issues/1592

0 голосов
/ 15 июля 2020

В случае ошибки тайм-аута вызовите acquTokenPopup с тем же набором областей, а затем сделайте запрос еще раз. Вы можете обратиться к , это

Это известная проблема с проблемой продления. Вы можете отслеживать проблему здесь .

Если вы хотите использовать MSAL для Angular, обратитесь к этому образцу

...