2017-09-26 133 views
1

我正在嘗試使用Azure AD B2C實現對Angular 2+應用程序的身份驗證。發現這個偉大的example。然而,該示例在彈出窗口中進行身份驗證。我寧願使用重定向而不是彈出。對於不彈出認證MSAL Service的代碼如下:如何使用loginRedirect而不是loginPopup?

import { Injectable } from '@angular/core'; 
declare var bootbox: any; 
declare var Msal:any; 
@Injectable() 
export class MsalService { 

    access_token: string; 

    tenantConfig = { 
     tenant: "fabrikamb2c.onmicrosoft.com", 
     clientID: '90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6', 
     signUpSignInPolicy: "b2c_1_susi", 
     b2cScopes: ["https://fabrikamb2c.onmicrosoft.com/demoapi/demo.read"] 
    }; 

    // Configure the authority for Azure AD B2C 

    authority = "https://login.microsoftonline.com/tfp/" + this.tenantConfig.tenant + "/" + this.tenantConfig.signUpSignInPolicy; 

    /* 
    * B2C SignIn SignUp Policy Configuration 
    */ 
    clientApplication = new Msal.UserAgentApplication(
     this.tenantConfig.clientID, this.authority, 
     function (errorDesc: any, token: any, error: any, tokenType: any) { 
      // Called after loginRedirect or acquireTokenPopup 
     } 
    ); 

    public login(): void { 
     var _this = this; 
     this.clientApplication.loginPopup(this.tenantConfig.b2cScopes).then(function (idToken: any) { 
      _this.clientApplication.acquireTokenSilent(_this.tenantConfig.b2cScopes).then(
       function (accessToken: any) { 
        _this.access_token = accessToken; 
       }, function (error: any) { 
        _this.clientApplication.acquireTokenPopup(_this.tenantConfig.b2cScopes).then(
         function (accessToken: any) { 
          _this.access_token = accessToken; 
         }, function (error: any) { 
          bootbox.alert("Error acquiring the popup:\n" + error); 
         }); 
       }) 
     }, function (error: any) { 
      bootbox.alert("Error during login:\n" + error); 
     }); 
    } 

    logout(): void { 
     this.clientApplication.logout(); 
    }; 

    isOnline(): boolean { 
     return this.clientApplication.getUser() != null; 
    }; 
} 

如何改變這種代碼使用loginRedirect,而不是loginPopup做同樣的事情?

回答

2

then中的代碼從.loginPopup(blah).then()...中取出並放入// Called after loginRedirect or acquireTokenPopup所在的塊中。

+0

謝謝你的回答。你會碰巧知道爲什麼'login'函數上面的代碼同時調用'acquireTokenSilent'和'acguireTokenPopup'?看起來它應該調用其中一個或另一個,但不能同時調用它。 – ebhh2001

+1

如果它無法默默獲取令牌,那麼它將不得不提示用戶採取一些就像再次登錄一樣 – spottedmahn

0

而不是調用loginPopup進行登錄,您可以調用loginRedirect函數與Azure AD進行交互以進行重定向而不是彈出窗口。

+0

是的,我想到了很多。但是關於'.loginPopup'('.then(function ...')後面的代碼的其餘部分怎麼樣呢? – ebhh2001