Search code examples
c#microsoft-graph-apiazure-ad-graph-api

How to assign license in Microsoft Graph API version 5.19 c#?


How to assign license in Microsoft Graph API version 5.19 c#?

When I searched online, I couldn't find a method that I could use on version 5 or higher.


Solution

  • When you try to upgrade to v5 this library has a breaking changes from this article https://github.com/microsoftgraph/msgraph-sdk-dotnet/blob/dev/docs/upgrade-to-v5.md

    The first step you need to get token like this

    var interactiveBrowserCredential = new InteractiveBrowserCredential(interactiveBrowserCredentialOptions);
    var graphServiceClient = new GraphServiceClient(interactiveBrowserCredential);
    

    or like custom authentication flows can be done creating an implementation of IAccessTokenProvider

    public class TokenProvider : IAccessTokenProvider
    {
        public Task<string> GetAuthorizationTokenAsync(Uri uri, Dictionary<string, object> additionalAuthenticationContext = default,
            CancellationToken cancellationToken = default)
        {
            var token = "token";
            // get the token and return it in your own way
            return Task.FromResult(token);
        }
    
        public AllowedHostsValidator AllowedHostsValidator { get; }
    }
    

    Creating instance of GraphServiceClientCreating

    var authenticationProvider = new BaseBearerTokenAuthenticationProvider(new YourAuthenticationProvider()); // Authorization method
    var graphClient = new GraphServiceClient(authenticationProvider); 
    

    Insert your licences for removing and adding. Make sure that this data has value in licensesToRemove or licensesToAdd

    var licensesToRemove = new List<Guid?> { };
    var license = new AssignedLicense { SkuId = "yourLicenceId" };
    List<AssignedLicense> licensesToAdd = new List<AssignedLicense> { license };
    

    Make query

    await graphClient.Users["yourUserId"].AssignLicense.PostAsync(new Microsoft.Graph.Users.Item.AssignLicense.AssignLicensePostRequestBody()
        {
            RemoveLicenses = licensesToRemove,
            AddLicenses = licensesToAdd
        });