Home

Util.AzureCloud / Util.MSAL - can it create credentials for GraphServiceClient ?

I was blown away when I saw LinqPad's ability to simplify MSAL with MFA etc...

Truly great stuff, thanks ! :)

I've tried to create a Graph client using the token generated and I just can't get it right.

Anyone know how I can feed a Util.MSAL token into new GraphServiceClient ?

Thanks

Paul

Comments

  • Have you tried the approach suggested in the LINQPad Tutorial and Reference?

    Using a GraphServiceClient instead of an ArmClient:

    async Task Main()
    {
        string authEndPoint = Util.AzureCloud.PublicCloud.AuthenticationEndpoint;
        string tenantID = "domain.com";
        string userHint = $"user@{tenantID}";
    
        var credential = new LINQPadTokenCredential (authEndPoint + tenantID, userHint);
        var graphServiceClient = new GraphServiceClient (credential);
        ...    
    }
    
    class LINQPadTokenCredential : TokenCredential
    {
        public readonly string Authority, UserIDHint;
    
        public LINQPadTokenCredential (string authority, string userIDHint) => (Authority, UserIDHint) = (authority, userIDHint);
    
        public override AccessToken GetToken (TokenRequestContext requestContext, CancellationToken cancellationToken)
            => GetTokenAsync (requestContext, cancellationToken).Result;
    
        public override async ValueTask<AccessToken> GetTokenAsync (TokenRequestContext requestContext,
                                                                    CancellationToken cancelToken)
        {
            // Call LINQPad's AcquireTokenAsync method to authenticate interactively, and cache token in the LINQPad GUI.
            var auth = await Util.MSAL.AcquireTokenAsync (Authority, requestContext.Scopes, UserIDHint).ConfigureAwait (false);
            return new AccessToken (auth.AccessToken, auth.ExpiresOn);
        }
    }
    
  • Thanks Joe,

    I'm missing something, I'm getting "Access is denied. Check credentials and try again." on the inner exception when using the graph client.
    I think I need to set an App (with a client id) in Azure.
    The outer exception is "Exception of type 'Microsoft.Graph.Models.ODataErrors.ODataError' was thrown."

    After creating the graphServiceClient, I run.... this is where the access denied comes in

    var result = await graphServiceClient.Me.Messages.GetAsync((requestConfiguration) =>
    {
        requestConfiguration.QueryParameters.Filter = "importance eq 'high'";
    }); 
    

    I'm using MFA, could that be the problem? The other example using Util.AzureCloud.PublicCloud works perfectly, but I can't seem to use that token for Microsoft Graph...

    string azureAuth = Util.AzureCloud.PublicCloud.AuthenticationEndpoint;
    string scope = Util.AzureCloud.PublicCloud.ManagementApiDefaultScope;
    
    // Now we can ask the LINQPad host process to authenticate:
    var authResult = await Util.MSAL.AcquireTokenAsync (azureAuth + tenantID, scope, userHint);
    
  • What happens when you try the code I posted?

  • edited July 2023

    Hi Joe,

    It throws the exception I mentioned.
    The outer exception is "Exception of type 'Microsoft.Graph.Models.ODataErrors.ODataError' was thrown."
    Main error gives

    • Message: Access is denied. Check credentials and try again.

    I'm using your LINQPadTokenCredential class

    My main method is almost identical to your example, adding the GraphServiceClient...

    async Task Main()
    {
    string authEndPoint = Util.AzureCloud.PublicCloud.AuthenticationEndpoint;
    
    string domain = Util.ReadLine("Enter the domain");
    string username = Util.ReadLine("Enter the username");
    
    string tenantID = domain;
    string userHint = $"{username}@{tenantID}";
    
    var credential = new LINQPadTokenCredential(authEndPoint + tenantID, userHint);
    var graphServiceClient = new GraphServiceClient(credential);
    
    try
    {
        var result = await graphServiceClient.Me.Messages.GetAsync((requestConfiguration) =>
        {
        requestConfiguration.QueryParameters.Filter = "importance eq 'high'";
        });
    }
    catch (Microsoft.Graph.Models.ODataErrors.ODataError ex)
    {
        ex.Dump();
    }
    }
    

    My credentials are good. I know this because if I use your example "Authentication with MSAL (interactive + MFA + Azure + OAuth).linq", and paste the token received into https://jwt.ms, I get a good response.

  • Are you confident that the config on the Azure end is set up correctly to allow these credentials?

  • I should have asked this question a different way, I still have a lot to learn about Azure AD, Auth and Graph

    I can create a GraphServiceClient using a DeviceCodeCredential (Azure.Identity) and setting user scopes. To use this method I also need to register an App in Azure AD. This gives me a clientId and tenantId that I can use when instantiating the GraphServiceClient.

    Using the LinqPad MSAL method, do I need to create the App in Azure Id, and how do I integrate the tenantId, clientId and scopes into the LinqPad MSAL method ?

    My preference is to be able to access the Graph ".Me" methods (ie: userClient.Me.MailFolders["Inbox"].Messages) without needing to register an App in Azure AD, which is what I figured the LinqPad MSAL method gave me.

  • edited February 11

    I found the time to come back to this on the weekend.

    I wanted to authenticate with AzureAD and send an email using Microsoft Graph. I figured LinqPads new LINQPadTokenCredential would make this a breeze for me.

    In the end, I resolved that what I was trying to do was impossible using the LINQPadTokenCredential method, so I used the traditional method.

    Reasons Why:

    Limited Scopes available from Util.AzureCloud.PublicCloud
    I'm targeting a "Mail.Send" scope. It wasn't clear to me how I could create my own scope in Util.MSAL.AcquireTokenAsync. Using "Mail.Send", "https://graph.microsoft.com/.default" or a blank scope worked.

    Needed to use a ClientId (AD App Regisgration)
    I figured that I should be able to use LINQPadTokenCredential without having to create an App Registration in Azure AD. In the end, the easiest method was to create an App Registration, but there's no need for a secret using the method I used. It's sending as the logged user, not on behalf of the user.

    **Set API Permissions, in the App Registration **
    Mail.Send (from Microsoft Graph) must be set as in API Permission.

    Needed a Redirect URL
    Specify a redirect url, for LinqPad (or for a Desktop App), that's https://login.microsoftonline.com/common/oauth2/nativeclient

    using Azure.Identity;
    using Microsoft.Graph;
    async void Main()
    {
    
        var tenantId = "xxx" ; // From the App Registration 
        var clientId = "xxx"; // From the App Registration 
    
        var options = new InteractiveBrowserCredentialOptions
        {
            AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
            ClientId = clientId,
            TenantId = tenantId,
            RedirectUri = new Uri("https://login.microsoftonline.com/common/oauth2/nativeclient")
        };
    
    
    // for mail.send any of the following scopes worked, I found that if you’re doing Mail.ReadWrite, then I need to use the second method, specifying the additional scopes
        var scopes = new[] { "" };
    //  var scopes = new[] { "Mail.Send" };
    //  var scopes = new[] { "https://graph.microsoft.com/.default" };
    
    
        var credential = new InteractiveBrowserCredential(options);
        var graphClient = new GraphServiceClient(credential, scopes);
    
        var subject = $"Test email, send {DateTime.Now.ToString("s")}";
        var body = $"Email Message . Device: {Environment.MachineName}. User: {Environment.UserName}.";
    
    
        var message = new Message
        {
            Subject = subject,
            Body = new ItemBody
            {
                ContentType = BodyType.Html,
                Content = body
            },
            ToRecipients = new List<Recipient>()
        {
            new Recipient { EmailAddress = new EmailAddress { Address = "test@example.com" }}
        }
        };
    
    
        Microsoft.Graph.Me.SendMail
            .SendMailPostRequestBody requestbody = new()
        {
            Message = message,
            SaveToSentItems = true // or false
        };
    
        await graphClient.Me.SendMail.PostAsync(requestbody);
    
    }
    
  • Thanks for the info.

    You can specify scopes and a client ID in the Util.MSAL.AcquireTokenAsync method. Have you tried the following:

    class LINQPadTokenCredential : TokenCredential
    {
        public readonly string Authority, UserIDHint;
    
        public LINQPadTokenCredential (string authority, string userIDHint) => (Authority, UserIDHint) = (authority, userIDHint);
    
        public override AccessToken GetToken (TokenRequestContext requestContext, CancellationToken cancellationToken)
            => GetTokenAsync (requestContext, cancellationToken).Result;
    
        public override async ValueTask<AccessToken> GetTokenAsync (TokenRequestContext requestContext,
                                                                    CancellationToken cancelToken)
        {
            // Call LINQPad's AcquireTokenAsync method to authenticate interactively, and cache token in the LINQPad GUI.
            var auth = await Util.MSAL.AcquireTokenAsync (
                Authority,
                ["user.read", "mail.read", "mail.send"],
                UserIDHint,
                "<Your client ID>").ConfigureAwait (false);
    
            return new AccessToken (auth.AccessToken, auth.ExpiresOn);
        }
    }
    
  • Thanks Joe,
    Yes, that worked, and taught me a lot about MSAL in the process.
    Paul

Sign In or Register to comment.