A single page application (SPA) calling a Web API. Authentication is done with Azure AD B2C by leveraging MSAL.js
page_type: sample description: "A sample demonstrating how to use the Microsoft Authentication Library for JavaScript to get an access token and call an API secured by Azure AD B2C." languages: - javascript products: - azure-active-directory-b2c
This simple sample demonstrates how to use the Microsoft Authentication Library for JavaScript (msal.js) to get an access token and call an API secured by Azure AD B2C.
:warning: Silent renewing of access tokens is not supported by all social identity providers.
A quickstart guide covering this sample can be found here. A more detailed tutorial covering this sample can be found here.
:information_source: See here a new B2C single-page application sample using MSAL.js 2.x authorization code flow with PKCE.
| File/folder | Description | |-------------------|--------------------------------------------| |
JavaScriptSPA| Contains sample source files. | |
authPopup.js| Main authentication logic resides here (using Popup flow). | |
authRedirect.js| Use this instead of
authPopup.jsfor authentication with redirect flow. | |
authConfig.js| Contains configuration parameters for the sample. | |
api.js| Provides a helper function for calling the web API. | |
apiConfig.js| Contains API endpoint and scope. | |
ui.js| Contains UI logic. | |
policies.js| Contains policies and authority strings. | |
index.html| Contains the UI of the sample. | |
.gitignore| Defines what to ignore at commit time. | |
CHANGELOG.md| List of changes to the sample. | |
CODE_OF_CONDUCT.md| Code of Conduct information. | |
CONTRIBUTING.md| Guidelines for contributing to the sample. | |
LICENSE| The license for the sample. | |
package.json| Package manifest for npm. | |
README.md| This README file. | |
SECURITY.md| Security disclosures. | |
server.js| Implements a simple Node server to serve index.html. |
There are two ways to run this sample:
This sample demonstrates how to sign in or sign up for an account at "Fabrikam B2C" - the demo environment for this sample. Once signed-in, clicking on the Call Web API button shows the display name you used when you created your account.
From your shell or command line:
git clone https://github.com/Azure-Samples/active-directory-b2c-javascript-msal-singlepageapp.git
Make sure you've installed Node.
From your shell or command line:
cd active-directory-b2c-javascript-msal-singlepageapp npm install && npm update npm start
The console window shows the port number for the web application
Listening on port 6420...
You can visit
http://localhost:6420and perform the following actions:
In the previous section, you learned how to run the sample application using the demo environment. In this section, you'll learn how to configure this single page application sample and the related Node.js Web API with Azure AD B2C sample to work with your own Azure AD B2C Tenant. This will be covered in two parts.
Follow the instructions on the Node.js Web API with Azure AD B2C sample. Once you are done, you should have a Node.js web API running on the port 5000. While it runs, continue with Part II below.
Next, you need to register your single page application in your B2C tenant.
Provide the following values for the Single Page Application registration:
My Test SPA. You will identify this application by its Name whenever working in the Azure portal.
http://localhost:6420. This sample provided in this repository is configured to run on port 6420.
demo.readand hit Save.
Now in the sample code, you can replace the single page application's demo environment configuration with your own tenant.
authConfig.jsfile.
clientIdand replace the value with the Application ID for the single page application you registered earlier, for example the Application ID found in
My Test SPAapplication in the Azure portal.
policies.jsfile.
namesand
authoritiesand replacing, as appropriate, with the names of the policies you created in Step 2, and
fabrikamb2c.onmicrosoft.comby the name of your Azure AD B2C tenant, for example
https://.b2clogin.com/.onmicrosoft.com/
apiConfig.jsfile.
b2cScopesreplacing the URL by the scope URL you created for the Web API, e.g.
b2cScopes: ["https://.onmicrosoft.com/helloapi/demo.read"]
webApireplacing the current URL by the URL where you deployed your Web API in Step 4, e.g.
webApi: http://localhost:5000/hello
Your resulting code should look as follows:
const msalConfig = { auth: { clientId: "e760cab2-b9a1-4c0d-86fb-ff7084abd902", authority: b2cPolicies.authorities.signUpSignIn.authority, validateAuthority: false }, cache: { cacheLocation: "localStorage", storeAuthStateInCookie: true } };const loginRequest = { scopes: ["openid", "profile"], };
const tokenRequest = { scopes: apiConfig.b2cScopes // i.e. ["https://fabrikamb2c.onmicrosoft.com/helloapi/demo.read"] };
const b2cPolicies = { names: { signUpSignIn: "b2c_1_susi", forgotPassword: "b2c_1_reset", editProfile: "b2c_1_edit_profile" }, authorities: { signUpSignIn: { authority: "https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/b2c_1_susi", }, forgotPassword: { authority: "https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/b2c_1_reset", }, editProfile: { authority: "https://fabrikamb2c.b2clogin.com/fabrikamb2c.onmicrosoft.com/b2c_1_edit_profile" } }, }
const apiConfig = { b2cScopes: ["https://fabrikamb2c.onmicrosoft.com/helloapi/demo.read"], webApi: "https://fabrikamb2chello.azurewebsites.net/hello" };
Install the node dependencies if this is your first time running the app (e.g. if you skipped running in the demo environment):
cd active-directory-b2c-javascript-msal-singlepageapp npm install && npm update
Run the Web application:
npm start
Go to
http://localhost:6420.
Click the login button at the top of the application screen. The sample works exactly in the same way regardless of the account type you choose, apart from some visual differences in the authentication and consent experience. Upon successful sign in, the application screen will show buttons that allow you to call an API and sign out.
Click on the Call Web API and see the textual representation of the JSON object that is returned. Make sure your Node.js Web API sample is still running on port 5000.
Sign out by clicking the Logout button.
:thought_balloon: Consider taking a moment to share your experience with us.
The MSAL.js library allows you to pass a login_hint parameter in the AuthenticationParameters object, using the
loginHintattribute.
const loginRequest = { scopes: ["openid", "profile"], loginHint: "[email protected]" };
You can pass any custom query string parameter in the AuthenticationParameters object, using the
extraQueryParametersattribute. Following sample sets the
campaignIdthat can be used in the Azure AD B2C UI, and the ui_locales set to es (Spanish).
const loginRequest = { scopes: ["openid", "profile"], extraQueryParameters: { campaignId: 'hawaii', ui_locales: 'es' } };
For more information on Azure B2C, see:
We use StackOverflow with the msal and azure-ad-b2c tags to provide support. We highly recommend you ask your questions on StackOverflow first and browse existing issues to see if someone has asked your question before. Make sure that your questions or comments are tagged with [msal.js].
If you find and bug or have a feature request, please raise the issue on GitHub Issues.
To provide a recommendation, visit our Feedback Forum.
If you'd like to contribute to this sample, see CONTRIBUTING.MD.
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.