Git Product home page Git Product logo

azure-samples / ms-identity-aspnet-webapp-openidconnect Goto Github PK

View Code? Open in Web Editor NEW
171.0 50.0 70.0 902 KB

A sample showcasing how to develop a web application that handles sign on via the unified Azure AD and MSA endpoint, so that users can sign in using both their work/school account or Microsoft account. The sample also shows how to use MSAL to obtain a token for invoking the Microsoft Graph, as well as incrementental consent.

License: MIT License

C# 32.52% CSS 1.22% HTML 28.12% JavaScript 10.38% PowerShell 27.58% ASP.NET 0.17%

ms-identity-aspnet-webapp-openidconnect's Introduction

services platforms author level client service endpoint page_type languages products description
active-directory
dotnet
jmprieur
400
ASP.NET Web App
Microsoft Graph
Microsoft identity platform
sample
csharp
azure
microsoft-entra-id
dotnet
office-ms-graph
This sample showcases how to develop a ASP.NET MVC web application that handles sign using the Microsoft identity platform and ASP.NET OpenId Connect OWIN middleware.

Use OpenID Connect to sign in users to Microsoft identity platform and execute Microsoft Graph operations using incremental consent

Build Badge

About this sample

Overview

This sample showcases how to develop a web application that handles sign using the Microsoft identity platform. It shows you how to use the new unified signing-in model that can be used to sign-in users to the app with both their work/school account (Microsoft Entra account) or Microsoft account (MSA). The application is implemented as an ASP.NET MVC project, while the web sign-on functionality is implemented via ASP.NET OpenId Connect OWIN middleware.

The sample shows how to use MSAL.NET (Microsoft Authentication Library) to obtain an access token for Microsoft Graph. Specifically, the sample shows how to retrieve the last email messages received by the signed in user, and how to send a mail message as the user using Microsoft Graph.

The sample also showcases a new capability introduced by the new Microsoft identity platform - the ability for one app to seek consent for new permissions incrementally.

Finally, the sample demonstrates how to use MSAL.js v2 and MSAL .Net together in a "hybrid" application that performs both server-side and client-side authenication. Some applications like SharePoint and OWA are built as "hybrid" web applications, which are built with server-side and client-side components (e.g. an ASP.net web application hosting a React single-page application). In these scenarios, the application will likely need authentication both client-side (e.g. a public client using MSAL.js) and server-side (e.g. a confidential client using MSAL.net ), and each application context will need to acquire its own tokens.

It shows how to use two new APIs, WithSpaAuthorizationCode on AcquireTokenByAuthorizationCode in MSAL .Net and acquireTokenByCode in MSAL.js v2, to authenticate a user server-side using a confidential client, and then SSO that user client-side using a second authorization code that is returned to the confidential client and redeemed by the public client client-side. This helps mitigate user experience and performance concerns that arise when performing server-side and client-side authentication for the same user, especially when third-party cookies are blocked by the browser.

For more information about how the protocols work in this scenario and other scenarios, see Authentication Scenarios for Microsoft Entra ID.

For more information about Microsoft Graph, please visit the Microsoft Graph homepage.

Topology

Overview

Looking for previous versions of this code sample? Check out the tags on the releases GitHub page.

Scenario

You sign in using your personal Microsoft Account in the app. During this flow, the app asks for consent to read your email only. Then, using this app, you can get the contents of your email's inbox using Microsoft Graph Api.

When you want to send an email, the app then proceeds to ask for an additional permission to send emails on your behalf. Once you provide that, it presents you with a screen using which you can send emails. The emails are sent using Microsoft Graph API.

How To Run This Sample

To run this sample, you'll need:

  • Visual Studio
  • An Internet connection
  • At least one of the following accounts:
  • A Microsoft Account with access to an outlook.com enabled mailbox
  • a Microsoft Entra account with access to an Office 365 mailbox

You can get a Microsoft Account and outlook.com mailbox for free by choosing the Sign-up option while visiting https://www.microsoft.com/outlook-com/. You can get an Office365 office subscription, which will give you both a Microsoft Entra account and a mailbox, at https://products.office.com/try.

Step 1: Clone or download this repository

From your shell or command line:

git clone https://github.com/Azure-Samples/ms-identity-aspnet-webapp-openidconnect.git

or download and extract the repository .zip file.

Given that the name of the sample is quiet long, and so are the names of the referenced NuGet packages, you might want to clone it in a folder close to the root of your hard drive, to avoid file size limitations on Windows.

Step 2: Register the sample application with your Microsoft Entra tenant

There is one project in this sample. To register it, you can:

If you want to use this automation:

  1. On Windows run PowerShell and navigate to the root of the cloned directory

  2. In PowerShell run:

    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
  3. Run the script to create your Microsoft Entra application and configure the code of the sample application accordinly.

    .\AppCreationScripts\Configure.ps1

    Remember to make the manual change in the manifest for the signInAudience as explained below.

    Other ways of running the scripts are described in App Creation Scripts

  4. Open the Visual Studio solution and click start

If you don't want to use this automation, follow the steps below

Choose the Microsoft Entra tenant where you want to create your applications

As a first step you'll need to:

  1. Sign in to the Microsoft Entra admin center using either a work or school account or a personal Microsoft account.
  2. If your account is present in more than one Microsoft Entra tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory. Change your portal session to the desired Microsoft Entra tenant.

As a first step you'll need to:

  1. Sign in to the Microsoft Entra admin center using either a work or school account or a personal Microsoft account.
  2. If your account is present in more than one Microsoft Entra tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory. Change your portal session to the desired Microsoft Entra tenant.

Register the service app (MailApp-openidconnect-v2)

  1. Navigate to the Microsoft identity platform for developers App registrations page.

  2. Select New registration.

  3. When the Register an application page appears, enter your application's registration information:

    • In the Name section, enter a meaningful application name that will be displayed to users of the app, for example MailApp-openidconnect-v2.
    • Change Supported account types to Accounts in any organizational directory and personal Microsoft accounts (e.g. Skype, Xbox, Outlook.com).
    • In the Redirect URI (optional) section, select Web in the combo-box and enter the following redirect URIs: https://localhost:44326/.
  4. Select Register to create the application.

  5. On the app Overview page, find the Application (client) ID value and record it for later. You'll need it to configure the Visual Studio configuration file for this project.

  6. Select Save.

  7. From the Certificates & secrets page, in the Client secrets section, choose New client secret:

    • Type a key description (of instance app secret),
    • Select a key duration of either In 1 year, In 2 years, or Never Expires.
    • When you press the Add button, the key value will be displayed, copy, and save the value in a safe location.
    • You'll need this key later to configure the project in Visual Studio. This key value will not be displayed again, nor retrievable by any other means, so record it as soon as it is visible from the Microsoft Entra admin center.
  8. Select the API permissions section

    • Click the Add a permission button and then,
    • Ensure that the Microsoft APIs tab is selected
    • In the Commonly used Microsoft APIs section, click on Microsoft Graph
    • In the Delegated permissions section, ensure that the right permissions are checked: openid, profile, offline_access, Mail.Read, User.Read. Use the search box if necessary.
    • Select the Add permissions button

Change the application's manifest to enable both Work and School and Microsoft Accounts

  1. Select the Manifest section for your app.

  2. Search for signInAudience and make sure it's set to AzureADandPersonalMicrosoftAccount

         "signInUrl": null,
         "signInAudience": "AzureADandPersonalMicrosoftAccount",
  3. Click Save to save the app manifest.

Configure the service project

Note: if you used the setup scripts, the changes below will have been applied for you

  1. Open the solution in Visual Studio.
  2. Open the web.config file.
  3. Find the app key ida:ClientId and replace the existing value with the application ID (clientId) of the MailApp-openidconnect-v2 application copied from the Microsoft Entra admin center.
  4. Find the app key ida:ClientSecret and replace the existing value with the key you saved during the creation of the MailApp-openidconnect-v2 app, in the Microsoft Entra admin center.

Step 5: Run the sample

Clean the solution, rebuild the solution, and run it.

Once you run the MailApp web application, you are presented with the standard ASP.NET home page. Click on the Sign-in with Microsoft link on top-right to trigger the log-in flow. Sign-in

On the sign-in page, enter the name and password of a personal Microsoft account or a work/school account. 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. During the sign-in process, you will be prompted to grant various permissions - including the ability for the app to read the user's email.

First Consent

Remember, the account you choose must have access to an email inbox. If you are using a MSA and the email features don't work, your account might not have been migrated to the new API. The fastest workaround is to create a new test *@outlook.com account. Please refer to the beginning of this readme for instructions.

As you sign in, the app will change the sign-in button into a greeting to the current user - and two new menu commands will appear: Read Mail and Send Mail.

Post sign-in

Click on Read Mail: the app will show a dump of the last few messages from the current user's inbox, as they are received from the Microsoft Graph.

Click on View Profile: the app will show the profile of the current user, as they are received from the Microsoft Graph.

The sample redeems the Spa Auth Code from the initial token aquisition. You will need to sign-out and sign back in to request the SPA Auth Code. If you want to add more client side functionallity, please refer to the MSAL JS Browser Sample for Hybrid SPA

Click on Send Mail. As it is the first time you do so, you will receive a message informing you that for the app to receive the permissions to send mail as the user, the user needs to grant additional consent. The message offers a link to initiate the process.

Incremental Consent Link

Click it, and you will be transported back to the consent experience, this time it lists just one permission, which is Send mail as you.

Incremental Consent prompt

Once you have consented to this permission, you will be transported back to the application: but this time, you will be presented with a simple experience for authoring an email. Use it to compose and send an email to a mailbox you have access to. Send the message and verify you receive it correctly.

Hit the sign-out link on the top right corner.

Sign in again with the same user, and follow the exact same steps described so far. You will notice that the send mail experience appears right away and no longer forces you to grant extra consent, as your decision has been recorded in your previous session.

Did the sample not work for you as expected? Did you encounter issues trying this sample? Then please reach out to us using the GitHub Issues page.

About the code

Here there's a quick guide to the most interesting authentication-related bits of the sample.

Sign in

As it is standard practice for ASP.NET MVC apps, the sign-in functionality is implemented with Microsoft.Identity.Web coordinating the ASP.NET OpenID Connect OWIN middleware and MSAL.NET. Here there's a relevant snippet from the authentication initialization (in the App_Start/Startup.Auth.cs file.):

public void ConfigureAuth(IAppBuilder app)
{
    // ...
    // Get a TokenAcquirerFactory specialized for OWIN
    OwinTokenAcquirerFactory owinTokenAcquirerFactory = TokenAcquirerFactory.GetDefaultInstance<OwinTokenAcquirerFactory>();

    // Configure the web app.
    app.AddMicrosoftIdentityWebApp(owinTokenAcquirerFactory,
                                    updateOptions: options => {});

    // Add the services you need.
    owinTokenAcquirerFactory.Services
            .Configure<ConfidentialClientApplicationOptions>(options => 
                { options.RedirectUri = "https://localhost:44326/"; })
        .AddMicrosoftGraph()
        .AddInMemoryTokenCaches();

    owinTokenAcquirerFactory.Build();
    // ...
}

Important things to notice:

  • The Authority points to the new authentication endpoint, which supports both personal and work and school accounts.
  • the list of scopes includes both entries that are used for the sign-in function (openid, email, profile) and for the token acquisition function (offline_access is required to obtain refresh_tokens as well; Mail.Read is required for getting access tokens that can be used when requesting to read the user's mail).
  • In this sample, the issuer validation is turned off, which means that anybody with an account can access the application. Real life applications would likely be more restrictive, limiting access only to those Microsoft Entra tenants or Microsoft accounts associated to customers of the application itself. In other words, real life applications would likely also have a sign-up function - and the sign-in would enforce that only the users who previously signed up have access. For simplicity, this sample does not include sign up features.

Initial token acquisition

This sample makes use of OpenId Connect hybrid flow, where at authentication time the app receives both sign in info, the id_token and artifacts (in this case, an authorization code) that the app can use for obtaining an access token. This access token can be used to access other resources - in this sample, the Microsoft Graph, for the purpose of reading the user's mailbox.

Using access tokens in the app, handling token expiration

The ReadMail action in the HomeController class demonstrates how to take advantage of Microsoft.Identity.Web for calling Microsoft Graph without having to worry about getting a token, or caching it.

Here is the relevant code:

    try
    {
        GraphServiceClient graphServiceClient = this.GetGraphServiceClient();
        await graphServiceClient.Me
            .SendMail(message, true)
            .Request()
            .WithScopes("Mail.Send").PostAsync();
        return View("MailSent");
    }
    catch (ServiceException graphEx) when (graphEx.InnerException is MicrosoftIdentityWebChallengeUserException)
    {
        ChallengeUser(graphEx.InnerException as MicrosoftIdentityWebChallengeUserException);
        return View();
    }
    catch(Exception ex)
    {
        ViewBag.Message = ex.Message;
        return View();
    }
}

The idea is simple. The code gets an instance of GraphServiceClient, which already knows how to get a token. That done, all you need to do is to invoke WithScopes on the request, asking for the scopes you need. MSAL will look up the cache and return any cached token, which matches with the requirement. If such access tokens are expired or no suitable access tokens are present, but there is an associated refresh token, MSAL will automatically use that to get a new access token and return it transparently.

In the case in which refresh tokens are not present or they fail to obtain a new access token, MSAL will throw MsalUiRequiredException, embedded by Microsoft.Identity.Web into a MicrosoftIdentityWebChallengeUserException. That means that in order to obtain the requested token, the user must go through an interactive sign-in experience.

In the case of this sample, the Mail.Read permission is obtained as part of the login process - hence we need to trigger a new login; however we can't just redirect the user without warning, as it might be disorienting (what is happening, or why, would not be obvious to the user) and there might still be things they can do with the app that do not entail accessing mail. For that reason, the sample simply signals to the view to show a warning - and to offer a link to an action (RefreshSession) that the user can leverage for explicitly initiating the re-authentication process.

Using Spa Auth Code in the Front End

First, configure a new PublicClientApplication from MSAL.js in your single-page application:

const msalInstance = new msal.PublicClientApplication({
    auth: {
        clientId: "Enter the Client ID from the Web.Config file",
        redirectUri: "https://localhost:44326/",
        authority: "https://login.microsoftonline.com/organizations/"
    }
})

Next, render the code that was acquired server-side, and provide it to the acquireTokenByCode API on the MSAL.js PublicClientApplication instance. Be sure to not include any additional scopes that were not included in the first login request, otherwise the user may be prompted for consent.

    var code = spaCode;
    const scopes = ["user.read"];

    console.log('MSAL: acquireTokenByCode hybrid parameters present');

    var authResult = msalInstance.acquireTokenByCode({
        code,
        scopes
    })

Once the Access Token is retrieved using the new MSAL.js acquireTokenByCode api, the token is then used to read the user's profile

function callMSGraph(endpoint, token, callback) {
    const headers = new Headers();
    const bearer = `Bearer ${token}`;
    headers.append("Authorization", bearer);

    const options = {
        method: "GET",
        headers: headers
    };

    console.log('request made to Graph API at: ' + new Date().toString());

    fetch(endpoint, options)
        .then(response => response.json())
        .then(response => callback(response, endpoint))
        .then(result => {
            console.log('Successfully Fetched Data from Graph API:', result);
        })
        .catch(error => console.log(error))
}

Handling incremental consent and OAuth2 code redemption

The SendMail action demonstrates how to perform operations that require incremental consent. Observe the structure of the GET overload of that action. The code follows the same structure as the one you saw in ReadMail: the difference is in how MsalUiRequiredException is handled. The application did not ask for Mail.Send during sign-in, hence the failure to obtain a token silently could have been caused by the fact that the user did not yet grant consent for the app to use this permission. Instead of triggering a new sign-in as we have done in ReadMail, here we can craft a specific authorization request for this permission.

The call to the utility function ChallengeUser does precisely that, leveraging ASP.NET to generate an OAuth2/OpenId Connect request for an authorization code for the Mail.Send permission.

private void ChallengeUser(MicrosoftIdentityWebChallengeUserException exc)
{
    var authenticationProperties = new AuthenticationProperties();
    if (exc.Scopes != null)
    {
        authenticationProperties.Dictionary.Add("scopes", string.Join(" ", exc.Scopes));
    }
    if (!string.IsNullOrEmpty(exc.MsalUiRequiredException.Claims))
    {
        authenticationProperties.Dictionary.Add("claims", exc.MsalUiRequiredException.Claims);
    }
    authenticationProperties.Dictionary.Add("login_hint", (HttpContext.User as ClaimsPrincipal).GetDisplayName());
    authenticationProperties.Dictionary.Add("domain_hint", (HttpContext.User as ClaimsPrincipal).GetDomainHint());

    HttpContext.GetOwinContext().Authentication.Challenge(authenticationProperties, OpenIdConnectAuthenticationDefaults.AuthenticationType);
}

Note that the custom middleware is provided only as an example, and it has numerous limitations (like a hard dependency on MSALPerUserMemoryTokenCache) that limit its applicability outside of this scenario.

How to deploy this sample to Azure

This project has one WebApp / Web API projects. To deploy them to Azure Web Sites, you'll need, for each one, to:

  • create an Azure Web Site
  • publish the Web App / Web APIs to the web site, and
  • update its client(s) to call the web site instead of IIS Express.

Create and publish the openidconnect-v2 to an Azure Web Site

  1. Sign in to the Microsoft Entra admin center.
  2. Click Create a resource in the top left-hand corner, select Web --> Web App, and give your web site a name, for example, openidconnect-v2-contoso.azurewebsites.net.
  3. Thereafter select the Subscription, Resource Group, App service plan and Location. OS will be Windows and Publish will be Code.
  4. Click Create and wait for the App Service to be created.
  5. Once you get the Deployment succeeded notification, then click on Go to resource to navigate to the newly created App service.
  6. Once the web site is created, locate it it in the Dashboard and click it to open App Services Overview screen.
  7. From the Overview tab of the App Service, download the publish profile by clicking the Get publish profile link and save it. Other deployment mechanisms, such as from source control, can also be used.
  8. Switch to Visual Studio and go to the openidconnect-v2 project. Right click on the project in the Solution Explorer and select Publish. Click Import Profile on the bottom bar, and import the publish profile that you downloaded earlier.
  9. Click on Configure and in the Connection tab, update the Destination URL so that it is a https in the home page url, for example https://openidconnect-v2-contoso.azurewebsites.net. Click Next.
  10. On the Settings tab, make sure Enable Organizational Authentication is NOT selected. Click Save. Click on Publish on the main screen.
  11. Visual Studio will publish the project and automatically open a browser to the URL of the project. If you see the default web page of the project, the publication was successful.

Update the Active Directory tenant application registration for openidconnect-v2

  1. Navigate back to to the Microsoft Entra admin center. In the left-hand navigation pane, select the Microsoft Entra ID service, and then select App registrations (Preview).
  2. In the resultant screen, select the openidconnect-v2 application.
  3. From the Branding menu, update the Home page URL, to the address of your service, for example https://openidconnect-v2-contoso.azurewebsites.net. Save the configuration.
  4. Add the same URL in the list of values of the Authentication -> Redirect URIs menu. If you have multiple redirect urls, make sure that there a new entry using the App service's Uri for each redirect url.

Community Help and Support

Use Stack Overflow to get support from the community. Ask your questions on Stack Overflow 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 dotnet microsoft-graph].

If you find a bug in the sample, please raise the issue on GitHub Issues.

To provide a recommendation, visit the following User Voice page.

Contributing

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.

More information

For more information, visit the following links:

ms-identity-aspnet-webapp-openidconnect's People

Contributors

acomsmpbot avatar aremo-ms avatar bgavrilms avatar brentschmaltz avatar danieldobalian avatar dependabot[bot] avatar didunayodeji avatar gladjohn avatar gladwinjohnson avatar gsacavdm avatar jennyf19 avatar jmprieur avatar markzuber avatar neha-bhargava avatar rwike77 avatar v-michaelmi avatar vibronet avatar westin-m avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ms-identity-aspnet-webapp-openidconnect's Issues

AADSTS9000512: A Hybrid SPA code can only be requested while redeeming a confidential client authorization code. Error

Hi,

I have downloaded the latest commit of e62c8db and then created an app registration and enabled ID tokens, along with the necessary delegated permissions, a web redirecturi, and the client secret which I have then set up in the web.config.

I then run the web app and sign in with my account and I receive this error.

AADSTS9000512: A Hybrid SPA code can only be requested while redeeming a confidential client authorization code (a code issued to a web-type redirect URI). Do not request a hybrid code otherwise

I notice that the exception happens on

AuthenticationResult result = await clientApp.AcquireTokenByAuthorizationCode(new[] { "Mail.Read User.Read" }, context.Code)
                .WithSpaAuthorizationCode() //Request an authcode for the front end
                .ExecuteAsync();

in OnAuthorizationCodeReceived in Startup.Auth.cs.

Could anyone advise me on how to fix this?

Can the configuration be managed from database?

I am trying to read the configuration values from database,

 <add key="ida:ClientId" value="[Enter your client ID, as obtained from the app registration portal]"/>
    <add key="ida:ClientSecret" value="[Enter your client secret, as obtained from the app registration portal]"/>
    <add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}{1}"/>
    <add key="ida:RedirectUri" value="https://localhost:44326/"/>

I am having different clients, so that I will read it from database and pass it on config

Rewriting for ASP.NET Core: Challenge not working

Hi,

I've been rewriting this sample for ASP.NET Core. I have most of it working, but I'm having trouble getting the challenge to work properly in HomeController.RefreshSession. I.e. when I'm logged in, I'm redirected to the Access Denied URL that is configured in the cookie middleware, instead of the auth endpoint when I issue a challenge. Seems like this behavior changed in ASP.NET Core. Any ideas on how to get this to work again?

Thanks!

Getting unsupported_response_type when signing in

I cloned the repo, followed the instructions to setup a v2 app and modified the web.config to use my app. When I ran the app locally and tried to signin I get an "unsupported_response_type" error back. I tried this with both my Microsoft corp credential and hotmail credential. Both returned the same error. Anyone know what's going on?

Thanks.

Incremental consent experience broken with MSAL update

I've noticed since the update to MSAL 1.1.0-preview that the incremental consent experience doesn't work optimally. I've also noticed this when I updated to the latest MSAL in this branch of another sample.

When I click on the "send mail" tab, I go through the incremental consent experience, but then redirect to a page with this error:

image

When I click on "send mail" a second time, I go through the consent experience again, and then end up on a page that tells me that I've consented to the additional permissions.

After that second attempt I can send a mail successfully.

I didn't see this with an earlier version of this sample that used the -alpha version of MSAL, and I didn't see this problem in the aspnet-snippets-sample (linked above) until after I updated it to the latest MSAL.

unauthorized_client

I tried using this example with an existing AAD app I'd already created and I'm getting the unauthorized_client response. I replaced the client id and secret, as well as the application id and the redirect url was modified correctly. Is there something I'm missing here?

Migrating from Asp.Net Identity to Azure AD authentication

I'm want to migrate an Asp.Net MVC app using Identity for authentication, to use Azure AD for authentication.

Some questions:

  1. I believe I need to map the Azure AD user with my 'in-app' User Profile and Roles. What is the best claim to use for that ? I was told to use the Upn (Universal Principal Name), but this claim doesn't exist when using V2 endpoint.

  2. Is it still required to call AuthenticationManager.SignIn() somewhere in the pipeline, or the OWIN middleware already manage this ?
    Here is the snippet I'm talking about in a tradititional AccountController:

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
            AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);

        }
  1. If 2) is not required anymore, I am not clear how the OpenIdConnect middleware is making the link to my Asp.Net Identity user.

sample not working when hosting on iis server secured(https)

Hello,

I hope I can find an answer to my issue.
I've created the app Id on azure (with secret key), and set the redirect URL to localhost. when executing the app,I'm able to connect using my MS account, and execute the ms graph functions.

But when I hosted the app on one of my IIS server (https), and also set the redirect URL to this new url, when executing the app, click on sign in, and enter the passsword, I'm redirected to my app, but with no session registred.

the cookie created is call : OpenIDConnect.nonce..

Please help.
Screenshot after signin:

image

ClaimsPrincipal.Current.GetUserId() in MsalAppBuilder.cs doesn't work with newer .net libraries

As the title says, this method no longer works, as per this post here:

aspnet/Announcements#140

So this code will no longer compile if the developer is using newer asp.net libraries.

    `public static async Task RemoveAccount()
    {

        BuildConfidentialClientApplication();

        var userAccount = await clientapp.GetAccountAsync(GetUserId(ClaimsPrincipal.Current));
        if (userAccount != null)
        {
            await clientapp.RemoveAsync(userAccount);
        }
    }`

I ended up using the tenant and client id to get the account by id:

        public static async Task RemoveAccount()
        {
            ClaimsPrincipal cp = ClaimsPrincipal.Current;
            if (cp == null)
            {
                throw new MsalException("01","Missing Claims Principal");
            }
            var objIdClaim = cp.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier");
            var tenantIdClaim = cp.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid");
            GetIConfidentialClientApplication();
            if (objIdClaim == null || tenantIdClaim == null)
            {
                throw new MsalException("02", "Missing Name or Tenant Claim");
            }
            var userAccount = await clientapp.GetAccountAsync(objIdClaim.Value +"."+tenantIdClaim.Value);
            if (userAccount != null)
            {
                await clientapp.RemoveAsync(userAccount);
            }
        }

GetAccountAsync does not work with Guest account in single tenant configuration

Hi,

I'm using this sample because it's the closest to our application, i.e. using .NET Framework.
Our requirement is to support external user (guest account) authentication on our AAD tenant.
The authorization is performed on AD groups assigned to these guest accounts in our AAD tenant.
Therefore, we need to configure the application in single tenant mode (using our tenant id), otherwise the access token will be issued by the guest account's tenant and the call to Microsoft Graph API to retrieve authenticated user's AD groups will be performed on the tenant of the user instead of ours.

The problem is that in single tenant mode, the ClaimsPrincipal.Current.GetAccountId() does not return the same value as the TokenCacheNotificationArgs.SuggestedCacheKey :

Indeed, GetAccountId returns the "objectId.tenantId" from our AAD tenant, whereas the SuggestedCacheKey manages for some reason (couldn't find out how) to retrieve the correct HomeAccountId of the user's tenant.
As a result, GetAccountAsync returns null and AcquireTokenSilent doesn't work.

Thank you for your help.

owin token provider

Looks like the Owin Token acquire factory is supposed to be setup during initialization, but the DefineConfiguration method returns current httpcontext information. It is throwing an error upon startup.

Request.Query["code"] is always null

string code = context.Request.Query["code"]; in the overridden Invoke(IOwinContext context) method of the "OAuth2CodeRedeemerMiddleware : OwinMiddleware" class is always null.

How to get access token for use right after successful signin?

Hi,
I could be on the wrong path here. Any direction would be appreciated.
What I am trying to do is add a claim to the user right after they are authenticated.
This claim will essentially be used for user authorization.
The user authorization will be determined by their membership in AD group(s).

I'm trying to do this in the OnAuthorizationCodeReceived event:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDistributedMemoryCache();
            services.AddHttpClient();
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddOptions();

            // Token acquisition service based on MSAL.NET and chosen token cache implementation
            services.AddAzureAdV2Authentication(Configuration)
                    .AddMsal(new string[] { Configuration["GraphAdGroups:GraphAdGroupsScope"], Constants.ScopeUserRead })
                    .AddInMemoryTokenCaches();

            services.AddGraphAdGroupsService(Configuration);
            var sp = services.BuildServiceProvider();
            services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
            {
                var handler = options.Events.OnAuthorizationCodeReceived;
                options.Events.OnAuthorizationCodeReceived = async context =>
                {
                    await handler(context);
                    var groupService = sp.GetService<IGraphAdGroupsService>();
                    var gms = await groupService.GetGroupMembers("ECOMM_ADMIN");
                };
            }
            );

            services.AddMvc(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

appsettings.json:

"GraphAdGroups": { "GraphAdGroupsScope": "api://189be169-44c6-4ef4-8d67-a95b134e6619/user_impersonation api://189be169-44c6-4ef4-8d67-a95b134e6619/Group.Read.All api://189be169-44c6-4ef4-8d67-a95b134e6619/Directory.Read.All", "GraphAdGroupsBaseAddress": "https://localhost:44320" },

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Identity.Web.Client;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using web.Models.GraphAdGroups;

namespace web.Services.GraphAdGroups
{
    public static class GraphAdGroupsServiceExtensions
    {
        public static void AddGraphAdGroupsService(this IServiceCollection services, IConfiguration configuration)
        {
            // https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests
            services.AddHttpClient<IGraphAdGroupsService, GraphAdGroupsService>();
        }
    }

    public class GraphAdGroupsService : IGraphAdGroupsService
    {
        private readonly IHttpContextAccessor _contextAccessor;
        private readonly HttpClient _httpClient;
        private readonly string _GraphAdGroupsBaseAddress = string.Empty;
        private readonly ITokenAcquisition _tokenAcquisition;
        private readonly string _scopes = string.Empty;

        public GraphAdGroupsService(ITokenAcquisition tokenAcquisition, HttpClient httpClient, IConfiguration configuration, IHttpContextAccessor contextAccessor)
        {
            _httpClient = httpClient;
            _tokenAcquisition = tokenAcquisition;
            _contextAccessor = contextAccessor;
            _GraphAdGroupsBaseAddress = configuration["GraphAdGroups:GraphAdGroupsBaseAddress"];
            _scopes = configuration["GraphAdGroups:GraphAdGroupsScope"];
        }

        private async Task PrepareAuthenticatedClient()
        {
            var accessToken = await _tokenAcquisition.GetAccessTokenOnBehalfOfUser(_contextAccessor.HttpContext, new[] { _scopes });
            Debug.WriteLine($"PrepareAuthenticatedClient(): access token-{accessToken}");
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }

        public async Task<dynamic> GetGroupMembers(string group)
        {
            await PrepareAuthenticatedClient();
            var request = $"{_GraphAdGroupsBaseAddress}/Graph/GetGroupMembers/{group}";
            var response = await _httpClient.GetAsync(request);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                var content = await response.Content.ReadAsStringAsync();
                IEnumerable<GroupMembers> groupMembersList = JsonConvert.DeserializeObject<IEnumerable<GroupMembers>>(content);
                GroupMemberSearch gms = new GroupMemberSearch();
                gms.GroupSearched = group;
                gms.GroupMembersList = groupMembersList.ToList();
                return gms;
            }
            throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}.");
        }

    }
}

The error I'm getting is:
`MsalUiRequiredException: No account or login hint was passed to the AcquireTokenSilent call.
Microsoft.Identity.Client.AcquireTokenSilentParameterBuilder.Validate()

Exception: An error was encountered while handling the remote login.
Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler.HandleRequestAsync()`
on the
var gms = await groupService.GetGroupMembers("ECOMM_ADMIN");
line within OnAuthorizationCodeReceived

PostLogoutRedirectURI does not work for Organizational Accounts

It does not seem to work for accounts in the Organizational Directory.
In particular it gets stuck on this screen after you've selected the account to sign out with:

image

Reading up on other solutions on the internet I noted that usually you need to send an id_token_hint to get this to work, but still no success. Below is the code added to the OpenIdConnect Notifications which does successfully add a non-null idTokenHint

private Task OnSecurityTokenValidated(SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> n)
        {
            var id = n.AuthenticationTicket.Identity;
            n.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
            n.AuthenticationTicket = new AuthenticationTicket(
              id,
              n.AuthenticationTicket.Properties);
            return Task.CompletedTask;
        }


       private  Task OnRedirectToIdentityProvider(RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> n)
        {
            if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout)
            {
                var id_token_claim = n.OwinContext.Authentication.User.Claims.FirstOrDefault(x => x.Type == "id_token");
                if (id_token_claim != null)
                {
                    n.ProtocolMessage.IdTokenHint = id_token_claim.Value;
                }
            }
            return Task.CompletedTask;
        }

I find it strange that it doesn't work, because on other projects I've done when using MSAL.js for client side apps it does work. So it should be able to work somehow.

Master branch missing OnAuthorizationCodeReceivedAsync to set Spa_Auth_Code session state

Hi,

I noticed that the master branch is missing the code to set the session state for the Spa Auth Code during logon. Seems like some refactoring was done and that was missed.

HttpContext.Current.Session.Add("Spa_Auth_Code", result.SpaAuthCode);

This is always returning null for me:

public async Task<ActionResult> ViewProfile()
{
    var spaAuthCode = HttpContext.Session["Spa_Auth_Code"];

    ViewBag.SpaAuthCode = spaAuthCode as string;

    return await Task.Run(() => View());
}

Implicit Grant Flow

I have a question. I have noted that to make the sample work I have to leave the checkbox "Allow Implicit Flow" checked when registering the app.

In this page Is the implicit grant suitable for my app? I read that is not recommended for web apps with a backend:

If you are developing a Web application which includes a backend, and that is meant to consume API from its backend code, the implicit flow is also not a good fit. Other grants give you far more power: for example, the OAuth2 client credentials grant provides the ability to obtain tokens that reflect the permissions assigned to the app itself as opposed to user delegations, the ability to maintain programmatic access to resources even when a user is not actively engaged in a session, and so on. Not only that, but such grants give higher security guarantees: access tokens never transit through the user browser, they don’t risk being saved in the browser history, and so on; the client application can perform strong authentication when requesting a token; and so on.

Is there a way to setup the sample to use the "authorization code flow" only? Thanks in advance.

Azure AD B2C

Hello everyone.

Does this sample support Azure AD B2C ?

Seems to expire.

When I compile and run it in the browser, leave it for about 15-20 minutes and the session expires. Is there any way to keep the user logged in as long as the browser is on the web site?

Issue with Custom RoleProvider and cacheRolesInCookie

After incorporating this code into my application, it seemed to get stuck in a loop trying to acquire the token (AcquireTokenSilent).

After some trial and error and educated guesses, I discovered that setting cacheRolesInCookie="false" for my custom RoleProvider in Web.Config solved the problem.

Not sure if this is an issue with this code per se, but thought I might save someone else some trouble by documenting what I discovered.

I would be interested in understanding why a custom RoleProvider caching roles in a cookie would interfere with the Graph Authentication. I did try changing some of the other RoleProvider cookie settings, like changing the cookie name, but it didn't seem to make any difference.

Thanks

GetAccountsAsync is deprecated but all examples still use it. What is the alternative for GetAccountsAsync?

We have a confidential client and retrieve a token with AcquireTokenSilent.
We use the code like in this example: https://github.com/Azure-Samples/ms-identity-aspnet-webapp-openidconnect

Especially this part:

var accounts = await app.GetAccountsAsync();
string[] scopes = { "Mail.Read" };

try
{
  // try to get token silently
  result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync().ConfigureAwait(false);
}

But the app.GetAccountsAsync is deprecated.

How should we retrieve a token silently without app.GetAccountsAsync?

Kind regards,
Harold

Processing admin consent response via owin middleware

For the incremental consent, is there any particular reason of using an owin middleware instead of using a redirectUri to a specific controller action that would process the admin consent response ?

I don't like the fact that the middleware 'trigger' is to have a 'code' in query string. That is too implicit.

GetAccountAsync return null

When running this sample, in the HomeController, app.GetAccountAsync(ClaimsPrincipal.Current.GetAccountId()) always return null.
I think the root cause could be the cache initialization. When initializing the IConfidentialClientApplication instance by calling MsalAppBuilder.BuildConfidentialClientApplication, CreateTokenCacheSerializer method seems to return a different cache object every time, and therefore clientapp.UserTokenCache is always initialized as empty.
It appears to me that a regression was caused by this PR.
Could you please confirm?

Request: Provide better example for handling failed OnAuthenticationFailed in openidconnect sample

I'm looking for a way to handle Authentication errors in a robust way. I found this sample in this repo:

notification.Response.Redirect("/Error?message=" + notification.Exception.Message);

I noticed two issues with this approach:

  1. Anyone can supply a error message by modifying the query parameter. This could be a security issue.
  2. This does not seem to work when the app has a different base path.

I could work around 1. with a data protector and I can deal with 2. with some custom logic, but this does not seem like a "clean" way to do it.

App creation scrips don't work

I get this for both Setup and Cleanup:

$creds = Connect-AzureAD -Credential $Credential | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | One or more errors occurred. (Could not load type 'System.Security.Cryptography.SHA256Cng' from | assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.): Could not | load type 'System.Security.Cryptography.SHA256Cng' from assembly 'System.Core, Version=4.0.0.0, | Culture=neutral, PublicKeyToken=b77a5c561934e089'.

Use AD B2C and AAD with MVC 5 Owin

Hi, my app was built using MVC 5 and Owin, we added AD B2C and AAD to it, but today we are facing issues with refresh token. I added created an issue in the Katana repository. aspnet/AspNetKatana#512

Now we are trying to update our code to use Microsoft.Identity.Web.OWIN and see if we can have those issues with refresh token fixed.
I was trying to follow this sample but I could not see how I could have configuration for both AD B2C and AAD for Web Application.
I see here that is not possible to use AD B2C in Web App with Owin AzureAD/microsoft-identity-web#2312

Do you know how I could implement it? What is the recommendation?

A configuration issue is preventing authentication

When I try to log in with an AD user (onmicrosoft.com) I am receiving the following message:

A configuration issue is preventing authentication - check the error message from the server for details. You can modify the configuration in the application registration portal. See https://aka.ms/msal-net-invalid-client for details. Original exception: AADSTS7000215: Invalid client secret provided. Ensure the secret being sent in the request is the client secret value, not the client secret ID

When I implement this in a WebApp, I get Public Client can't send a client secret exception

Am I missing something in the app registration that would cause authentication to do this? I'm using a work or school account to create the app registration and everything saved appropriately. Implicit flow and Redirect Urls seem to be ok.

However, a call to ccs.AcquireTokenByAuthorizationCodeAsync returns the following error:

AADSTS90023: Public clients can't send a client secret.
Trace ID: 1b3cdfc8-82ac-495b-9d87-3738aa2b0800
Correlation ID: f2a52982-654f-4071-b8f0-87ea1e300c6b
Timestamp: 2017-05-17 17:13:39Z

Code for OnAuthorizationCodeReceived is a direct copy of what you have in this example:

        private static async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
        {
            var code = context.Code;
            string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
            ConfidentialClientApplication cca = new ConfidentialClientApplication(MSALConstants.ClientId, MSALConstants.RedirectUri, 
                new ClientCredential(MSALConstants.AppKey), 
                new MSALSessionCache(signedInUserID, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance(), null);
            string[] scopes = MSALConstants.GraphScopes.Split(new char[] { ' ' });

            var uri = new Uri(MSALConstants.RedirectUri);
            var result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes);
        }

Maybe I am missing something? The OWIN middleware is a direct copy from this site. Just trying to get the authentication working so that I can more on to using this with Microsoft Graph to get groups and such. Help is appreciated.

cca.users.count is zero even after logging in.

This problem happens sometimes but not all the time. My organization has AD FS. I run F5, successfully login and stop debugging from VS. Sometimes even after successful login, cca.Users count in readmail shows zero. After logging out and logging in, the problem disappears. Is the problem due to having AD FS? It's been driving me crazy for a couple of months and any insight will be helpful. I have tried virtually all samples using openidconnect and they all have the same issue.

Assembly loading issue

Clean, fresh downloaded project, after run get error:

Could not load file or assembly 'Microsoft.Owin, Version=4.2.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Issue with Authentication.Challenge not respecting properties in OWIN

I'm encountering an issue with the OWIN authentication process where the authenticationProperties provided to Authentication.Challenge do not seem to influence the outcome as expected.

In this sample, the /Home/ReadMail route is supposed to check if the required scopes are included in the token. If not, our ChallengeUser method adds these scopes to authenticationProperties.Dictionary and triggers an authentication challenge. However, despite confirming that authenticationProperties.Dictionary contains the necessary values, the authorization request always defaults to the initially specified scopes, resulting in a continuous redirect loop.

image

image

Furthermore, the public documentation implies that the [AuthorizeForScopes] attribute should be available in ASP.Net Framework, it seems that the attribute can not be used in ASP.Net Framework.

https://learn.microsoft.com/en-us/entra/identity-platform/scenario-web-api-call-api-acquire-token?tabs=aspnet

How to ensure the authentication properties are properly respected and why the [AuthorizeForScopes] attribute might be missing?

Thank you for your assistance.

AADSTS1002016

I'm getting an error that says the app is using ' TLS version 1.0, 1.1 and/or 3DES cipher'. This is an issue that appeared randomly without any change starting ~20th of july

Cookie timeout settings / configuration

We seem to have an issue with a cookie timing out and forcing a user to re-login / re-direct after a period of time, usually 60 minutes, is this configurable in the below sample? thanks.

invalid_client issue

hi,
i am using this example as reference and it was working all good, but suddenly i started getting invalid_client issue. what could be the problem. if i use rest call to get authentication code it works but with sample application its not wroking

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.