Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
@azure/msal-angular
Advanced tools
Microsoft Authentication Library for Angular (Preview) =========================================================
@azure/msal-angular is a library that allows Angular applications to authenticate users with Microsoft Identity Platform and obtain tokens to call Microsoft APIs such as Microsoft Graph or any API registered with the Microsoft identity platform.
User Authentication
This code demonstrates how to set up the MSAL instance in an Angular application to enable user authentication with Microsoft Identity Platform.
import { MsalModule, MsalService, MSAL_INSTANCE } from '@azure/msal-angular';
import { PublicClientApplication } from '@azure/msal-browser';
export function MSALInstanceFactory() {
return new PublicClientApplication({
auth: {
clientId: 'your-client-id',
authority: 'https://login.microsoftonline.com/your-tenant-id',
redirectUri: 'http://localhost:4200'
}
});
}
@NgModule({
imports: [
MsalModule
],
providers: [{
provide: MSAL_INSTANCE,
useFactory: MSALInstanceFactory
}, MsalService]
})
export class AppModule { }
Token Acquisition
This code demonstrates how to log in a user and acquire an access token silently for calling Microsoft Graph API or other APIs.
import { MsalService } from '@azure/msal-angular';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
constructor(private authService: MsalService) {}
login() {
this.authService.loginPopup().subscribe(response => {
console.log('Login successful', response);
}, error => {
console.error('Login failed', error);
});
}
getToken() {
this.authService.acquireTokenSilent({
scopes: ['user.read']
}).subscribe(response => {
console.log('Token acquired', response.accessToken);
}, error => {
console.error('Token acquisition failed', error);
});
}
}
Guarding Routes
This code demonstrates how to protect routes in an Angular application using MsalGuard to ensure that only authenticated users can access certain routes.
import { MsalGuard } from '@azure/msal-angular';
const routes: Routes = [
{ path: 'profile', component: ProfileComponent, canActivate: [MsalGuard] }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
angular-oauth2-oidc is a library for OAuth2 and OpenID Connect (OIDC) authentication in Angular applications. It provides similar functionalities to @azure/msal-angular, such as user authentication, token management, and route protection. However, it is more generic and can be used with various identity providers, not just Microsoft Identity Platform.
oidc-client is a JavaScript library for OpenID Connect (OIDC) and OAuth2 authentication. It can be used in various JavaScript frameworks, including Angular, to handle user authentication and token management. Unlike @azure/msal-angular, it is not specific to Angular and requires more manual setup for integration with Angular applications.
auth0-angular is a library for integrating Auth0 authentication and authorization into Angular applications. It provides similar functionalities to @azure/msal-angular, such as user authentication, token management, and route protection. Auth0 is a third-party identity provider that supports various authentication methods and social logins.
The MSAL for Angular library is a wrapper of the core MSAL.js library which enables Angular (6+) applications to authenticate enterprise users using Microsoft Azure Active Directory (AAD), Microsoft account users (MSA), users using social identity providers like Facebook, Google, LinkedIn etc. and get access to Microsoft Cloud OR Microsoft Graph.
Please note that during the preview we may make changes to the API, internal cache format, and other mechanisms of this library, which you will be required to take along with bug fixes or feature improvements. This may impact your application. For instance, a change to the cache format may impact your users, such as requiring them to sign in again. An API change may require you to update your code. When we provide the General Availability release we will require you to update to the General Availability version within six months, as applications written using a preview version of library may no longer work.
This is an early preview library and we are tracking certain known issues and requests which we plan on addressing. Please watch the Roadmap for details.
The MSAL Angular package is available on NPM:
npm install msal @azure/msal-angular --save
Before using MSAL.js, register an application in Azure AD to get your clientId.
Import MsalModule into app.module.ts. To initialize MSAL module you are required to pass the clientId of your application which you can get from the application registration.
@NgModule({
imports: [
MsalModule.forRoot({
auth: {
clientId: "Your client ID"
}
})
]
})
export class AppModule {}
You can add authentication to secure specific routes in your application by just adding canActivate : [MsalGuard]
to your route definition. It can be added at the parent or child routes.
{ path: 'product', component: ProductComponent, canActivate : [MsalGuard],
children: [
{ path: 'detail/:id', component: ProductDetailComponent }
]
},
{ path: 'myProfile' ,component: MsGraphComponent, canActivate : [MsalGuard] },
When user visits these routes, the library prompts the user to authenticate.
MSAL Angular allows you to add an Http interceptor (MsalInterceptor
) in your app.module.ts as follows. MsalInterceptor will obtain tokens and add them to all your Http requests in API calls except the API endpoints listed as unprotectedResources
.
providers: [
ProductService, {
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true
}
],
Using MsalInterceptor is optional and you can write your own interceptor if you choose to. Alternatively, you can also explicitly acquire tokens using the acquireToken APIs.
MSAL wrapper provides below callbacks for various operations. For all callbacks, you need to inject BroadcastService as a dependency in your component/service.
this.broadcastService.subscribe("msal:loginFailure", payload => {
// do something here
});
this.broadcastService.subscribe("msal:loginSuccess", payload => {
// do something here
});
this.broadcastService.subscribe("msal:acquireTokenSuccess", payload => {
// do something here
});
this.broadcastService.subscribe("msal:acquireTokenFailure", payload => {
// do something here
});
private subscription: Subscription;
this.subscription= this.broadcastService.subscribe("msal:acquireTokenFailure", (payload) => {
});
ngOnDestroy() {
this.broadcastService.getMSALSubject().next(1);
if(this.subscription) {
this.subscription.unsubscribe();
}
}
The wrapper exposes APIs for login, logout, acquiring access token and more.
loginRedirect()
loginPopup()
logOut()
acquireTokenSilent()
- This will try to acquire the token silently. If the scope is not already consented then user will get a callback at msal:acquireTokenFailure
event. User can call either acquireTokenPopup()
or acquireTokenRedirect(
) there to acquire the token interactively.acquireTokenPopup()
acquireTokenRedirect()
getAccount()
Note: Since MSAL Angular wrapper is inheriting from UserAgentApplication of msal-core, all the public APIs of msal-core are still accessible from msal-angular. But it is recommended not to use any of the msal-core APIs like acquireTokenSilent(), acquireTokenPopup(), acquireTokenRedirect() etc from Angular application and use only the APIs which are exposed directly from the msal-angular wrapper itself.
Besides the required clientID, you can optionally pass the following config options to MSAL module during initialization. For example:
@NgModule({
imports: [
MsalModule.forRoot({
auth: {
clientId: 'clientid',
authority: "https://login.microsoftonline.com/common/",
validateAuthority: true,
redirectUri: "http://localhost:4200/",
postLogoutRedirectUri: "http://localhost:4200/",
navigateToLoginRequestUrl: true,
},
cache: {
cacheLocation : "localStorage",
storeAuthStateInCookie: true, // set to true for IE 11
},
framework: {
unprotectedResources: ["https://www.microsoft.com/en-us/"],
protectedResourceMap: new Map(protectedResourceMap)
},
system: {
logger: new Logger(loggerCallback, options)
}
}, {
popUp: !isIE,
consentScopes: [ "user.read", "openid", "profile", "api://a88bb933-319c-41b5-9f04-eff36d985612/access_as_user"],
extraQueryParameters: {}
})
]
})
export class AppModule {}
redirectUri : The redirect URI of your app, where authentication responses can be sent and received by your app. It must exactly match one of the redirect URIs you registered in the portal, except that it must be URL encoded.
Defaults to window.location.href
.
authority : A URL indicating a directory that MSAL can use to obtain tokens.
validateAuthority : Validate the issuer of tokens. Default is true.
cacheLocation : Sets browser storage to either localStorage
or sessionStorage
. Defaults to sessionStorage
.
storeAuthStateInCookie : Stores auth state in a browser cookie instead of local storage. Needs to be set to true when a user is on IE11, which may clear local storage contents when redirecting between websites in different zones. Defaults is false
.
postLogoutRedirectUri : Redirects the user to postLogoutRedirectUri after logout. Defaults is 'redirectUri'.
loadFrameTimeout : The number of milliseconds of inactivity before a token renewal response from AAD should be considered timed out. Default is 6 seconds.
navigateToLoginRequestUrl :Ability to turn off default navigation to start page after login. Default is true. This is used only for redirect flows.
popup : Show login popup or redirect. Default:Redirect
consentScopes : Allows the client to express the desired scopes that should be consented. Scopes can be from multiple resources/endpoints. Passing scope here will only consent it and no access token will be acquired till the time client actually calls the API. This is optional if you are using MSAL for only login(Authentication).
unprotectedResources : Array of URI's. Msal will not attach a token to outgoing requests that have these uri. Defaults to 'null'.
protectedResourceMap : Mapping of resources to scopes {"https://graph.microsoft.com/v1.0/me", ["user.read", "mail.send"]}. Used internally by the MSAL for automatically attaching tokens in webApi calls. This is required only for CORS calls.
export const protectedResourceMap:[string, string[]][]=[ ['https://buildtodoservice.azurewebsites.net/api/todolist',['api://a88bb933-319c-41b5-9f04-eff36d985612/access_as_user']] , ['https://graph.microsoft.com/v1.0/me', ['user.read']] ];
level : Configurable log level. Default value is Info. Passed in options object as the second argument to Logger
.
logger : Callback instance that can be provided by the developer to consume and publish logs in a custom manner. Callback method must follow this signature.
loggerCallback(logLevel, message, piiEnabled) { }
piiLoggingEnabled : PII stands for Personal Identifiable Information. By default, MSAL does not capture or log any PII. By turning on PII, the app takes responsibility for safely handling highly-sensitive data and complying with any regulatory requirements. Passed in options object as the second argument to Logger
.
This flag is to enable/disable logging of PII data. PII logs are never written to default outputs like Console, Logcat or NSLog. Default is set to false.
correlationId : Unique identifier used to map the request with the response. Defaults to RFC4122 version 4 guid (128 bits). Passed in options object as the second argument to Logger
.
The logger definition has the following properties. Please see the config section for more details on their use:
You can enable logging in your app as shown below:
export function loggerCallback(logLevel, message, piiEnabled) {
console.log(message);
}
@NgModule({
imports: [ MsalModule.forRoot({
auth: {
clientId: 'Your client ID',
},
system: {
logger: new Logger(loggerCallback, {
correlationId: '1234',
level: LogLevel.Verbose,
piiLoggingEnabled: true,
}
}
})]
})
By default, you have multi-tenant support since MSAL sets the tenant in the authority to 'common' if it is not specified in the config. This allows any Microsoft account to authenticate to your application. If you are not interested in multi-tenant behavior, you will need to set the authority
config property as shown above.
If you allow multi-tenant authentication, and you do not wish to allow all Microsoft account users to use your application, you must provide your own method of filtering the token issuers to only those tenants who are allowed to login.
Tokens are accessible from Javascript since MSAL is using HTML5 storage. Default storage option is sessionStorage, which keeps the tokens per session. You should ask user to login again for important operations on your app. You should protect your site for XSS. Please check the article here: https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
MSAL will get access tokens using a hidden Iframe for given CORS API endpoints in the config. To make CORS API call, you need to specify your CORS API endpoints as a map in the config.
export const protectedResourceMap:[string, string[]][]= [
['https://buildtodoservice.azurewebsites.net/api/todolist', [ 'api://a88bb933-319c-41b5-9f04-eff36d985612/access_as_user' ]],
['https://graph.microsoft.com/v1.0/me', ['user.read']]
];
@NgModule({
imports: [
MsalModule.forRoot({
auth: {
clientId: 'Your client ID',
},
framework: {
protectedResourceMap : protectedResourceMap
}
})
]
})
In your API project, you need to enable CORS API requests to receive flight requests.
This library supports Internet Explorer 11 with the following configuration:
storeAuthStateInCookie
to true
.popUp
to false
.It is recommended that these properties are set dynamically based on the user's browser.
const isIE =
window.navigator.userAgent.indexOf("MSIE ") > -1 ||
window.navigator.userAgent.indexOf("Trident/") > -1;
MsalModule.forRoot({
// ...
cache: {
storeAuthStateInCookie: ieIE
}
framework: {
popUp: !isIE
}
});
You can find a quickstart and detailed sample under the sample directory.
FAQs for access to our frequently asked questions
Stack Overflow using tag "msal". We highly recommend you ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.
GitHub Issues for reporting a bug or feature requests
User Voice page to provide recommendations and/or feedback
We enthusiastically welcome contributions and feedback. Please read the contributing guide before you begin.
If you want to build the library and run all the unit tests, you can do the following.
First navigate to the root directory of the library(msal-angular) and install the dependencies:
npm install
Then use the following command to build the library and run all the unit tests:
npm run ngcompile
npm run test
This library controls how users sign-in and access services. We recommend you always take the latest version of our library in your app when possible. We use semantic versioning so you can control the risk associated with updating your app. As an example, always downloading the latest minor version number (e.g. x.y.x) ensures you get the latest security and feature enhanements but our API surface remains the same. You can always see the latest version and release notes under the Releases tab of GitHub.
If you find a security issue with our libraries or services please report it to secure@microsoft.com with as much detail as possible. Your submission may be eligible for a bounty through the Microsoft Bounty program. Please do not post security issues to GitHub Issues or any other public site. We will contact you shortly upon receiving the information. We encourage you to get notifications of when security incidents occur by visiting this page and subscribing to Security Advisory Alerts.
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License (the "License");
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
FAQs
Microsoft Authentication Library for Angular
The npm package @azure/msal-angular receives a total of 37,507 weekly downloads. As such, @azure/msal-angular popularity was classified as popular.
We found that @azure/msal-angular demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.