Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Created May 14, 2020 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manoj-choudhari-git/3ed5c3d06ab8fead0aa0a3248fe78e04 to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/3ed5c3d06ab8fead0aa0a3248fe78e04 to your computer and use it in GitHub Desktop.
App Component TS For Azure AD protected Angular App
import { Component, OnInit } from '@angular/core';
import { BroadcastService, MsalService } from '@azure/msal-angular';
import { Logger, CryptoUtils } from 'msal';
import { isIE, b2cPolicies } from './app-config';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
title = 'app';
isIframe = false;
loggedIn = false;
constructor(private broadcastService: BroadcastService, private authService: MsalService) { }
ngOnInit() {
this.isIframe = window !== window.parent && !window.opener;
this.checkAccount();
// event listeners for authentication status
this.broadcastService.subscribe('msal:loginSuccess', (success) => {
// We need to reject id tokens that were not issued with the default sign-in policy.
// "acr" claim in the token tells us what policy is used
// (NOTE: for new policies (v2.0), use "tfp" instead of "acr")
if (success.idToken.claims['tfp'] !== b2cPolicies.names.signUpSignIn) {
window.alert("Password has been reset successfully. \nPlease sign-in with your new password");
return this.authService.logout()
}
console.log('login succeeded. id token acquired at: ' + new Date().toString());
console.log(success);
this.checkAccount();
});
this.broadcastService.subscribe('msal:loginFailure', (error) => {
console.log('login failed');
console.log(error);
// Check for forgot password error
if (error.errorMessage.indexOf('AADB2C90118') > -1) {
if (isIE) {
this.authService.loginRedirect(b2cPolicies.authorities.resetPassword);
} else {
this.authService.loginPopup(b2cPolicies.authorities.resetPassword);
}
}
});
// redirect callback for redirect flow (IE)
this.authService.handleRedirectCallback((authError, response) => {
if (authError) {
console.error('Redirect Error: ', authError.errorMessage);
return;
}
console.log('Redirect Success: ', response);
});
this.authService.setLogger(new Logger((logLevel, message, piiEnabled) => {
console.log('MSAL Logging: ', message);
}, {
correlationId: CryptoUtils.createNewGuid(),
piiLoggingEnabled: false
}));
}
// other methods
checkAccount() {
this.loggedIn = !!this.authService.getAccount();
}
login() {
this.authService.loginRedirect();
}
logout() {
this.authService.logout();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment