skip to Main Content

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 .

2

Answers


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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search