-1

I have a .net core api and User.Read delegated permission is given. Authentication section in startup.cs:

services.AddAuthentication("Bearer")
        .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd"));

Getting the graph api client:

var credential = new DefaultAzureCredential();
                    var token = credential.GetToken(
                            new Azure.Core.TokenRequestContext(
                                new[] { "https://graph.microsoft.com/.default" }));
                    var accessToken = token.Token;
                    _graphServiceClient = new GraphServiceClient(
                        new DelegateAuthenticationProvider((requestMessage) =>
                        {
                            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
                            return Task.CompletedTask;
                        }));

Not sure if i need to have application type permission and use user/{userID}. But why i don't understand. Getting error: me request is only valid with delegated authentication flow .

Md Farid Uddin Kiron
  • 16,817
  • 3
  • 17
  • 43
Manognya
  • 37
  • 5

2 Answers2

0

These are the permissions required to access the user details using the both delegated and application permissions:

enter image description here

As far as for /me endpoint as mentioned in the note here:

enter image description here

Hope this helps.

Mehtab Siddique
  • 556
  • 1
  • 2
  • 5
0

Not sure if i need to have application type permission and use user/{userID}. But why i don't understand. Getting error: me request is only valid with delegated authentication flow

You are defining delegated permission but passing token within it. Have a look on the below document:

enter image description here

First let me clarify, when delegated permission required. If you want to access UserList from your application its called application permission then you would need to pass auth token. But if you want to access UserList while the user login you need delegated permission auth token wouldn't need to pass there. Therefore, as you are mixing them consequently encountered that perticular error.

Please check the details steps here.

Right Authentication Provider:

Based on your scenario, you can call Graph API using numerous authentical protocol. For instance, authorization code flow enables native and web apps to securely obtain tokens in the name of the user. You can implement as following:

var scopes = new[] { "User.Read" };

var tenantId = "common";

var clientId = "YOUR_CLIENT_ID";
var clientSecret = "YOUR_CLIENT_SECRET";

var authorizationCode = "AUTH_CODE_FROM_REDIRECT";

var options = new TokenCredentialOptions
{
    AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};


var authCodeCredential = new AuthorizationCodeCredential(
    tenantId, clientId, clientSecret, authorizationCode, options);

var graphClient = new GraphServiceClient(authCodeCredential, scopes);

Note: More details can be found here

Using Graph SDK:

[Authorize]
public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        private readonly GraphServiceClient _graphServiceClient;
       


        public HomeController(ILogger<HomeController> logger,
                          GraphServiceClient graphServiceClient)
        {
            _logger = logger;
            _graphServiceClient = graphServiceClient;
        }
            
            [AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
        public async Task<IActionResult> GetUsers()
        {

            var users = await _graphServiceClient
                       .Users
                       .Request()
                       .GetAsync()
                       .ConfigureAwait(false);

         
            return View();
        }
            
      }

Note: You can check here

Using Token aquisition service:

            //Initialize on behalf of user token aquisition service
            var _tokenAcquisition = this.HttpContext.RequestServices
           .GetRequiredService<ITokenAcquisition>() as ITokenAcquisition;
            //define the scope
            string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
       
            //Getting token from Azure Active Directory
            string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes);
            //Request Grap API end point
            HttpClient _client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format("https://graph.microsoft.com/v1.0/me"));
            //Passing Token For this Request
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            HttpResponseMessage response = await _client.SendAsync(request);
            //Get User into from grpah API
            dynamic userInfo = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());

Program.cs Configuration:

You can check details here.

    string[] initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');
    
                
 services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                    .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
                    .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
                    .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
                    .AddInMemoryTokenCaches();

    

Note: If you still need more information, you could check our official document here.

Md Farid Uddin Kiron
  • 16,817
  • 3
  • 17
  • 43
  • Actually we are using a jwt bearer token and not using client secret so _tokenAcquisition.GetAccessTokenForUserAsync is failing. I was following the tutorial: https://learn.microsoft.com/en-us/azure/app-service/scenario-secure-app-access-microsoft-graph-as-app?tabs=azure-powershell – Manognya Mar 07 '23 at 12:16
  • Ah I see, apparently its permission issue. How did you configured your permission? Have you checked token whether it has required permission in it? – Md Farid Uddin Kiron Mar 08 '23 at 00:58
  • In the token, there is no scope. I gave permission to the API application. I think permission is needed in the client application as we are using the bearer token. – Manognya Mar 10 '23 at 15:10