我正在尝试使用 Angular2 中的 MSAL 库进行 B2C Azure 身份验证。登录页面完美地重定向到 Azure 页面并提示用户输入用户名和密码。单击登录按钮并且身份验证成功后,该页面必须将自身重定向回我的应用程序登录页面并将“用户”对象设置为从 AzureAD 获取的对象。尽管身份验证成功,但未设置用户对象并且应用程序失败。
app.component.ts
import { Component } from '@angular/core';
import { Injectable } from '@angular/core';
import { AuthService } from 'app/services/auth.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [AuthService]
})
@Injectable()
export class AppComponent {
public user:Msal.User;
public userInfo: any = null;
public apiCallFailed: boolean;
public loginFailed: boolean;
constructor(private authService: AuthService,
private partnerService: PartnerService) {
authService.user$.subscribe((newUser: Msal.User) => {
console.log('change detected');
this.user = newUser;
});
}
public login() {
this.loginFailed = false;
this.authService.login()
//
}
auth.service.ts
import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Rx';
import {Subject} from 'rxjs/Rx';
import '../../../node_modules/msal/out/msal';
/// <reference path="../../../node_modules/msal/out/msal.d.ts" />
import { WindowRef } from '../windowRef';
@Injectable()
export class AuthService {
private applicationConfig: any = {
clientID: '**************************',
authority: "https://login.microsoftonline.com/tfp/*********",
b2cScopes: ["some.scope"],
webApi: 'http://localhost:3000/api/partners',
redirect_uri: 'http://localhost:6420'
};
private app: any;
private user =new Subject<Msal.User>();
user$ = this.user.asObservable();
constructor(private winRef: WindowRef) {
this.app = new Msal.UserAgentApplication(this.applicationConfig.clientID, this.applicationConfig.authority,
(errorDesc, token, error, tokenType) => {
console.log(this.winRef.nativeWindow.msal.getUser())
this.user.next(this.winRef.nativeWindow.msal.getUser());
}
);
}
public login() {
return this.app.loginRedirect(this.applicationConfig.b2cScopes)
}
我对 Angular2 完全陌生,并且处于学习曲线的开始阶段。经过一番阅读,我发现 observable 是前进的方式(我可能是错的)并在服务“Observable”中设置了用户对象,并让组件订阅它,以便可以捕获服务对用户对象的任何更改并由组件对其采取行动。但它不起作用。
app.component.html
<button (click)="login()" type="button" *ngIf="!user">Login</button>
<button (click)="callAPI()" type="button" *ngIf="user">Call API</button>
<button (click)="logout()" type="button" *ngIf="user">Logout</button>
与上面的代码一样,即使在成功验证后,我也只得到“登录”按钮(因为未设置用户),而不是预期的其他按钮。任何引导我走向正确方向的帮助将不胜感激。