Я пытаюсь заставить приложение Angular 7 правильно выполнить неявную аутентификацию с Azure AD B2 C. Я использую msal. js, чтобы попытаться заставить его работать. Что я сделал на странице обслуживания
`import { Injectable } from '@angular/core';
import * as Msal from 'msal';
import { Router } from '@angular/router';
import { AuthenticationService } from '.';
import { CurrentPer } from '../_models';
import { BehaviorSubject } from 'rxjs';
import { environment } from '../../../../environments/environment';
import { PreviousRouteService } from './previous-route.service';
@Injectable()
export class MsalService {
private currentPersonInfoSubject: BehaviorSubject<CurrentPersonInfoDto>;
private b2cAccessTokenKey = "b2c.access.token";
private tenantConfig;
private authority;
private clientApplication;
constructor(
private router: Router,
private authenticationService: AuthenticationService,
private coreService: CoreService,
private featureService : FeatureService,
private previousRouteService: PreviousRouteService) {
this.tenantConfig = {
tenant: environment.tenant,
clientID: environment.clientID,
resetPasswordPolicy: environment.resetPasswordPolicy,
signInPolicy: environment.signInPolicy,
signUpPolicy: environment.signUpPolicy,
postLogoutRedirectUri: environment.postLogoutRedirectUri.replace('$hostname', window.location.hostname),
redirectUri: window.location.origin,
b2cScopes: [environment.b2cScopes]
};
this.authority = environment.authority + this.tenantConfig.tenant + "/" + this.tenantConfig.signInPolicy;
this.clientApplication = new Msal.UserAgentApplication(
this.tenantConfig.clientID, this.authority, this.authCallback,
{ validateAuthority: false,//required for enabling JS
cacheLocation: 'sessionStorage'
}
);
}
public login(): void {
this.clientApplication.authority = environment.authority + this.tenantConfig.tenant + "/" + this.tenantConfig.signInPolicy;
this.clientApplication.loginRedirect(this.tenantConfig.b2cScopes);
}
public getAuthenticationToken() {
this.clientApplication.acquireTokenSilent(this.tenantConfig.b2cScopes).then(
function (accessToken: any) {
this.saveAccessTokenToCache(accessToken);
//API call
this.authenticationService.APIcall().pipe().subscribe(response => {
this.coreService.fireRequest().pipe()
.subscribe(result => {
let redirectUrl =this.previousRouteService.getPreviousUrl();
if (redirectUrl)
{
this.router.navigate(['/'+ redirectUrl]);
}
else
{
this.router.navigate(['/profile']);
}
});
});
}, function (error: any) {
console.info("error:", error);
this.clientApplication.acquireTokenRedirect(this.tenantConfig.b2cScopes).then(
function (accessToken: any) {
this.saveAccessTokenToCache(accessToken);
//call API
this.authenticationService.APICall().pipe().subscribe(response => {
this.coreService.fireRequest().pipe()
.subscribe(result => {
let redirectUrl = this.previousRouteService.getPreviousUrl();
if (redirectUrl)
{
this.router.navigate(['/'+ redirectUrl]);
}
else
{
this.router.navigate(['/profile']);
}
});
});
}, function (error: any) {
console.log("error: ", error);
});
})
}
private authCallback(errorDesc: any, token: any, error: any, tokenType: any) {
console.log('Callback');
if (token) {
console.log("Id token", token);
}
else {
console.log(error + ":" + errorDesc);
}
this.getAuthenticationToken();
}
saveAccessTokenToCache(accessToken: string): void {
sessionStorage.setItem(this.b2cAccessTokenKey, accessToken);
};
checkAccessTokenInCache(): boolean {
if (sessionStorage.hasOwnProperty(this.b2cAccessTokenKey) && sessionStorage[this.b2cAccessTokenKey] !== "") {
return true;
}
return false;
};
logout(): void {
sessionStorage.clear();
this.currentPersonInfoSubject.next(null);
this.clientApplication.logout();
location.replace('login');
};
isLoggedIn(): boolean {
console.log(this.clientApplication.getUser());
return this.clientApplication.getUser() != null;
};
getUserEmail(): string {
return this.getUser().idToken['emails'][0];
}
getUser() {
return this.clientApplication.getUser();
}
}
`и в routing.ts
{
path: '',
redirectTo: 'profile',
pathMatch: 'full',
},
{
path: 'login',
canActivate: [LoginGuard],
component: LoginComponent
},
и в login.guard.ts
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
console.log(this._mslaService.isLoggedIn());
if (!this._mslaService.isLoggedIn()) {
return true;
}
location.replace('/profile');
return false;
}
Я получаю идентификатор токен в msal.service.ts. Но я столкнулся с некоторыми проблемами 1. после этого он не вызывает getAuthenticationToken (). 2. после входа в систему снова перенаправьте на страницу входа. 3. не можете вызвать API-интерфейс для получения информации о пользователе. Требуется ли снова вызывать getAuthenticationToken ()? Что-то не так в потоке кода?. Я пытался с другой документацией. Но я не могу понять проблему