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

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:

  1. Go to the Azure portal page for app registration.
  2. Enter a name for your application and select Register.
  3. 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

  1. Sign in to the Azure portal.
  2. 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.
  3. Search for and select Azure Active Directory.
  4. Under Manage, select App registrations > New registration.
  5. 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.
  6. Set the Redirect URI type to Web and value to https://localhost:44368/.
  7. Select Register.
  8. Under Manage, select Authentication.
  9. In the Implicit grant and hybrid flows section, select ID tokens.
  10. 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

  1. 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.

  2. Open the solution in Visual Studio (AppModelv2-WebApp-OpenIDConnect-DotNet.sln).

  3. 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.

  4. Open the Package Manager Console by selecting View > Other Windows > Package Manager Console. Then run Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -r.

  5. Edit Web.config and replace the parameters ClientId, Tenant, and redirectUri with:

    <add key="ClientId" value="Enter_the_Application_Id_here" />
    <add key="Tenant" value="Enter_the_Tenant_Info_Here" />
    <add key="redirectUri" value="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.
    • 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

Diagram of the interaction between the web browser, the web app, and the Microsoft identity platform in the sample app.

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.Owin.Security.OpenIdConnect
Install-Package Microsoft.Owin.Security.Cookies
Install-Package Microsoft.Owin.Host.SystemWeb

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());
    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            // Sets the client ID, authority, and redirect URI as obtained from Web.config
            ClientId = clientId,
            Authority = authority,
            RedirectUri = redirectUri,
            // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it's using the home page
            PostLogoutRedirectUri = redirectUri,
            Scope = OpenIdConnectScope.OpenIdProfile,
            // ResponseType is set to request the code id_token, which contains basic information about the signed-in user
            ResponseType = OpenIdConnectResponseType.CodeIdToken,
            // ValidateIssuer set to false to allow personal and work accounts from any organization to sign in to your application
            // To only allow users from a single organization, set ValidateIssuer to true and the 'tenant' setting in Web.config to the tenant name
            // To allow users from only a list of specific organizations, set ValidateIssuer to true and use the ValidIssuers parameter
            TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = false // Simplification (see note below)
            },
            // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to the OnAuthenticationFailed method
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = OnAuthenticationFailed
            }
        }
    );
}
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.

Note

Setting ValidateIssuer = false is a simplification for this quickstart. In real applications, validate the issuer. See the samples to understand how to do that.

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.

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.

In this quickstart, you download and run a code sample that demonstrates how an ASP.NET Core web app can 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

  1. Sign in to the Azure portal.
  2. 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.
  3. Search for and select Azure Active Directory.
  4. Under Manage, select App registrations > New registration.
  5. For Name, enter a name for your application. For example, enter AspNetCore-Quickstart. Users of your app will see this name, and you can change it later.
  6. Set the Redirect URI type to Web and value to https://localhost:44321/signin-oidc.
  7. Select Register.
  8. Under Manage, select Authentication.
  9. For Front-channel logout URL, enter https://localhost:44321/signout-oidc.
  10. Under Implicit grant and hybrid flows, select ID tokens.
  11. Select Save.
  12. Under Manage, select Certificates & secrets > Client secrets > New client secret.
  13. Enter a Description, for example clientsecret1.
  14. Select In 1 year for the secret's expiration.
  15. 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

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: Configure your ASP.NET Core project

  1. Extract the .zip archive into a local folder near the root of your drive. For example, extract into 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.

  2. Open the solution in Visual Studio 2019.

  3. Open the appsettings.json file and modify the following code:

    "Domain": "[Enter the domain of your tenant, e.g. contoso.onmicrosoft.com]",
    "ClientId": "Enter_the_Application_Id_here",
    "TenantId": "common",
    
    • Replace Enter_the_Application_Id_here with the application (client) ID of the application that you registered in the Azure portal. You can find the Application (client) ID value on the app's Overview page.
    • Replace common with one of the following:
      • If your application supports Accounts in this organizational directory only, replace this value with the directory (tenant) ID (a GUID) or the tenant name (for example, contoso.onmicrosoft.com). You can find the Directory (tenant) ID value on the app's Overview page.
      • If your application supports Accounts in any organizational directory, replace this value with organizations.
      • If your application supports All Microsoft account users, leave this value as common.
    • Replace Enter_the_Client_Secret_Here with the Client secret you 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.

You're prompted for your credentials, and then asked to consent to the permissions that your app requires. Select Accept on the consent prompt.

Screenshot of the consent dialog box, showing the permissions that the app is requesting from the user.

After consenting to the requested permissions, the app displays that you've successfully logged in using your Azure Active Directory credentials, and you'll see your email address in the "Api result" section of the page. This was extracted using Microsoft Graph.

Web browser displaying the running web app and the user signed in

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

Diagram of the interaction between the web browser, the web app, and the Microsoft identity platform in the sample app.

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 your 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 your application to acquire a token to call protected web APIs. AddMicrosoftGraph enables your 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

You can protect a controller or its methods 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 GitHub repo that contains the ASP.NET Core code sample referenced in this quickstart includes instructions and more code samples that show you how to:

  • 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

Register and download your quickstart application

Step 1: Register your application

  1. Sign in to the Azure portal.
  2. 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.
  3. Under Manage, select App registrations > New registration.
  4. Enter a Name for your application. Users of your app might see this name, and you can change it later.
  5. Under Supported account types, select Accounts in this organizational directory only.
  6. Set the Redirect URI type to Web and value to http://localhost:3000/auth/redirect.
  7. Select Register.
  8. On the app Overview page, note the Application (client) ID value for later use.
  9. Under Manage, select Certificates & secrets > Client secrets > New client secret. Leave the description blank and default expiration, and then select Add.
  10. 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.

  1. To start the server, run the following commands from within the project directory:

    cd App
    npm install
    npm start
    
  2. Go to http://localhost:3000/.

  3. 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 to set up OpenID Connect authentication in a web application built using Node.js with Express. The sample is designed to run on any platform.

Prerequisites

Register your application

  1. Sign in to the Azure portal.

  2. 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.

  3. Search for and select Azure Active Directory.

  4. Under Manage, select App registrations > New registration.

  5. Enter a Name for your application, for example MyWebApp. Users of your app might see this name, and you can change it later.

  6. In the Supported account types section, select Accounts in any organizational directory and personal Microsoft accounts (e.g. Skype, Xbox, Outlook.com).

    If there are more than one redirect URIs, add these from the Authentication tab later after the app has been successfully created.

  7. Select Register to create the app.

  8. On the app's Overview page, find the Application (client) ID value and record it for later. You'll need this value to configure the application later in this project.

  9. Under Manage, select Authentication.

  10. Select Add a platform > Web.

  11. In the Redirect URIs section, enter http://localhost:3000/auth/openid/return.

  12. Enter a Front-channel logout URL https://localhost:3000.

  13. In the Implicit grant and hybrid flows section, select ID tokens as this sample requires the Implicit grant flow to be enabled to sign-in the user.

  14. Select Configure.

  15. Under Manage, select Certificates & secrets > Client secrets > New client secret.

  16. Enter a key description (for instance app secret).

  17. Select a key duration of either In 1 year, In 2 years, or Never Expires.

  18. Select Add. The key value will be displayed. Copy the key value and save it in a safe location for later use.

Download the sample application and modules

Next, clone the sample repo and install the NPM modules.

From your shell or command line:

$ git clone git@github.com:AzureADQuickStarts/AppModelv2-WebApp-OpenIDConnect-nodejs.git 

or

$ git clone https://github.com/AzureADQuickStarts/AppModelv2-WebApp-OpenIDConnect-nodejs.git

From the project root directory, run the command:

$ npm install

Configure the application

Provide the parameters in exports.creds in config.js as instructed.

  • Update <tenant_name> in exports.identityMetadata with the Azure AD tenant name of the format *.onmicrosoft.com.
  • Update exports.clientID with the Application ID noted from app registration.
  • Update exports.clientSecret with the Application secret noted from app registration.
  • Update exports.redirectUrl with the Redirect URI noted from app registration.

Optional configuration for production apps:

  • Update exports.destroySessionUrl in config.js, if you want to use a different post_logout_redirect_uri.

  • Set exports.useMongoDBSessionStore in config.js to true, if you want to use mongoDB or other compatible session stores. The default session store in this sample is express-session. The default session store isn't suitable for production.

  • Update exports.databaseUri, if you want to use mongoDB session store and a different database URI.

  • Update exports.mongoDBSessionMaxAge. Here you can specify how long you want to keep a session in mongoDB. The unit is second(s).

Build and run the application

Start mongoDB service. If you're using mongoDB session store in this app, you have to install mongoDB and start the service first. If you're using the default session store, you can skip this step.

Run the app using the following command from your command line.

$ node app.js

Is the server output hard to understand?: We use bunyan for logging in this sample. The console won't make much sense to you unless you also install bunyan and run the server like above but pipe it through the bunyan binary:

$ npm install -g bunyan

$ node app.js | bunyan

You're done!

You'll have a server successfully running on http://localhost:3000.

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 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:

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

  1. Go to the Azure portal - App registrations quickstart experience.
  2. Enter a name for your application, and then select Register.
  3. 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:

  1. Sign in to the Azure portal.
  2. 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.
  3. Search for and select Azure Active Directory.
  4. Under Manage, select App registrations.
  5. Select New registration.
  6. Enter a Name for your application, for example java-webapp. Users of your app might see this name. You can change it later.
  7. Select Register.
  8. On the Overview page, note the Application (client) ID and the Directory (tenant) ID. You'll need these values later.
  9. Under Manage, select Authentication.
  10. Select Add a platform > Web.
  11. In the Redirect URIs section, enter https://localhost:8443/msal4jsample/secure/aad.
  12. Select Configure.
  13. In the Web section, under Redirect URIs, enter https://localhost:8443/msal4jsample/graph/me as a second redirect URI.
  14. Under Manage, select Certificates & secrets. In the Client secrets section, select New client secret.
  15. Enter a key description (for example, app secret), leave the default expiration, and select Add.
  16. Note the Value of the client secret. You'll need it later.

Step 2: Download the code sample

Download the code sample

Step 3: Configure the code sample

  1. Extract the zip file to a local folder.

  2. Optional. If you use an integrated development environment, open the sample in that environment.

  3. 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, and aad.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.
  1. 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
  1. 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.

  1. On the front page, select the Login button to redirect users to Azure Active Directory and prompt them for credentials.

  2. 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.

  1. 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);
        }
       }
      
  2. 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"/>
      
  3. 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.
  4. 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

Diagram that shows how the sample app generated by this quickstart 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 get an access token to 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.

See How the sample works for an illustration.

Prerequisites

Register and download your quickstart app

You have two options to start your quickstart application: express (Option 1), and manual (Option 2)

Option 1: Register and auto configure your app and then download your code sample

  1. Go to the Azure portal - App registrations quickstart experience.
  2. Enter a name for your application and select Register.
  3. Follow the instructions to download and automatically configure your new application.

Option 2: Register and manually configure your application and code sample

Step 1: Register your application

To register your application and add the app's registration information to your solution manually, follow these steps:

  1. Sign in to the Azure portal.
  2. 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.
  3. Under Manage, select App registrations > New registration.
  4. Enter a Name for your application, for example python-webapp . Users of your app might see this name, and you can change it later.
  5. Under Supported account types, select Accounts in any organizational directory and personal Microsoft accounts.
  6. Select Register.
  7. On the app Overview page, note the Application (client) ID value for later use.
  8. Under Manage, select Authentication.
  9. Select Add a platform > Web.
  10. Add http://localhost:5000/getAToken as Redirect URIs.
  11. Select Configure.
  12. Under Manage, select the Certificates & secrets and from the Client secrets section, select New client secret.
  13. Type a key description (for instance app secret), leave the default expiration, and select Add.
  14. Note the Value of the Client Secret for later use.
  15. Under Manage, select API permissions > Add a permission.
  16. Ensure that the Microsoft APIs tab is selected.
  17. From the Commonly used Microsoft APIs section, select Microsoft Graph.
  18. From the Delegated permissions section, ensure that the right permissions are checked: User.ReadBasic.All. Use the search box if necessary.
  19. Select the Add permissions button.

Step 2: Download your project

Download the Code Sample

Step 3: Configure the Application

  1. Extract the zip file to a local folder closer to the root folder - for example, C:\Azure-Samples
  2. If you use an integrated development environment, open the sample in your favorite IDE (optional).
  3. Open the app_config.py file, which can be found in the root folder and replace with the following code snippet:
CLIENT_ID = "Enter_the_Application_Id_here"
CLIENT_SECRET = "Enter_the_Client_Secret_Here"
AUTHORITY = "https://login.microsoftonline.com/Enter_the_Tenant_Name_Here"

Where:

  • 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_Name_Here - is the Directory (tenant) ID value of the application you registered.

Step 4: Run the code sample

  1. You will need to install MSAL Python library, Flask framework, Flask-Sessions for server-side session management and requests using pip as follows:

    pip install -r requirements.txt
    
  2. Run app.py from shell or command line:

    python app.py
    

    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.

More information

How the sample works

Shows how the sample app generated by this quickstart works

Getting MSAL

MSAL is the library used to sign in users and request tokens used to access an API protected by the Microsoft identity Platform. You can add MSAL Python to your application using Pip.

pip install msal

MSAL initialization

You can add the reference to MSAL Python by adding the following code to the top of the file where you will be using MSAL:

import msal

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.