Quickstart: Add sign-in with Microsoft to a web app
In this quickstart, you download and run a code sample that demonstrates an ASP.NET web application that can sign in users with Azure Active Directory (Azure AD) accounts.
See How the sample works for an illustration.
Prerequisites
- An Azure account with an active subscription. Create an account for free.
- Visual Studio 2022
- .NET Framework 4.7.2+
Register and download the app
You have two options to start building your application: automatic or manual configuration.
Automatic configuration
If you want to automatically configure your app and then download the code sample, follow these steps:
- Go to the Azure portal page for app registration.
- Enter a name for your application and select Register.
- Follow the instructions to download and automatically configure your new application in one click.
Manual configuration
If you want to manually configure your application and code sample, use the following procedures.
Step 1: Register your application
- Sign in to the Azure portal.
- If you have access to multiple tenants, use the Directory + subscription filter
in the top menu to switch to the tenant in which you want to register the application.
- Search for and select Azure Active Directory.
- Under Manage, select App registrations > New registration.
- For Name, enter a name for your application. For example, enter ASPNET-Quickstart. Users of your app will see this name, and you can change it later.
- Set the Redirect URI type to Web and value to
https://localhost:44368/
. - Select Register.
- Under Manage, select Authentication.
- In the Implicit grant and hybrid flows section, select ID tokens.
- Select Save.
Step 2: Download the project
Download the ASP.NET code sample
Tip
To avoid errors caused by path length limitations in Windows, we recommend extracting the archive or cloning the repository into a directory near the root of your drive.
Step 3: Run the project
Extract the .zip file to a local folder that's close to the root folder. For example, extract to C:\Azure-Samples.
We recommend extracting the archive into a directory near the root of your drive to avoid errors caused by path length limitations on Windows.
Open the solution in Visual Studio (AppModelv2-WebApp-OpenIDConnect-DotNet.sln).
Depending on the version of Visual Studio, you might need to right-click the project AppModelv2-WebApp-OpenIDConnect-DotNet and then select Restore NuGet packages.
Open the Package Manager Console by selecting View > Other Windows > Package Manager Console. Then run
Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -r
.Edit appsettings.json and replace the parameters
ClientId
,Tenant
, andredirectUri
with:"ClientId" :"Enter_the_Application_Id_here" /> "TenantId": "Enter_the_Tenant_Info_Here" /> "RedirectUri" :"https://localhost:44368/" />
In that code:
Enter_the_Application_Id_here
is the application (client) ID of the app registration that you created earlier. Find the application (client) ID on the app's Overview page in App registrations in the Azure portal.Enter_the_Tenant_Info_Here
is one of the following options:- If your application supports My organization only, replace this value with the directory (tenant) ID or tenant name (for example,
contoso.onmicrosoft.com
). Find the directory (tenant) ID on the app's Overview page in App registrations in the Azure portal. - If your application supports Accounts in any organizational directory, replace this value with
organizations
. - If your application supports All Microsoft account users, replace this value with
common
.
- If your application supports My organization only, replace this value with the directory (tenant) ID or tenant name (for example,
redirectUri
is the Redirect URI you entered earlier in App registrations in the Azure portal.
More information
This section gives an overview of the code required to sign in users. This overview can be useful to understand how the code works, what the main arguments are, and how to add sign-in to an existing ASP.NET application.
How the sample works
OWIN middleware NuGet packages
You can set up the authentication pipeline with cookie-based authentication by using OpenID Connect in ASP.NET with OWIN middleware packages. You can install these packages by running the following commands in Package Manager Console within Visual Studio:
Install-Package Microsoft.Identity.Web.Owin
Install-Package Microsoft.Identity.Web.MicrosoftGraph
Install-Package Microsoft.Owin.Security.Cookies
OWIN startup class
The OWIN middleware uses a startup class that runs when the hosting process starts. In this quickstart, the startup.cs file is in the root folder. The following code shows the parameters that this quickstart uses:
public void Configuration(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
OwinTokenAcquirerFactory factory = TokenAcquirerFactory.GetDefaultInstance<OwinTokenAcquirerFactory>();
app.AddMicrosoftIdentityWebApp(factory);
factory.Services
.Configure<ConfidentialClientApplicationOptions>(options => { options.RedirectUri = "https://localhost:44368/"; })
.AddMicrosoftGraph()
.AddInMemoryTokenCaches();
factory.Build();
}
Where | Description |
---|---|
ClientId |
The application ID from the application registered in the Azure portal. |
Authority |
The security token service (STS) endpoint for the user to authenticate. It's usually https://login.microsoftonline.com/{tenant}/v2.0 for the public cloud. In that URL, {tenant} is the name of your tenant, your tenant ID, or common for a reference to the common endpoint. (The common endpoint is used for multitenant applications.) |
RedirectUri |
The URL where users are sent after authentication against the Microsoft identity platform. |
PostLogoutRedirectUri |
The URL where users are sent after signing off. |
Scope |
The list of scopes being requested, separated by spaces. |
ResponseType |
The request that the response from authentication contains an authorization code and an ID token. |
TokenValidationParameters |
A list of parameters for token validation. In this case, ValidateIssuer is set to false to indicate that it can accept sign-ins from any personal, work, or school account type. |
Notifications |
A list of delegates that can be run on OpenIdConnect messages. |
Authentication challenge
You can force a user to sign in by requesting an authentication challenge in your controller:
public void SignIn()
{
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties{ RedirectUri = "/" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
Tip
Requesting an authentication challenge by using this method is optional. You'd normally use it when you want a view to be accessible from both authenticated and unauthenticated users. Alternatively, you can protect controllers by using the method described in the next section.
Attribute for protecting a controller or a controller actions
You can protect a controller or controller actions by using the [Authorize]
attribute. This attribute restricts access to the controller or actions by allowing only authenticated users to access the actions in the controller. An authentication challenge will then happen automatically when an unauthenticated user tries to access one of the actions or controllers decorated by the [Authorize]
attribute.
Call Microsoft Graph from the controller
You can call Microsoft Graph from the controller by getting the instance of GraphServiceClient using the GetGraphServiceClient
extension method on the controller, like in the following code:
try
{
var me = await this.GetGraphServiceClient().Me.Request().GetAsync();
ViewBag.Username = me.DisplayName;
}
catch (ServiceException graphEx) when (graphEx.InnerException is MicrosoftIdentityWebChallengeUserException)
{
HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
return View();
}
Help and support
If you need help, want to report an issue, or want to learn about your support options, see Help and support for developers.
Next steps
For a complete step-by-step guide on building applications and new features, including a full explanation of this quickstart, try out the ASP.NET tutorial.
The following quickstart uses a ASP.NET Core web app code sample to demonstrate how to sign in users from any Azure Active Directory (Azure AD) organization.
See How the sample works for an illustration.
Prerequisites
Register and download your quickstart application
Step 1: Register your application
- Sign in to the Azure portal.
- If access to multiple tenants is available, use the Directories + subscriptions filter
in the top menu to switch to the tenant in which to register the application.
- Search for and select Azure Active Directory.
- Under Manage, select App registrations > New registration.
- For Name, enter a name for the application. For example, enter AspNetCore-Quickstart. Users of the app will see this name, and can be changed later.
- Set the Redirect URI type to Web and value to
https://localhost:44321/signin-oidc
. - Select Register.
- Under Manage, select Authentication.
- For Front-channel logout URL, enter https://localhost:44321/signout-oidc.
- Under Implicit grant and hybrid flows, select ID tokens.
- Select Save.
- Under Manage, select Certificates & secrets > Client secrets > New client secret.
- Enter a Description, for example
clientsecret1
. - Select In 1 year for the secret's expiration.
- Select Add and immediately record the secret's Value for use in a later step. The secret value is never displayed again and is irretrievable by any other means. Record it in a secure location as you would any password.
Step 2: Download the ASP.NET Core project
Download the ASP.NET Core solution
Step 3: Configure your ASP.NET Core project
Extract the .zip file to a local folder that's close to the root of the disk to avoid errors caused by path length limitations on Windows. For example, extract to C:\Azure-Samples.
Open the solution in the chosen code editor.
In appsettings.json, replace the values of
ClientId
, andTenantId
. The value for the application (client) ID and the directory (tenant) ID, can be found in the app's Overview page on the Azure portal."Domain": "[Enter the domain of your tenant, e.g. contoso.onmicrosoft.com]", "ClientId": "Enter_the_Application_Id_here", "TenantId": "common",
Enter_the_Application_Id_Here
is the application (client) ID for the registered application.- Replace
Enter_the_Tenant_Info_Here
with one of the following:- If the application supports Accounts in this organizational directory only, replace this value with the directory (tenant) ID (a GUID) or tenant name (for example,
contoso.onmicrosoft.com
). The directory (tenant) ID can be found on the app's Overview page. - If the application supports Accounts in any organizational directory, replace this value with
organizations
. - If the application supports All Microsoft account users, leave this value as
common
.
- If the application supports Accounts in this organizational directory only, replace this value with the directory (tenant) ID (a GUID) or tenant name (for example,
- Replace
Enter_the_Client_Secret_Here
with the Client secret that was created and recorded in an earlier step.
For this quickstart, don't change any other values in the appsettings.json file.
Step 4: Build and run the application
Build and run the app in Visual Studio by selecting the Debug menu > Start Debugging, or by pressing the F5 key.
A prompt for credentials will appear, and then a request for consent to the permissions that the app requires. Select Accept on the consent prompt.
After consenting to the requested permissions, the app displays that sign-in has been successful using correct Azure Active Directory credentials. The user's account email address will be displayed in the API result section of the page. This was extracted using the Microsoft Graph API.
More information
This section gives an overview of the code required to sign in users and call the Microsoft Graph API on their behalf. This overview can be useful to understand how the code works, main arguments, and also if you want to add sign-in to an existing ASP.NET Core application and call Microsoft Graph. It uses Microsoft.Identity.Web, which is a wrapper around MSAL.NET.
How the sample works
Startup class
The Microsoft.AspNetCore.Authentication middleware uses a Startup
class that's executed when the hosting process starts:
// Get the scopes from the configuration (appsettings.json)
var initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
public void ConfigureServices(IServiceCollection services)
{
// Add sign-in with Microsoft
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
// Add the possibility of acquiring a token to call a protected web API
.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
// Enables controllers and pages to get GraphServiceClient by dependency injection
// And use an in memory token cache
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
// Enables a UI and controller for sign in and sign out.
services.AddRazorPages()
.AddMicrosoftIdentityUI();
}
The AddAuthentication()
method configures the service to add cookie-based authentication. This authentication is used in browser scenarios and to set the challenge to OpenID Connect.
The line that contains .AddMicrosoftIdentityWebApp
adds Microsoft identity platform authentication to the application. The application is then configured to sign in users based on the following information in the AzureAD
section of the appsettings.json configuration file:
appsettings.json key | Description |
---|---|
ClientId |
Application (client) ID of the application registered in the Azure portal. |
Instance |
Security token service (STS) endpoint for the user to authenticate. This value is typically https://login.microsoftonline.com/ , indicating the Azure public cloud. |
TenantId |
Name of your tenant or the tenant ID (a GUID), or common to sign in users with work or school accounts or Microsoft personal accounts. |
The EnableTokenAcquisitionToCallDownstreamApi
method enables the application to acquire a token to call protected web APIs. AddMicrosoftGraph
enables the controllers or Razor pages to benefit directly the GraphServiceClient
(by dependency injection) and the AddInMemoryTokenCaches
methods enables your app to benefit from a token cache.
The Configure()
method contains two important methods, app.UseAuthentication()
and app.UseAuthorization()
, that enable their named functionality. Also in the Configure()
method, you must register Microsoft Identity Web routes with at least one call to endpoints.MapControllerRoute()
or a call to endpoints.MapControllers()
:
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
Protect a controller or a controller's method
The controller or its methods can be protected by applying the [Authorize]
attribute to the controller's class or one or more of its methods. This [Authorize]
attribute restricts access by allowing only authenticated users. If the user isn't already authenticated, an authentication challenge can be started to access the controller. In this quickstart, the scopes are read from the configuration file:
[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
public async Task<IActionResult> Index()
{
var user = await _graphServiceClient.Me.Request().GetAsync();
ViewData["ApiResult"] = user.DisplayName;
return View();
}
Help and support
If you need help, want to report an issue, or want to learn about your support options, see Help and support for developers.
Next steps
The following GitHub repository contains the ASP.NET Core code sample referenced in this quickstart and more samples that show how to achieve the following:
- Add authentication to a new ASP.NET Core web application.
- Call Microsoft Graph, other Microsoft APIs, or your own web APIs.
- Add authorization.
- Sign in users in national clouds or with social identities.
In this quickstart, you download and run a code sample that demonstrates how a Node.js web app can sign in users by using the authorization code flow. The code sample also demonstrates how to get an access token to call the Microsoft Graph API.
See How the sample works for an illustration.
This quickstart uses the Microsoft Authentication Library for Node.js (MSAL Node) with the authorization code flow.
Prerequisites
- An Azure subscription. Create an Azure subscription for free.
- Node.js
- Visual Studio Code or another code editor
Register and download your quickstart application
Step 1: Register your application
- Sign in to the Azure portal.
- If you have access to multiple tenants, use the Directories + subscriptions filter
in the top menu to switch to the tenant in which you want to register the application.
- Under Manage, select App registrations > New registration.
- Enter a Name for your application. Users of your app might see this name, and you can change it later.
- Under Supported account types, select Accounts in this organizational directory only.
- Set the Redirect URI type to Web and value to
http://localhost:3000/auth/redirect
. - Select Register.
- On the app Overview page, note the Application (client) ID value for later use.
- Under Manage, select Certificates & secrets > Client secrets > New client secret. Leave the description blank and default expiration, and then select Add.
- Note the value of Client secret for later use.
Step 2: Download the project
To run the project with a web server by using Node.js, download the core project files.
Step 3: Configure your Node app
Extract the project, open the ms-identity-node-main folder, and then open the .env file under the App folder. Replace the values above as follows:
Variable | Description | Example(s) |
---|---|---|
Enter_the_Cloud_Instance_Id_Here |
The Azure cloud instance in which your application is registered | https://login.microsoftonline.com/ (include the trailing forward-slash) |
Enter_the_Tenant_Info_here |
Tenant ID or Primary domain | contoso.microsoft.com or cbe899ec-5f5c-4efe-b7a0-599505d3d54f |
Enter_the_Application_Id_Here |
Client ID of the application you registered | cbe899ec-5f5c-4efe-b7a0-599505d3d54f |
Enter_the_Client_Secret_Here |
Client secret of the application you registered | WxvhStRfDXoEiZQj1qCy |
Enter_the_Graph_Endpoint_Here |
The Microsoft Graph API cloud instance that your app will call | https://graph.microsoft.com/ (include the trailing forward-slash) |
Enter_the_Express_Session_Secret_Here |
A random string of characters used to sign the Express session cookie | WxvhStRfDXoEiZQj1qCy |
Your file should look similar to below:
CLOUD_INSTANCE=https://login.microsoftonline.com/
TENANT_ID=cbe899ec-5f5c-4efe-b7a0-599505d3d54f
CLIENT_ID=fa29b4c9-7675-4b61-8a0a-bf7b2b4fda91
CLIENT_SECRET=WxvhStRfDXoEiZQj1qCy
REDIRECT_URI=http://localhost:3000/auth/redirect
POST_LOGOUT_REDIRECT_URI=http://localhost:3000
GRAPH_API_ENDPOINT=https://graph.microsoft.com/
EXPRESS_SESSION_SECRET=6DP6v09eLiW7f1E65B8k
Step 4: Run the project
Run the project by using Node.js.
To start the server, run the following commands from within the project directory:
cd App npm install npm start
Go to
http://localhost:3000/
.Select Sign in to start the sign-in process.
The first time you sign in, you're prompted to provide your consent to allow the application to sign you in and access your profile. After you're signed in successfully, you'll be redirected back to the application home page.
More information
How the sample works
The sample hosts a web server on localhost, port 3000. When a web browser accesses this address, the app renders the home page. Once the user selects Sign in, the app redirects the browser to Azure AD sign-in screen, via the URL generated by the MSAL Node library. After user consents, the browser redirects the user back to the application home page, along with an ID and access token.
MSAL Node
The MSAL Node library signs in users and requests the tokens that are used to access an API that's protected by Microsoft identity platform. You can download the latest version by using the Node.js Package Manager (npm):
npm install @azure/msal-node
Next steps
Learn more about the web app scenario that the Microsoft identity platform supports:
In this quickstart, you download and run a code sample that demonstrates how a Java web application can sign in users and call the Microsoft Graph API. Users from any Azure Active Directory (Azure AD) organization can sign in to the application.
See How the sample works for an illustration.
Prerequisites
To run this sample, you need:
- Java Development Kit (JDK) 8 or later.
- Maven.
Register and download your quickstart app
There are two ways to start your quickstart application: express (option 1) and manual (option 2).
Option 1: Register and automatically configure your app, and then download the code sample
- Go to the Azure portal - App registrations quickstart experience.
- Enter a name for your application, and then select Register.
- Follow the instructions in the portal's quickstart experience to download the automatically configured application code.
Option 2: Register and manually configure your application and code sample
Step 1: Register your application
To register your application and manually add the app's registration information to it, follow these steps:
- Sign in to the Azure portal.
- If you have access to multiple tenants, use the Directories + subscriptions filter
in the top menu to switch to the tenant in which you want to register the application.
- Search for and select Azure Active Directory.
- Under Manage, select App registrations.
- Select New registration.
- Enter a Name for your application, for example java-webapp. Users of your app might see this name. You can change it later.
- Select Register.
- On the Overview page, note the Application (client) ID and the Directory (tenant) ID. You'll need these values later.
- Under Manage, select Authentication.
- Select Add a platform > Web.
- In the Redirect URIs section, enter
https://localhost:8443/msal4jsample/secure/aad
. - Select Configure.
- In the Web section, under Redirect URIs, enter
https://localhost:8443/msal4jsample/graph/me
as a second redirect URI. - Under Manage, select Certificates & secrets. In the Client secrets section, select New client secret.
- Enter a key description (for example, app secret), leave the default expiration, and select Add.
- Note the Value of the client secret. You'll need it later.
Step 2: Download the code sample
Step 3: Configure the code sample
Extract the zip file to a local folder.
Optional. If you use an integrated development environment, open the sample in that environment.
Open the application.properties file. You can find it in the src/main/resources/ folder. Replace the values in the fields
aad.clientId
,aad.authority
, andaad.secretKey
with the application ID, tenant ID, and client secret values, respectively. Here's what it should look like:aad.clientId=Enter_the_Application_Id_here aad.authority=https://login.microsoftonline.com/Enter_the_Tenant_Info_Here/ aad.secretKey=Enter_the_Client_Secret_Here aad.redirectUriSignin=https://localhost:8443/msal4jsample/secure/aad aad.redirectUriGraph=https://localhost:8443/msal4jsample/graph/me aad.msGraphEndpointHost="https://graph.microsoft.com/"
In the previous code:
Enter_the_Application_Id_here
is the application ID for the application you registered.Enter_the_Client_Secret_Here
is the Client Secret you created in Certificates & secrets for the application you registered.Enter_the_Tenant_Info_Here
is the Directory (tenant) ID value of the application you registered.
- To use HTTPS with localhost, provide the
server.ssl.key
properties. To generate a self-signed certificate, use the keytool utility (included in JRE).
Here's an example:
keytool -genkeypair -alias testCert -keyalg RSA -storetype PKCS12 -keystore keystore.p12 -storepass password
server.ssl.key-store-type=PKCS12
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=password
server.ssl.key-alias=testCert
- Put the generated keystore file in the resources folder.
Step 4: Run the code sample
To run the project, take one of these steps:
- Run it directly from your IDE by using the embedded Spring Boot server.
- Package it to a WAR file by using Maven, and then deploy it to a J2EE container solution like Apache Tomcat.
Running the project from an IDE
To run the web application from an IDE, select run, and then go to the home page of the project. For this sample, the standard home page URL is https://localhost:8443.
On the front page, select the Login button to redirect users to Azure Active Directory and prompt them for credentials.
After users are authenticated, they're redirected to
https://localhost:8443/msal4jsample/secure/aad
. They're now signed in, and the page will show information about the user account. The sample UI has these buttons:- Sign Out: Signs the current user out of the application and redirects that user to the home page.
- Show User Info: Acquires a token for Microsoft Graph and calls Microsoft Graph with a request that contains the token, which returns basic information about the signed-in user.
Running the project from Tomcat
If you want to deploy the web sample to Tomcat, make a couple changes to the source code.
Open ms-identity-java-webapp/src/main/java/com.microsoft.azure.msalwebsample/MsalWebSampleApplication.
Delete all source code and replace it with this code:
package com.microsoft.azure.msalwebsample; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication public class MsalWebSampleApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(MsalWebSampleApplication.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(MsalWebSampleApplication.class); } }
Tomcat's default HTTP port is 8080, but you need an HTTPS connection over port 8443. To configure this setting:
Go to tomcat/conf/server.xml.
Search for the
<connector>
tag, and replace the existing connector with this connector:<Connector protocol="org.apache.coyote.http11.Http11NioProtocol" port="8443" maxThreads="200" scheme="https" secure="true" SSLEnabled="true" keystoreFile="C:/Path/To/Keystore/File/keystore.p12" keystorePass="KeystorePassword" clientAuth="false" sslProtocol="TLS"/>
Open a Command Prompt window. Go to the root folder of this sample (where the pom.xml file is located), and run
mvn package
to build the project.- This command will generate a msal-web-sample-0.1.0.war file in your /targets directory.
- Rename this file to msal4jsample.war.
- Deploy the WAR file by using Tomcat or any other J2EE container solution.
- To deploy the msal4jsample.war file, copy it to the /webapps/ directory in your Tomcat installation, and then start the Tomcat server.
After the file is deployed, go to https://localhost:8443/msal4jsample by using a browser.
Important
This quickstart application uses a client secret to identify itself as a confidential client. Because the client secret is added as plain text to your project files, for security reasons we recommend that you use a certificate instead of a client secret before using the application in a production environment. For more information on how to use a certificate, see Certificate credentials for application authentication.
More information
How the sample works
Get MSAL
MSAL for Java (MSAL4J) is the Java library used to sign in users and request tokens that are used to access an API that's protected by the Microsoft identity platform.
Add MSAL4J to your application by using Maven or Gradle to manage your dependencies by making the following changes to the application's pom.xml (Maven) or build.gradle (Gradle) file.
In pom.xml:
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>msal4j</artifactId>
<version>1.0.0</version>
</dependency>
In build.gradle:
compile group: 'com.microsoft.azure', name: 'msal4j', version: '1.0.0'
Initialize MSAL
Add a reference to MSAL for Java by adding the following code at the start of the file where you'll be using MSAL4J:
import com.microsoft.aad.msal4j.*;
Help and support
If you need help, want to report an issue, or want to learn about your support options, see Help and support for developers.
Next steps
For a more in-depth discussion of building web apps that sign in users on the Microsoft identity platform, see the multipart scenario series:
In this quickstart, you download and run a code sample that demonstrates how a Python web application can sign in users and call the Microsoft Graph API. Users with a personal Microsoft Account or an account in any Azure Active Directory (Azure AD) organization can sign into the application.
The following diagram displays how the sample app works:
- The application uses the
identity
package to obtain an access token from the Microsoft Identity platform. - The access token is used as a bearer token to authenticate the user when calling the Microsoft Graph API.
Prerequisites
- An Azure account with an active subscription. Create an account for free.
- An Azure Active Directory (Azure AD) tenant. For more information on how to get an Azure AD tenant, see how to get an Azure AD tenant.
- Python 3.7+
Step 1: Register your application
Follow these steps to register your application in the Azure portal:
- Sign in to the Azure portal.
- If you have access to multiple tenants, use the Directory + subscription filter
in the top menu to select the tenant in which you want to register an application.
- Navigate to the portal's App registrations page, and select New registration.
- Enter a Name for your application, for example python-webapp.
- Under Supported account types, select Accounts in any organizational directory and personal Microsoft accounts.
- Under Redirect URIs, select Web for the platform.
- Enter a redirect URI of
http://localhost:5000/getAToken
. This can be changed later. - Select Register.
Step 2: Add a client secret
- On the app Overview page, note the Application (client) ID value for later use.
- Under Manage, select the Certificates & secrets and from the Client secrets section, select New client secret.
- Enter a description for the client secret, leave the default expiration, and select Add.
- Save the Value of the Client Secret in a safe location. You'll need it to configure the code, and you can't retrieve it later.
Step 3: Add a scope
- Under Manage, select API permissions > Add a permission.
- Ensure that the Microsoft APIs tab is selected.
- From the Commonly used Microsoft APIs section, select Microsoft Graph.
- From the Delegated permissions section, ensure that User.ReadBasic.All is selected. Use the search box if necessary.
- Select Add permissions.
Step 4: Download the sample app
Download the Python code sample or clone the repository:
git clone https://github.com/Azure-Samples/ms-identity-python-webapp.git
You can also use an integrated development environment to open the folder.
Step 5: Configure the sample app
Go to the application folder.
Create an .env file in the root folder of the project using .env.sample as a guide.
CLIENT_ID=<client id> CLIENT_SECRET=<client secret> # The AUTHORITY variable expects a full authority URL. # # If you are using an AAD tenent, configure it as # "https://login.microsoftonline.com/TENANT_GUID" # or "https://login.microsoftonline.com/subdomain.onmicrosoft.com". # # If you are using a CIAM tenant, configure it as "https://subdomain.ciamlogin.com" # # Alternatively, leave it undefined if you are building a multi-tenant app in world-wide cloud #AUTHORITY=<authority url>
- Set the value of
CLIENT_ID
to the Application (client) ID for the registered application, available on the overview page. - Set the value of
CLIENT_SECRET
to the client secret you created in Certificates & Secrets for the registered application. - Set the value of
AUTHORITY
to a URL that includes Directory (tenant) ID of the registered application. That ID is also available on the overview page.
The environment variables are referenced in app_config.py, and are kept in a separate .env file to keep them out of source control. The provided .gitignore file prevents the .env file from being checked in.
- Set the value of
Step 6: Run the sample app
Create a virtual environment for the app:
py -m venv .venv .venv\scripts\activate
Install the requirements using
pip
:python3 -m pip install -r requirements.txt
Run the app from the command line, specifying the host and port to match the redirect URI:
python3 -m flask run --debug --host=localhost --port=5000
Important
This quickstart application uses a client secret to identify itself as confidential client. Because the client secret is added as a plain-text to your project files, for security reasons, it is recommended that you use a certificate instead of a client secret before considering the application as production application. For more information on how to use a certificate, see these instructions.
Help and support
If you need help, want to report an issue, or want to learn about your support options, see Help and support for developers.
Next steps
Learn more about web apps that sign in users in our multi-part scenario series.
Feedback
Submit and view feedback for