目的 - @azure/msal-angularおよびmsalライブラリを使用して、angular 8 で azureAD 認証を実装しています。
問題 - pathlocationstrategy を使用するとすべて正常に動作しますが、hashlocationstrategy を使用すると、@azure/msal-angular ライブラリのコールバックが呼び出されません。
コード フロー -
ユーザーが HomeComponent のログイン ボタンをクリックする -> ユーザーが Microsoft のログイン ページにリダイレクトされる -> ユーザーが資格情報を入力する -> ログインに成功すると、ユーザーは msalLandingComponent ホーム コンポーネント (appcomponent の routeroutlet でレンダリングされる) にリダイレクトされ、そこでコールバック (this._msalService .handleRedirectCallback) を実行する必要があります。
コード
環境.ts
export const environment = {
production: false,
clientId: 'xxxxxxxxxxxxxxxxxxxxxxxxx',
authority: 'https://login.microsoftonline.com/xxxxxxxxxxxxxxxxxxxxxxx/',
redirectUrl: 'http://localhost:4200/#/msal-landing'
};
http://localhost:4200/ として redirectUrl も試しました
app-routing.module.ts
const routes: Routes = [
{ path: '', component: HomeComponent }
{ パス: 'msal-landing'、コンポーネント: MsalLandingComponent }
];
HomeComponent - ユーザーが onButtonClick() を呼び出すログイン ボタンをクリックします。
home.component.html
<input type="button" value="Login" (click)="onButtonClick()" />
home.component.ts
import { Component, OnInit } from '@angular/core';
import { MsalService } from '@azure/msal-angular';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private _msalService: MsalService) { }
ngOnInit() {
this._msalService.handleRedirectCallback((error,tokenInfo) => {
});
}
onButtonClick()
{
this._msalService.loginRedirect();
}
}
msal-landing.component.ts
import { Component, OnInit } from '@angular/core';
import { MsalService } from '@azure/msal-angular';
@Component({
selector: 'app-msal-landing',
templateUrl: './msal-landing.component.html',
styleUrls: ['./msal-landing.component.css']
})
export class MsalLandingComponent implements OnInit {
constructor(private _msalService: MsalService) { }
ngOnInit() {
this._msalService.handleRedirectCallback((error,tokenInfo) => {
});
}
}
問題の説明
ユーザーを Microsoft のログイン ページにリダイレクトするため
onButtonClick()
{
this._msalService.loginRedirect();
}
が呼び出され、ログイン ユーザーがリダイレクト URL にリダイレクトされた後、ngOnInit で以下のコードを実行する必要があります
ngOnInit() {
this._msalService.handleRedirectCallback((error,tokenInfo) => {
});
}
しかし、hashlocationstrategy を使用している場合、このコールバックは呼び出されません。
追加情報 アプリの登録時に、azure で # を使用して redirectUrl を設定することはできないと思います。
したがって、リダイレクト URL を "http://localhost:4200/#/msal-landing" として設定する代わりに、"http://localhost:4200/" に設定します。ホームコンポーネントが呼び出されるように。
msal-landing.component.ts の ngOnInIt を home.component.ts に移動して上記のコードを更新し、MsalLandingComponent を削除しました。
ただし、この場合も handleRedirectCallback は呼び出されません。このコードが app.compnent.ts の ngOnInIt() に配置された場合にのみ呼び出されます。appComponent であるが homeComponent ではなくルート コンポーネントで呼び出される理由を理解できません。