Home > Software design >  How to request email scope from AAD using Microsoft.Identity.Web
How to request email scope from AAD using Microsoft.Identity.Web

Time:02-19

I am trying to do something that I know how to do in .NET Framework in .NET Core but am missing a simple configuration step.

.NET Framework:

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
Scope = OpenIdConnectScope.OpenIdProfile   " "   OpenIdConnectScope.Email,
....

In .NET Core I am using Microsoft.Identity.Web and haven't been able to find the place to set scopes before the Azure Active Directory login request is sent. If I manually edit the URL when the login page occurs, I am able to get the email claim back by adding email to the scope in the URL query string.

This is the Startup.cs code in the new app that I think is where I need to add scope:

            services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));

As a guess, I tried adding "Scopes" to my appsettings here:

  "AzureAd": {
    "Instance": [...]
    "Scopes": "openid profile email"
  },

But that doesn't seem to be attached to anything.

What worked after reading kavyasaraboju-MT's helpful answer:

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme).AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));
services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    options.Scope.Add("email");
});

CodePudding user response:

Please check if below references can help.

In Startup Config (adding email scope)

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
    .AddAzureAD(options => Configuration.Bind("AzureAd", options));

services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
    options.Authority  = "/v2.0/";
    ..
//we can add scopes this way
options.Scope.Add("openid");
     options.Scope.Add("profile");
     options.Scope.Add("email");
//
…
}

In manifest we can add optional claims (for access token or id token )

"optionalClaims": {
        "idToken": [],
        "accessToken": [
            {
                "name": "email",
                "source": null,
                "essential": false,
                "additionalProperties": []
            } ],

enter image description here

Give app permissions for email ,profile and openid access in portal and grant consent.

And make sure the signin request has required scopes

&response_type=id_token &scope=openid profile email

Please refer these

  1. asp.net core mvc - Azure AD v2 with Azure App Registration missing optional email claim in ID Token for directly assigned user - Stack Overflow
  2. azure active directory - how to request additional user profile data (email address, ) - Stack Overflow
  • Related